diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/arithmea/client/widgets/LetterStarWidget.java b/src/arithmea/client/widgets/LetterStarWidget.java index 192ea90..d1840f4 100644 --- a/src/arithmea/client/widgets/LetterStarWidget.java +++ b/src/arithmea/client/widgets/LetterStarWidget.java @@ -1,112 +1,112 @@ package arithmea.client.widgets; import java.util.HashMap; import java.util.Map; import arithmea.shared.gematria.LatinLetter; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.canvas.dom.client.Context2d; import com.google.gwt.canvas.dom.client.CssColor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.VerticalPanel; public class LetterStarWidget extends Composite { private final VerticalPanel panel = new VerticalPanel(); private Canvas canvas; private Map<LatinLetter, Double> xPoints = new HashMap<LatinLetter, Double>(LatinLetter.values().length); private Map<LatinLetter, Double> yPoints = new HashMap<LatinLetter, Double>(LatinLetter.values().length); private Map<LatinLetter, Double> xLetterPos = new HashMap<LatinLetter, Double>(LatinLetter.values().length); private Map<LatinLetter, Double> yLetterPos = new HashMap<LatinLetter, Double>(LatinLetter.values().length); public LetterStarWidget(int width, int height) { canvas = Canvas.createIfSupported(); canvas.setCoordinateSpaceHeight(height); canvas.setCoordinateSpaceWidth(width); initPositions(); drawStar(); panel.add(canvas); initWidget(panel); setStyleName("tree-of-life"); } public Canvas getCanvas() { return canvas; } private void initPositions() { for (LatinLetter ll: LatinLetter.values()) { double angle = (ll.iaValue - 1) * (360.0 / (LatinLetter.values().length)); angle = angle * Math.PI / 180; //radians to degree double x = canvas.getCoordinateSpaceWidth() / 2 + ((Math.sin(angle) * canvas.getCoordinateSpaceWidth() * 0.40)); double y = canvas.getCoordinateSpaceHeight() / 2 - ((Math.cos(angle) * canvas.getCoordinateSpaceHeight() * 0.40)); xPoints.put(ll, x); yPoints.put(ll, y); double xLetter = canvas.getCoordinateSpaceWidth() / 2 + ((Math.sin(angle) * canvas.getCoordinateSpaceWidth() * 0.44) -4); double yLetter = canvas.getCoordinateSpaceHeight() / 2 - ((Math.cos(angle) * canvas.getCoordinateSpaceHeight() * 0.44) -4); xLetterPos.put(ll, xLetter); yLetterPos.put(ll, yLetter); } } private void drawStar() { Context2d ctx = canvas.getContext2d(); //reset content ctx.clearRect(0, 0, canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight()); ctx.beginPath(); ctx.setStrokeStyle(CssColor.make("#FFFFFF")); ctx.setFillStyle(CssColor.make("#FFFFFF")); ctx.setLineWidth(1); //draw circle - ctx.arc(canvas.getCoordinateSpaceWidth() / 2, canvas.getCoordinateSpaceHeight() / 2, canvas.getCoordinateSpaceWidth() * 0.4, 0, 360); + ctx.arc(canvas.getCoordinateSpaceWidth() / 2, canvas.getCoordinateSpaceHeight() / 2, canvas.getCoordinateSpaceWidth() * 0.4, 0, 360 * Math.PI / 180); //draw letters for (LatinLetter ll: LatinLetter.values()) { ctx.fillText(ll.name(), xLetterPos.get(ll), yLetterPos.get(ll)); } ctx.closePath(); ctx.stroke(); } public void setWord(String word) { drawStar(); if (word.length() <= 1) { return; } for (int i = 0; i < word.length() -1; i++) { String letter = word.substring(i, i+1); String nextLetter = word.substring(i+1, i+2); LatinLetter current = LatinLetter.valueOf(letter); LatinLetter next = LatinLetter.valueOf(nextLetter); if (next != null && current != null) { drawLine(xPoints.get(current), yPoints.get(current), xPoints.get(next), yPoints.get(next)); } } } private void drawLine(double startX, double startY, double endX, double endY) { canvas.getContext2d().setStrokeStyle(CssColor.make("#FFFFFF")); canvas.getContext2d().setLineWidth(3); canvas.getContext2d().beginPath(); canvas.getContext2d().moveTo(startX, startY); canvas.getContext2d().lineTo(endX, endY); canvas.getContext2d().closePath(); canvas.getContext2d().stroke(); } }
true
true
private void drawStar() { Context2d ctx = canvas.getContext2d(); //reset content ctx.clearRect(0, 0, canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight()); ctx.beginPath(); ctx.setStrokeStyle(CssColor.make("#FFFFFF")); ctx.setFillStyle(CssColor.make("#FFFFFF")); ctx.setLineWidth(1); //draw circle ctx.arc(canvas.getCoordinateSpaceWidth() / 2, canvas.getCoordinateSpaceHeight() / 2, canvas.getCoordinateSpaceWidth() * 0.4, 0, 360); //draw letters for (LatinLetter ll: LatinLetter.values()) { ctx.fillText(ll.name(), xLetterPos.get(ll), yLetterPos.get(ll)); } ctx.closePath(); ctx.stroke(); }
private void drawStar() { Context2d ctx = canvas.getContext2d(); //reset content ctx.clearRect(0, 0, canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight()); ctx.beginPath(); ctx.setStrokeStyle(CssColor.make("#FFFFFF")); ctx.setFillStyle(CssColor.make("#FFFFFF")); ctx.setLineWidth(1); //draw circle ctx.arc(canvas.getCoordinateSpaceWidth() / 2, canvas.getCoordinateSpaceHeight() / 2, canvas.getCoordinateSpaceWidth() * 0.4, 0, 360 * Math.PI / 180); //draw letters for (LatinLetter ll: LatinLetter.values()) { ctx.fillText(ll.name(), xLetterPos.get(ll), yLetterPos.get(ll)); } ctx.closePath(); ctx.stroke(); }
diff --git a/src/main/java/com/dc2f/technologyplayground/modeshape/FileSystemUtils.java b/src/main/java/com/dc2f/technologyplayground/modeshape/FileSystemUtils.java index 32c07b6..c707f9c 100644 --- a/src/main/java/com/dc2f/technologyplayground/modeshape/FileSystemUtils.java +++ b/src/main/java/com/dc2f/technologyplayground/modeshape/FileSystemUtils.java @@ -1,27 +1,27 @@ package com.dc2f.technologyplayground.modeshape; import java.io.File; import javax.jcr.Node; public class FileSystemUtils { private FileSystemUtils() { } - FileSystemUtils getInstance() { + public static FileSystemUtils getInstance() { return null; } /** * imports given rootFolder recursively into baseNode of repository. * e.g. rootFolder(/etc) baseNode(/blah) -> /etc/passwd == /blah/passwd * * If a file exists, it will be overwritten. * * @param rootFolder root folder from where to import * @param baseNode import relative paths from rootFolder into the repository starting at baseNode */ void load(File rootFolder, Node baseNode) { } }
true
true
FileSystemUtils getInstance() { return null; }
public static FileSystemUtils getInstance() { return null; }
diff --git a/src/test/java/org/apache/ibatis/logging/jdbc/ResultSetLoggerTest.java b/src/test/java/org/apache/ibatis/logging/jdbc/ResultSetLoggerTest.java index 7dc147032d..409030e084 100644 --- a/src/test/java/org/apache/ibatis/logging/jdbc/ResultSetLoggerTest.java +++ b/src/test/java/org/apache/ibatis/logging/jdbc/ResultSetLoggerTest.java @@ -1,71 +1,71 @@ /* * Copyright 2009-2013 The MyBatis Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.logging.jdbc; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.jdbc.ResultSetLogger; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class ResultSetLoggerTest { @Mock private ResultSet rs; @Mock private Log log; @Mock private ResultSetMetaData metaData; public void setup(int type) throws SQLException { when(rs.next()).thenReturn(true); when(rs.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnType(1)).thenReturn(type); - when(metaData.getColumnName(1)).thenReturn("ColumnName"); + when(metaData.getColumnLabel(1)).thenReturn("ColumnName"); when(rs.getString(1)).thenReturn("value"); when(log.isTraceEnabled()).thenReturn(true); ResultSet resultSet = ResultSetLogger.newInstance(rs, log); resultSet.next(); } @Test public void shouldNotPrintBlobs() throws SQLException { setup(Types.LONGNVARCHAR); verify(log).trace("<== Columns: ColumnName"); verify(log).trace("<== Row: <<BLOB>>"); } @Test public void shouldPrintVarchars() throws SQLException { setup(Types.VARCHAR); verify(log).trace("<== Columns: ColumnName"); verify(log).trace("<== Row: value"); } }
true
true
public void setup(int type) throws SQLException { when(rs.next()).thenReturn(true); when(rs.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnType(1)).thenReturn(type); when(metaData.getColumnName(1)).thenReturn("ColumnName"); when(rs.getString(1)).thenReturn("value"); when(log.isTraceEnabled()).thenReturn(true); ResultSet resultSet = ResultSetLogger.newInstance(rs, log); resultSet.next(); }
public void setup(int type) throws SQLException { when(rs.next()).thenReturn(true); when(rs.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnType(1)).thenReturn(type); when(metaData.getColumnLabel(1)).thenReturn("ColumnName"); when(rs.getString(1)).thenReturn("value"); when(log.isTraceEnabled()).thenReturn(true); ResultSet resultSet = ResultSetLogger.newInstance(rs, log); resultSet.next(); }
diff --git a/vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/applets/texteditor/TextEditor.java b/vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/applets/texteditor/TextEditor.java index ce22e639..ed7c66e1 100644 --- a/vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/applets/texteditor/TextEditor.java +++ b/vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/applets/texteditor/TextEditor.java @@ -1,125 +1,125 @@ package hr.fer.zemris.vhdllab.applets.texteditor; import hr.fer.zemris.vhdllab.entity.File; import hr.fer.zemris.vhdllab.platform.manager.editor.impl.AbstractEditor; import java.awt.Color; import java.io.PrintWriter; import java.io.StringWriter; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JTextPane; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import org.springframework.binding.value.CommitTrigger; import org.springframework.richclient.text.TextComponentPopup; public class TextEditor extends AbstractEditor implements DocumentListener, CaretListener { private JTextPane textPane; private CommitTrigger commitTrigger; private Object highlighted; @Override protected JComponent doInitWithoutData() { textPane = new JTextPane(); textPane.getDocument().addDocumentListener(this); textPane.addCaretListener(this); commitTrigger = new CommitTrigger(); TextComponentPopup.attachPopup(textPane, commitTrigger); return textPane; } @Override protected void doInitWithData(File f) { textPane.setText(f.getData()); commitTrigger.commit(); } @Override protected String getData() { return textPane.getText(); } @Override protected void doDispose() { } @Override public void setEditable(boolean flag) { textPane.setEditable(flag); } @Override public void highlightLine(int line) { int caret = textPane.getCaretPosition(); Highlighter h = textPane.getHighlighter(); h.removeAllHighlights(); String content = textPane.getText(); textPane.setCaretPosition(caret); int pos = 0; line--; - while (line != 0) { + while (line > 0) { pos = content.indexOf('\n', pos) + 1; line--; } int last = content.indexOf('\n', pos) + 1; if (last == 0) { last = content.length(); } try { highlighted = h.addHighlight(pos, last, new DefaultHighlighter.DefaultHighlightPainter(new Color( 180, 210, 238))); } catch (BadLocationException e) { e.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); JOptionPane.showMessageDialog(null, sw.toString()); } } // // DocumentListener implementation // @Override public void changedUpdate(DocumentEvent e) { setModified(true); } @Override public void insertUpdate(DocumentEvent e) { setModified(true); } @Override public void removeUpdate(DocumentEvent e) { setModified(true); } // // CaretListener implementation // @Override public void caretUpdate(CaretEvent e) { if (highlighted != null) { textPane.getHighlighter().removeHighlight(highlighted); highlighted = null; } } }
true
true
public void highlightLine(int line) { int caret = textPane.getCaretPosition(); Highlighter h = textPane.getHighlighter(); h.removeAllHighlights(); String content = textPane.getText(); textPane.setCaretPosition(caret); int pos = 0; line--; while (line != 0) { pos = content.indexOf('\n', pos) + 1; line--; } int last = content.indexOf('\n', pos) + 1; if (last == 0) { last = content.length(); } try { highlighted = h.addHighlight(pos, last, new DefaultHighlighter.DefaultHighlightPainter(new Color( 180, 210, 238))); } catch (BadLocationException e) { e.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); JOptionPane.showMessageDialog(null, sw.toString()); } }
public void highlightLine(int line) { int caret = textPane.getCaretPosition(); Highlighter h = textPane.getHighlighter(); h.removeAllHighlights(); String content = textPane.getText(); textPane.setCaretPosition(caret); int pos = 0; line--; while (line > 0) { pos = content.indexOf('\n', pos) + 1; line--; } int last = content.indexOf('\n', pos) + 1; if (last == 0) { last = content.length(); } try { highlighted = h.addHighlight(pos, last, new DefaultHighlighter.DefaultHighlightPainter(new Color( 180, 210, 238))); } catch (BadLocationException e) { e.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); JOptionPane.showMessageDialog(null, sw.toString()); } }
diff --git a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java index 1b1707e25..b2174a04a 100644 --- a/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java +++ b/gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/DefaultCommandModule.java @@ -1,60 +1,60 @@ // Copyright (C) 2009 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.sshd.commands; import com.google.gerrit.sshd.CommandModule; import com.google.gerrit.sshd.CommandName; import com.google.gerrit.sshd.Commands; import com.google.gerrit.sshd.DispatchCommandProvider; import com.google.gerrit.sshd.SuExec; /** Register the basic commands any Gerrit server should support. */ public class DefaultCommandModule extends CommandModule { @Override protected void configure() { final CommandName git = Commands.named("git"); final CommandName gerrit = Commands.named("gerrit"); // The following commands can be ran on a server in either Master or Slave // mode. If a command should only be used on a server in one mode, but not // both, it should be bound in both MasterCommandModule and // SlaveCommandModule. command(gerrit).toProvider(new DispatchCommandProvider(gerrit)); command(gerrit, "flush-caches").to(AdminFlushCaches.class); command(gerrit, "ls-projects").to(ListProjects.class); command(gerrit, "show-caches").to(AdminShowCaches.class); command(gerrit, "show-connections").to(AdminShowConnections.class); command(gerrit, "show-queue").to(AdminShowQueue.class); command(gerrit, "stream-events").to(StreamEvents.class); command(git).toProvider(new DispatchCommandProvider(git)); command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack")); command(git, "upload-pack").to(Upload.class); - command("ps").to(AdminShowCaches.class); + command("ps").to(AdminShowQueue.class); command("kill").to(AdminKill.class); command("scp").to(ScpCommand.class); // Honor the legacy hyphenated forms as aliases for the non-hyphenated forms // command("git-upload-pack").to(Commands.key(git, "upload-pack")); command("git-receive-pack").to(Commands.key(git, "receive-pack")); command("gerrit-receive-pack").to(Commands.key(git, "receive-pack")); command("suexec").to(SuExec.class); } }
true
true
protected void configure() { final CommandName git = Commands.named("git"); final CommandName gerrit = Commands.named("gerrit"); // The following commands can be ran on a server in either Master or Slave // mode. If a command should only be used on a server in one mode, but not // both, it should be bound in both MasterCommandModule and // SlaveCommandModule. command(gerrit).toProvider(new DispatchCommandProvider(gerrit)); command(gerrit, "flush-caches").to(AdminFlushCaches.class); command(gerrit, "ls-projects").to(ListProjects.class); command(gerrit, "show-caches").to(AdminShowCaches.class); command(gerrit, "show-connections").to(AdminShowConnections.class); command(gerrit, "show-queue").to(AdminShowQueue.class); command(gerrit, "stream-events").to(StreamEvents.class); command(git).toProvider(new DispatchCommandProvider(git)); command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack")); command(git, "upload-pack").to(Upload.class); command("ps").to(AdminShowCaches.class); command("kill").to(AdminKill.class); command("scp").to(ScpCommand.class); // Honor the legacy hyphenated forms as aliases for the non-hyphenated forms // command("git-upload-pack").to(Commands.key(git, "upload-pack")); command("git-receive-pack").to(Commands.key(git, "receive-pack")); command("gerrit-receive-pack").to(Commands.key(git, "receive-pack")); command("suexec").to(SuExec.class); }
protected void configure() { final CommandName git = Commands.named("git"); final CommandName gerrit = Commands.named("gerrit"); // The following commands can be ran on a server in either Master or Slave // mode. If a command should only be used on a server in one mode, but not // both, it should be bound in both MasterCommandModule and // SlaveCommandModule. command(gerrit).toProvider(new DispatchCommandProvider(gerrit)); command(gerrit, "flush-caches").to(AdminFlushCaches.class); command(gerrit, "ls-projects").to(ListProjects.class); command(gerrit, "show-caches").to(AdminShowCaches.class); command(gerrit, "show-connections").to(AdminShowConnections.class); command(gerrit, "show-queue").to(AdminShowQueue.class); command(gerrit, "stream-events").to(StreamEvents.class); command(git).toProvider(new DispatchCommandProvider(git)); command(git, "receive-pack").to(Commands.key(gerrit, "receive-pack")); command(git, "upload-pack").to(Upload.class); command("ps").to(AdminShowQueue.class); command("kill").to(AdminKill.class); command("scp").to(ScpCommand.class); // Honor the legacy hyphenated forms as aliases for the non-hyphenated forms // command("git-upload-pack").to(Commands.key(git, "upload-pack")); command("git-receive-pack").to(Commands.key(git, "receive-pack")); command("gerrit-receive-pack").to(Commands.key(git, "receive-pack")); command("suexec").to(SuExec.class); }
diff --git a/haw/ai/rn/client/Application.java b/haw/ai/rn/client/Application.java index 6988894..bce3ea0 100644 --- a/haw/ai/rn/client/Application.java +++ b/haw/ai/rn/client/Application.java @@ -1,13 +1,14 @@ package haw.ai.rn.client; public class Application { public static void main(String[] args) { System.out.println("Start client"); final Controller controller = new Controller(); - controller.setView(new Chat(controller)); + final Chat chat = new Chat(controller); + controller.setView(chat); controller.run(); System.out.println("Stopping client"); } }
true
true
public static void main(String[] args) { System.out.println("Start client"); final Controller controller = new Controller(); controller.setView(new Chat(controller)); controller.run(); System.out.println("Stopping client"); }
public static void main(String[] args) { System.out.println("Start client"); final Controller controller = new Controller(); final Chat chat = new Chat(controller); controller.setView(chat); controller.run(); System.out.println("Stopping client"); }
diff --git a/src/com/dunnkers/pathmaker/util/CodeFormat.java b/src/com/dunnkers/pathmaker/util/CodeFormat.java index 7b60119..1da3745 100644 --- a/src/com/dunnkers/pathmaker/util/CodeFormat.java +++ b/src/com/dunnkers/pathmaker/util/CodeFormat.java @@ -1,123 +1,123 @@ package com.dunnkers.pathmaker.util; import java.awt.Point; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * * @author Dunnkers */ public enum CodeFormat { OSBOT("OSBot", true, WorldMap.OLD_SCHOOL), TRIBOT_OLD_SCHOOL("TRiBot", true, WorldMap.OLD_SCHOOL), TRIBOT_RECENT("TRiBot", true, WorldMap.RECENT), RSBOT("RSBot", true, WorldMap.RECENT); private final String name; private final List<WorldMap> worldMaps; private final boolean enabled; private static final String DEFAULT_TEXT = "Not supported yet!"; private CodeFormat(String name, boolean enabled, final WorldMap... worldMaps) { this.name = name; this.worldMaps = Arrays.asList(worldMaps); this.enabled = enabled; } public String getName() { return name; } public boolean isEnabled() { return enabled; } public String getCode(final ArrayList<Point> tileArray, final TileMode tileMode) { StringBuilder output = new StringBuilder(200); /* * TODO convert to tile here, and store tile array as mouse points: more * efficient in drawing paint */ switch (tileMode) { case PATH: output.append(getPath()); output.append(getFormattedTiles(tileArray)); - output.append("\t);"); + output.append("\t};"); break; case AREA: output.append(getArea(tileArray)); switch (this) { default: output.append(getFormattedTiles(tileArray)); break; } output.append("\t);"); break; default: output.append(DEFAULT_TEXT); break; } return output.toString(); } private String getPath() { switch (this) { case RSBOT: return "\tprivate final Tile[] path = new Tile[] {\n"; case OSBOT: return "\tprivate final Position[] path = new Position[] {\n"; case TRIBOT_OLD_SCHOOL: return "\tprivate final RSTile[] path = new RSTile[] {\n"; default: return DEFAULT_TEXT; } } private String getArea(final ArrayList<Point> tileArray) { switch (this) { case RSBOT: case OSBOT: return "\tprivate final Area area = new Area(\n"; case TRIBOT_OLD_SCHOOL: return "\tprivate final RSArea area = new RSArea(\n"; default: return DEFAULT_TEXT; } } private String getTile(final Point point) { return String.format(getTileFormat(), point.x, point.y); } private String getTileFormat() { switch (this) { case RSBOT: return "new Tile(%s, %s, 0)"; case OSBOT: return "new Position(%s, %s, 0)"; case TRIBOT_OLD_SCHOOL: return "new RSTile(%s, %s, 0)"; default: return DEFAULT_TEXT; } } private String getFormattedTiles(final ArrayList<Point> tileArray) { StringBuilder output = new StringBuilder(200); for (int i = 0; i < tileArray.size(); i++) { final boolean lastTile = tileArray.size() - 1 == i; output.append("\t\t\t" + getTile(tileArray.get(i)) + (lastTile ? "" : ",") + "\n"); } return output.toString(); } public List<WorldMap> getWorldMaps() { return worldMaps; } }
true
true
public String getCode(final ArrayList<Point> tileArray, final TileMode tileMode) { StringBuilder output = new StringBuilder(200); /* * TODO convert to tile here, and store tile array as mouse points: more * efficient in drawing paint */ switch (tileMode) { case PATH: output.append(getPath()); output.append(getFormattedTiles(tileArray)); output.append("\t);"); break; case AREA: output.append(getArea(tileArray)); switch (this) { default: output.append(getFormattedTiles(tileArray)); break; } output.append("\t);"); break; default: output.append(DEFAULT_TEXT); break; } return output.toString(); }
public String getCode(final ArrayList<Point> tileArray, final TileMode tileMode) { StringBuilder output = new StringBuilder(200); /* * TODO convert to tile here, and store tile array as mouse points: more * efficient in drawing paint */ switch (tileMode) { case PATH: output.append(getPath()); output.append(getFormattedTiles(tileArray)); output.append("\t};"); break; case AREA: output.append(getArea(tileArray)); switch (this) { default: output.append(getFormattedTiles(tileArray)); break; } output.append("\t);"); break; default: output.append(DEFAULT_TEXT); break; } return output.toString(); }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/SynchronizeQueryJob.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/SynchronizeQueryJob.java index 5f79831e4..320bcd44d 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/SynchronizeQueryJob.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/SynchronizeQueryJob.java @@ -1,256 +1,256 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.tasks.ui; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages; import org.eclipse.mylyn.monitor.core.DateUtil; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.QueryHitCollector; import org.eclipse.mylyn.tasks.core.TaskList; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.IProgressConstants; /** * Not API. * * @author Mik Kersten * @author Rob Elves * @author Steffen Pingel */ class SynchronizeQueryJob extends Job { private final AbstractRepositoryConnector connector; private final TaskRepository repository; private final Set<AbstractRepositoryQuery> queries; private final TaskList taskList; private boolean synchronizeChangedTasks; private boolean forced = false; private HashSet<AbstractTask> tasksToBeSynchronized = new HashSet<AbstractTask>(); private boolean fullSynchronization = true; public SynchronizeQueryJob(AbstractRepositoryConnector connector, TaskRepository repository, Set<AbstractRepositoryQuery> queries, TaskList taskList) { super("Synchronizing queries for " + repository.getRepositoryLabel()); this.connector = connector; this.repository = repository; this.queries = queries; this.taskList = taskList; } public void setSynchronizeChangedTasks(boolean synchronizeChangedTasks) { this.synchronizeChangedTasks = synchronizeChangedTasks; } /** * @since 2.2 */ public boolean isFullSynchronization() { return fullSynchronization; } /** * @since 2.2 */ public void setFullSynchronization(boolean fullSynchronization) { this.fullSynchronization = fullSynchronization; } /** * Returns true, if synchronization was triggered manually and not by an automatic background job. */ public boolean isForced() { return forced; } /** * Indicates a manual synchronization (User initiated). If set to true, a dialog will be displayed in case of * errors. Any tasks with missing data will be retrieved. */ public void setForced(boolean forced) { this.forced = forced; } @Override protected IStatus run(IProgressMonitor monitor) { try { monitor.beginTask("Synchronizing " + queries.size() + " queries", 20 + queries.size() * 10 + 40); Set<AbstractTask> allTasks = Collections.unmodifiableSet(taskList.getRepositoryTasks(repository.getUrl())); for (AbstractTask task : allTasks) { - if (task.isStale()) { - StatusHandler.log(new Status(IStatus.WARNING, TasksUiPlugin.ID_PLUGIN, "Reseting flag on stale task: " + task.getTaskKey() + " [" + task.getRepositoryUrl() + "]")); - } +// if (task.isStale()) { +// StatusHandler.log(new Status(IStatus.WARNING, TasksUiPlugin.ID_PLUGIN, "Reseting flag on stale task: " + task.getTaskKey() + " [" + task.getRepositoryUrl() + "]")); +// } task.setStale(false); } // check if the repository has changed at all and have the connector mark tasks that need synchronization if (isFullSynchronization()) { try { monitor.subTask("Checking for changed tasks"); boolean hasChangedOrNew = connector.markStaleTasks(repository, allTasks, new SubProgressMonitor( monitor, 20)); if (!hasChangedOrNew && !forced) { updateQueryStatus(null); return Status.OK_STATUS; } } catch (CoreException e) { // synchronization is unlikely to succeed, inform user and exit updateQueryStatus(e.getStatus()); return Status.OK_STATUS; } } // synchronize queries, tasks changed within query are added to set of tasks to be synchronized int n = 0; for (AbstractRepositoryQuery repositoryQuery : queries) { repositoryQuery.setSynchronizationStatus(null); monitor.setTaskName("Synchronizing " + ++n + "/" + queries.size() + ": " + repositoryQuery.getSummary()); synchronizeQuery(repositoryQuery, new SubProgressMonitor(monitor, 10)); repositoryQuery.setSynchronizing(false); taskList.notifyContainersUpdated(Collections.singleton(repositoryQuery)); } // for background synchronizations all changed tasks are synchronized including the ones that are not part of a query if (!forced) { for (AbstractTask task : allTasks) { if (task.isStale()) { tasksToBeSynchronized.add(task); task.setSynchronizing(true); } } } // synchronize tasks that were marked by the connector if (!tasksToBeSynchronized.isEmpty()) { monitor.setTaskName("Synchronizing " + tasksToBeSynchronized.size() + " changed tasks"); SynchronizeTaskJob job = new SynchronizeTaskJob(connector, tasksToBeSynchronized); job.setForced(forced); job.run(new SubProgressMonitor(monitor, 40)); if (Platform.isRunning() && !(TasksUiPlugin.getRepositoryManager() == null) && isFullSynchronization()) { TasksUiPlugin.getRepositoryManager().setSynchronizationTime(repository, connector.getSynchronizationTimestamp(repository, tasksToBeSynchronized), TasksUiPlugin.getDefault().getRepositoriesFilePath()); } } taskList.notifyContainersUpdated(null); return Status.OK_STATUS; } catch (OperationCanceledException e) { return Status.CANCEL_STATUS; } finally { monitor.done(); } } private void updateQueryStatus(final IStatus status) { for (AbstractRepositoryQuery repositoryQuery : queries) { repositoryQuery.setSynchronizationStatus(status); repositoryQuery.setSynchronizing(false); } taskList.notifyContainersUpdated(queries); if (status != null && isForced()) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { StatusHandler.displayStatus("Query Synchronization Failed", status); } }); } } private void synchronizeQuery(AbstractRepositoryQuery repositoryQuery, IProgressMonitor monitor) { setProperty(IProgressConstants.ICON_PROPERTY, TasksUiImages.REPOSITORY_SYNCHRONIZE); QueryHitCollector collector = new QueryHitCollector(new TaskFactory(repository, true, false)); final IStatus resultingStatus = connector.performQuery(repositoryQuery, repository, monitor, collector); if (resultingStatus.getSeverity() == IStatus.CANCEL) { // do nothing } else if (resultingStatus.isOK()) { if (collector.getTasks().size() >= QueryHitCollector.MAX_HITS) { StatusHandler.log(new Status(IStatus.WARNING, TasksUiPlugin.ID_PLUGIN, QueryHitCollector.MAX_HITS_REACHED + "\n" + repositoryQuery.getSummary())); } // bug#195485 - tasks dissappear form tasklist for (AbstractTask removedTask : repositoryQuery.getChildren()) { taskList.removeFromQuery(repositoryQuery, removedTask); } for (AbstractTask hit : collector.getTasks()) { AbstractTask task = taskList.getTask(hit.getHandleIdentifier()); if (task != null) { // update the existing task from the query hit boolean changed = connector.updateTaskFromQueryHit(repository, task, hit); if (changed && !task.isStale() && task.getSynchronizationState() == RepositoryTaskSyncState.SYNCHRONIZED) { // set incoming marker for web tasks task.setSynchronizationState(RepositoryTaskSyncState.INCOMING); } task.setSynchronizationStatus(null); task.setSynchronizing(false); } else { // new tasks are marked stale by default task = hit; task.setStale(true); task.setSynchronizationState(RepositoryTaskSyncState.INCOMING); } taskList.addTask(task, repositoryQuery); if (synchronizeChangedTasks && task.isStale()) { tasksToBeSynchronized.add(task); task.setSynchronizing(true); } } repositoryQuery.setLastSynchronizedStamp(DateUtil.getFormattedDate(new Date(), "MMM d, H:mm:ss")); } else { repositoryQuery.setSynchronizationStatus(resultingStatus); if (isForced()) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { StatusHandler.displayStatus("Query Synchronization Failed", resultingStatus); } }); } } } }
true
true
protected IStatus run(IProgressMonitor monitor) { try { monitor.beginTask("Synchronizing " + queries.size() + " queries", 20 + queries.size() * 10 + 40); Set<AbstractTask> allTasks = Collections.unmodifiableSet(taskList.getRepositoryTasks(repository.getUrl())); for (AbstractTask task : allTasks) { if (task.isStale()) { StatusHandler.log(new Status(IStatus.WARNING, TasksUiPlugin.ID_PLUGIN, "Reseting flag on stale task: " + task.getTaskKey() + " [" + task.getRepositoryUrl() + "]")); } task.setStale(false); } // check if the repository has changed at all and have the connector mark tasks that need synchronization if (isFullSynchronization()) { try { monitor.subTask("Checking for changed tasks"); boolean hasChangedOrNew = connector.markStaleTasks(repository, allTasks, new SubProgressMonitor( monitor, 20)); if (!hasChangedOrNew && !forced) { updateQueryStatus(null); return Status.OK_STATUS; } } catch (CoreException e) { // synchronization is unlikely to succeed, inform user and exit updateQueryStatus(e.getStatus()); return Status.OK_STATUS; } } // synchronize queries, tasks changed within query are added to set of tasks to be synchronized int n = 0; for (AbstractRepositoryQuery repositoryQuery : queries) { repositoryQuery.setSynchronizationStatus(null); monitor.setTaskName("Synchronizing " + ++n + "/" + queries.size() + ": " + repositoryQuery.getSummary()); synchronizeQuery(repositoryQuery, new SubProgressMonitor(monitor, 10)); repositoryQuery.setSynchronizing(false); taskList.notifyContainersUpdated(Collections.singleton(repositoryQuery)); } // for background synchronizations all changed tasks are synchronized including the ones that are not part of a query if (!forced) { for (AbstractTask task : allTasks) { if (task.isStale()) { tasksToBeSynchronized.add(task); task.setSynchronizing(true); } } } // synchronize tasks that were marked by the connector if (!tasksToBeSynchronized.isEmpty()) { monitor.setTaskName("Synchronizing " + tasksToBeSynchronized.size() + " changed tasks"); SynchronizeTaskJob job = new SynchronizeTaskJob(connector, tasksToBeSynchronized); job.setForced(forced); job.run(new SubProgressMonitor(monitor, 40)); if (Platform.isRunning() && !(TasksUiPlugin.getRepositoryManager() == null) && isFullSynchronization()) { TasksUiPlugin.getRepositoryManager().setSynchronizationTime(repository, connector.getSynchronizationTimestamp(repository, tasksToBeSynchronized), TasksUiPlugin.getDefault().getRepositoriesFilePath()); } } taskList.notifyContainersUpdated(null); return Status.OK_STATUS; } catch (OperationCanceledException e) { return Status.CANCEL_STATUS; } finally { monitor.done(); } }
protected IStatus run(IProgressMonitor monitor) { try { monitor.beginTask("Synchronizing " + queries.size() + " queries", 20 + queries.size() * 10 + 40); Set<AbstractTask> allTasks = Collections.unmodifiableSet(taskList.getRepositoryTasks(repository.getUrl())); for (AbstractTask task : allTasks) { // if (task.isStale()) { // StatusHandler.log(new Status(IStatus.WARNING, TasksUiPlugin.ID_PLUGIN, "Reseting flag on stale task: " + task.getTaskKey() + " [" + task.getRepositoryUrl() + "]")); // } task.setStale(false); } // check if the repository has changed at all and have the connector mark tasks that need synchronization if (isFullSynchronization()) { try { monitor.subTask("Checking for changed tasks"); boolean hasChangedOrNew = connector.markStaleTasks(repository, allTasks, new SubProgressMonitor( monitor, 20)); if (!hasChangedOrNew && !forced) { updateQueryStatus(null); return Status.OK_STATUS; } } catch (CoreException e) { // synchronization is unlikely to succeed, inform user and exit updateQueryStatus(e.getStatus()); return Status.OK_STATUS; } } // synchronize queries, tasks changed within query are added to set of tasks to be synchronized int n = 0; for (AbstractRepositoryQuery repositoryQuery : queries) { repositoryQuery.setSynchronizationStatus(null); monitor.setTaskName("Synchronizing " + ++n + "/" + queries.size() + ": " + repositoryQuery.getSummary()); synchronizeQuery(repositoryQuery, new SubProgressMonitor(monitor, 10)); repositoryQuery.setSynchronizing(false); taskList.notifyContainersUpdated(Collections.singleton(repositoryQuery)); } // for background synchronizations all changed tasks are synchronized including the ones that are not part of a query if (!forced) { for (AbstractTask task : allTasks) { if (task.isStale()) { tasksToBeSynchronized.add(task); task.setSynchronizing(true); } } } // synchronize tasks that were marked by the connector if (!tasksToBeSynchronized.isEmpty()) { monitor.setTaskName("Synchronizing " + tasksToBeSynchronized.size() + " changed tasks"); SynchronizeTaskJob job = new SynchronizeTaskJob(connector, tasksToBeSynchronized); job.setForced(forced); job.run(new SubProgressMonitor(monitor, 40)); if (Platform.isRunning() && !(TasksUiPlugin.getRepositoryManager() == null) && isFullSynchronization()) { TasksUiPlugin.getRepositoryManager().setSynchronizationTime(repository, connector.getSynchronizationTimestamp(repository, tasksToBeSynchronized), TasksUiPlugin.getDefault().getRepositoriesFilePath()); } } taskList.notifyContainersUpdated(null); return Status.OK_STATUS; } catch (OperationCanceledException e) { return Status.CANCEL_STATUS; } finally { monitor.done(); } }
diff --git a/overwatch/src/overwatch/controllers/VehicleLogic.java b/overwatch/src/overwatch/controllers/VehicleLogic.java index 33d57be..47767c5 100644 --- a/overwatch/src/overwatch/controllers/VehicleLogic.java +++ b/overwatch/src/overwatch/controllers/VehicleLogic.java @@ -1,289 +1,289 @@ package overwatch.controllers; import overwatch.core.Gui; import overwatch.db.*; import overwatch.gui.*; import overwatch.gui.tabs.VehicleTab; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** * Set up the vehicle tab logic * @author John Murphy * @author Lee Coakley * @version 7 */ public class VehicleLogic extends TabController { private final VehicleTab tab; public VehicleLogic( VehicleTab vt ) { this.tab = vt; attachEvents(); } public void respondToTabSelect() { populateList(); } public JPanel getTab() { return tab; } /////////////////////////////////////////////////////////////////////////// // Internals ///////////////////////////////////////////////////////////////////////// private void doNew() { Integer vehicleNo = Vehicles.create(); populateList(); tab.setSelectedItem( vehicleNo ); } private void doSave() { if ( ! tab.areAllFieldsValid()) { Gui.showErrorDialogue( "Invalid Fields", "Can't save: some fields contain invalid data." ); return; } Integer vehicleNo = tab.getSelectedItem(); String vehicleType = tab.type .field.getText(); String pilotName = tab.pilot.field.getText(); Integer pilotNo = Personnel.getNumber( pilotName ); int mods = Database.update( "update Vehicles " + "set name = '" + vehicleType + "', " + " pilot = " + pilotNo + " " + "where vehicleNo = " + vehicleNo + ";" ); if (mods <= 0) { Gui.showErrorDialogue( "Vehicle Deleted", "The vehicle has been deleted by someone else!" ); } populateList(); tab.setSelectedItem( vehicleNo ); } private void doDelete() { Integer vehicleNo = tab.getSelectedItem(); Vehicles.delete( vehicleNo ); populateList(); } private void populateList() { populateFields( null ); tab.setSearchableItems( Database.queryKeyNamePairs( "Vehicles", "vehicleNo", "name", Integer[].class ) ); } private void populateFields(Integer vehicleNo) { if (vehicleNo == null) { tab.setEnableFieldsAndButtons(false); tab.clearFields(); return; } tab.setEnableFieldsAndButtons(true); EnhancedResultSet ers = Database.query( "SELECT vehicleNo, " + " name, " + " pilot " + "FROM Vehicles " + "WHERE vehicleNo = " + vehicleNo + ";" ); if (ers.isEmpty()) { showDeletedError( "vehicle" ); return; } Integer pilot = ers.getElemAs( "pilot", Integer.class ); String pilotName = ""; if (pilot != null) { pilotName = Database.querySingle( String.class, "select loginName " + "from Personnel " + "where personNo = " + pilot + ";" ); } tab.number.field.setText( "" + ers.getElemAs( "vehicleNo", Integer.class )); - tab.type .field.setText( ers.getElemAs( "loginName", String .class )); + tab.type .field.setText( ers.getElemAs( "name", String .class )); tab.pilot .field.setText( pilotName ); } private void attachEvents() { setupTabChangeActions(); setupButtonActions(); setupSelectActions(); setupFieldValidators(); setupPickActions(); } private void setupSelectActions() { tab.addSearchPanelListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { populateFields(tab.getSelectedItem()); } }); } private void setupButtonActions() { tab.addNewListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doNew(); } }); tab.addSaveListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSave(); } }); tab.addDeleteListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doDelete(); } }); } private void setupTabChangeActions() { Gui.getCurrentInstance().addTabSelectNotify(this); } private void setupFieldValidators() { tab.addTypeValidator( new CheckedFieldValidator() { public boolean check( String text ){ return DatabaseConstraints.isValidName( text ); } }); tab.addPilotValidator( new CheckedFieldValidator() { public boolean check( String text ){ return text.isEmpty() || DatabaseConstraints.personExists( text ); } }); } private void setupPickActions() { final PickListener<Integer> pickListener = new PickListener<Integer>() { public void onPick( Integer picked ) { if (picked != null) tab.pilot.field.setText(Personnel.getLoginName(picked)) ; } }; tab.pilot.button.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { new PersonnelPicker( Gui.getCurrentInstance(), pickListener ); } }); } }
true
true
private void populateFields(Integer vehicleNo) { if (vehicleNo == null) { tab.setEnableFieldsAndButtons(false); tab.clearFields(); return; } tab.setEnableFieldsAndButtons(true); EnhancedResultSet ers = Database.query( "SELECT vehicleNo, " + " name, " + " pilot " + "FROM Vehicles " + "WHERE vehicleNo = " + vehicleNo + ";" ); if (ers.isEmpty()) { showDeletedError( "vehicle" ); return; } Integer pilot = ers.getElemAs( "pilot", Integer.class ); String pilotName = ""; if (pilot != null) { pilotName = Database.querySingle( String.class, "select loginName " + "from Personnel " + "where personNo = " + pilot + ";" ); } tab.number.field.setText( "" + ers.getElemAs( "vehicleNo", Integer.class )); tab.type .field.setText( ers.getElemAs( "loginName", String .class )); tab.pilot .field.setText( pilotName ); }
private void populateFields(Integer vehicleNo) { if (vehicleNo == null) { tab.setEnableFieldsAndButtons(false); tab.clearFields(); return; } tab.setEnableFieldsAndButtons(true); EnhancedResultSet ers = Database.query( "SELECT vehicleNo, " + " name, " + " pilot " + "FROM Vehicles " + "WHERE vehicleNo = " + vehicleNo + ";" ); if (ers.isEmpty()) { showDeletedError( "vehicle" ); return; } Integer pilot = ers.getElemAs( "pilot", Integer.class ); String pilotName = ""; if (pilot != null) { pilotName = Database.querySingle( String.class, "select loginName " + "from Personnel " + "where personNo = " + pilot + ";" ); } tab.number.field.setText( "" + ers.getElemAs( "vehicleNo", Integer.class )); tab.type .field.setText( ers.getElemAs( "name", String .class )); tab.pilot .field.setText( pilotName ); }
diff --git a/org/python/modules/operator.java b/org/python/modules/operator.java index 8b6a357e..f79407b5 100644 --- a/org/python/modules/operator.java +++ b/org/python/modules/operator.java @@ -1,176 +1,176 @@ // Copyright � Corporation for National Research Initiatives package org.python.modules; import org.python.core.*; class OperatorFunctions extends PyBuiltinFunctionSet { public OperatorFunctions(String name, int index, int argcount) { super(name, index, argcount, argcount, false, null); } public OperatorFunctions(String name, int index, int minargs, int maxargs) { super(name, index, minargs, maxargs, false, null); } public PyObject __call__(PyObject arg1) { switch (index) { case 10: return arg1.__abs__(); case 11: return arg1.__invert__(); case 12: return arg1.__neg__(); case 13: return arg1.__not__(); case 14: return arg1.__pos__(); case 15: return Py.newBoolean(arg1.__nonzero__()); case 16: return Py.newBoolean(arg1.isCallable()); case 17: return Py.newBoolean(arg1.isMappingType()); case 18: return Py.newBoolean(arg1.isNumberType()); case 19: return Py.newBoolean(arg1.isSequenceType()); default: throw argCountError(1); } } public PyObject __call__(PyObject arg1, PyObject arg2) { switch (index) { case 0: return arg1._add(arg2); case 1: return arg1._and(arg2); case 2: return arg1._div(arg2); case 3: return arg1._lshift(arg2); case 4: return arg1._mod(arg2); case 5: return arg1._mul(arg2); case 6: return arg1._or(arg2); case 7: return arg1._rshift(arg2); case 8: return arg1._sub(arg2); case 9: return arg1._xor(arg2); case 20: return Py.newBoolean(arg1.__contains__(arg2)); case 21: arg1.__delitem__(arg2); return Py.None; case 23: return arg1.__getitem__(arg2); default: throw argCountError(2); } } public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { switch (index) { case 22: arg1.__delslice__(arg2, arg3); return Py.None; case 24: return arg1.__getslice__(arg2, arg3); case 25: arg1.__setitem__(arg2, arg3); return Py.None; default: throw argCountError(3); } } public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { switch (index) { case 26: arg1.__setslice__(arg2, arg3, arg4); return Py.None; default: throw argCountError(4); } } } public class operator implements InitModule { public void initModule(PyObject dict) { dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2)); dict.__setitem__("add", new OperatorFunctions("add", 0, 2)); dict.__setitem__("__concat__", new OperatorFunctions("__concat__", 0, 2)); dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2)); dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2)); dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2)); dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2)); dict.__setitem__("div", new OperatorFunctions("div", 2, 2)); dict.__setitem__("__lshift__", new OperatorFunctions("__lshift__", 3, 2)); dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2)); dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2)); dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2)); dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2)); dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2)); dict.__setitem__("__repeat__", new OperatorFunctions("__repeat__", 5, 2)); dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2)); dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2)); dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2)); dict.__setitem__("__rshift__", new OperatorFunctions("__rshift__", 7, 2)); dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2)); dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2)); dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2)); dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2)); dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2)); dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1)); dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1)); dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1)); dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1)); dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1)); dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1)); dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1)); dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1)); dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1)); dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1)); dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1)); dict.__setitem__("isCallable", new OperatorFunctions("isCallable", 16, 1)); dict.__setitem__("isMappingType", new OperatorFunctions("isMappingType", 17, 1)); dict.__setitem__("isNumberType", new OperatorFunctions("isNumberType", 18, 1)); dict.__setitem__("isSequenceType", new OperatorFunctions("isSequenceType", 19, 1)); dict.__setitem__("contains", new OperatorFunctions("contains", 20, 2)); dict.__setitem__("sequenceIncludes", new OperatorFunctions("sequenceIncludes", 20, 2)); dict.__setitem__("__delitem__", new OperatorFunctions("__delitem__", 21, 2)); dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2)); dict.__setitem__("__delslice__", new OperatorFunctions("__delslice__", 22, 3)); dict.__setitem__("delslice", new OperatorFunctions("delslice", 22, 3)); dict.__setitem__("__getitem__", new OperatorFunctions("__getitem__", 23, 2)); dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2)); dict.__setitem__("__getslice__", new OperatorFunctions("__getslice__", 24, 3)); dict.__setitem__("getslice", new OperatorFunctions("getslice", 24, 3)); dict.__setitem__("__setitem__", new OperatorFunctions("__setitem__", 25, 3)); dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3)); dict.__setitem__("__setslice__", new OperatorFunctions("__setslice__", 26, 4)); dict.__setitem__("setslice", new OperatorFunctions("setslice", 26, 4)); } public static int countOf(PyObject seq, PyObject item) { PyObject tmp; int i = 0; int count = 0; while ((tmp = seq.__finditem__(i++)) != null) { if (item._eq(tmp).__nonzero__()) count++; } return count; } public static int indexOf(PyObject seq, PyObject item) { PyObject tmp; int i = 0; while ((tmp = seq.__finditem__(i++)) != null) { if (item._eq(tmp).__nonzero__()) - return i; + return i - 1; } - return -1; + throw Py.ValueError("sequence.index(x): x not in list"); } }
false
true
{ public void initModule(PyObject dict) { dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2)); dict.__setitem__("add", new OperatorFunctions("add", 0, 2)); dict.__setitem__("__concat__", new OperatorFunctions("__concat__", 0, 2)); dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2)); dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2)); dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2)); dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2)); dict.__setitem__("div", new OperatorFunctions("div", 2, 2)); dict.__setitem__("__lshift__", new OperatorFunctions("__lshift__", 3, 2)); dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2)); dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2)); dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2)); dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2)); dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2)); dict.__setitem__("__repeat__", new OperatorFunctions("__repeat__", 5, 2)); dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2)); dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2)); dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2)); dict.__setitem__("__rshift__", new OperatorFunctions("__rshift__", 7, 2)); dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2)); dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2)); dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2)); dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2)); dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2)); dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1)); dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1)); dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1)); dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1)); dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1)); dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1)); dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1)); dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1)); dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1)); dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1)); dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1)); dict.__setitem__("isCallable", new OperatorFunctions("isCallable", 16, 1)); dict.__setitem__("isMappingType", new OperatorFunctions("isMappingType", 17, 1)); dict.__setitem__("isNumberType", new OperatorFunctions("isNumberType", 18, 1)); dict.__setitem__("isSequenceType", new OperatorFunctions("isSequenceType", 19, 1)); dict.__setitem__("contains", new OperatorFunctions("contains", 20, 2)); dict.__setitem__("sequenceIncludes", new OperatorFunctions("sequenceIncludes", 20, 2)); dict.__setitem__("__delitem__", new OperatorFunctions("__delitem__", 21, 2)); dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2)); dict.__setitem__("__delslice__", new OperatorFunctions("__delslice__", 22, 3)); dict.__setitem__("delslice", new OperatorFunctions("delslice", 22, 3)); dict.__setitem__("__getitem__", new OperatorFunctions("__getitem__", 23, 2)); dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2)); dict.__setitem__("__getslice__", new OperatorFunctions("__getslice__", 24, 3)); dict.__setitem__("getslice", new OperatorFunctions("getslice", 24, 3)); dict.__setitem__("__setitem__", new OperatorFunctions("__setitem__", 25, 3)); dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3)); dict.__setitem__("__setslice__", new OperatorFunctions("__setslice__", 26, 4)); dict.__setitem__("setslice", new OperatorFunctions("setslice", 26, 4)); } public static int countOf(PyObject seq, PyObject item) { PyObject tmp; int i = 0; int count = 0; while ((tmp = seq.__finditem__(i++)) != null) { if (item._eq(tmp).__nonzero__()) count++; } return count; } public static int indexOf(PyObject seq, PyObject item) { PyObject tmp; int i = 0; while ((tmp = seq.__finditem__(i++)) != null) { if (item._eq(tmp).__nonzero__()) return i; } return -1; } }
{ public void initModule(PyObject dict) { dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2)); dict.__setitem__("add", new OperatorFunctions("add", 0, 2)); dict.__setitem__("__concat__", new OperatorFunctions("__concat__", 0, 2)); dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2)); dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2)); dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2)); dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2)); dict.__setitem__("div", new OperatorFunctions("div", 2, 2)); dict.__setitem__("__lshift__", new OperatorFunctions("__lshift__", 3, 2)); dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2)); dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2)); dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2)); dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2)); dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2)); dict.__setitem__("__repeat__", new OperatorFunctions("__repeat__", 5, 2)); dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2)); dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2)); dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2)); dict.__setitem__("__rshift__", new OperatorFunctions("__rshift__", 7, 2)); dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2)); dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2)); dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2)); dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2)); dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2)); dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1)); dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1)); dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1)); dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1)); dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1)); dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1)); dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1)); dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1)); dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1)); dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1)); dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1)); dict.__setitem__("isCallable", new OperatorFunctions("isCallable", 16, 1)); dict.__setitem__("isMappingType", new OperatorFunctions("isMappingType", 17, 1)); dict.__setitem__("isNumberType", new OperatorFunctions("isNumberType", 18, 1)); dict.__setitem__("isSequenceType", new OperatorFunctions("isSequenceType", 19, 1)); dict.__setitem__("contains", new OperatorFunctions("contains", 20, 2)); dict.__setitem__("sequenceIncludes", new OperatorFunctions("sequenceIncludes", 20, 2)); dict.__setitem__("__delitem__", new OperatorFunctions("__delitem__", 21, 2)); dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2)); dict.__setitem__("__delslice__", new OperatorFunctions("__delslice__", 22, 3)); dict.__setitem__("delslice", new OperatorFunctions("delslice", 22, 3)); dict.__setitem__("__getitem__", new OperatorFunctions("__getitem__", 23, 2)); dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2)); dict.__setitem__("__getslice__", new OperatorFunctions("__getslice__", 24, 3)); dict.__setitem__("getslice", new OperatorFunctions("getslice", 24, 3)); dict.__setitem__("__setitem__", new OperatorFunctions("__setitem__", 25, 3)); dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3)); dict.__setitem__("__setslice__", new OperatorFunctions("__setslice__", 26, 4)); dict.__setitem__("setslice", new OperatorFunctions("setslice", 26, 4)); } public static int countOf(PyObject seq, PyObject item) { PyObject tmp; int i = 0; int count = 0; while ((tmp = seq.__finditem__(i++)) != null) { if (item._eq(tmp).__nonzero__()) count++; } return count; } public static int indexOf(PyObject seq, PyObject item) { PyObject tmp; int i = 0; while ((tmp = seq.__finditem__(i++)) != null) { if (item._eq(tmp).__nonzero__()) return i - 1; } throw Py.ValueError("sequence.index(x): x not in list"); } }
diff --git a/java/demo/localcal/src/CalendarController.java b/java/demo/localcal/src/CalendarController.java index 712e8f715..a98889116 100644 --- a/java/demo/localcal/src/CalendarController.java +++ b/java/demo/localcal/src/CalendarController.java @@ -1,405 +1,405 @@ /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import com.sun.media.sound.JavaSoundAudioClip; import java.applet.*; import java.util.*; import java.util.concurrent.*; import java.awt.*; import java.io.*; import java.security.*; import org.json.*; /** * This is the controller for the local calendar application */ public class CalendarController extends Applet { public static final String DBNAME = "LocalCalDB"; private String calid; private String gmtOffset; private String user; private String password; private String startDay; private String endDay; private static PrintStream console; private static final String CONSOLE_FILENAME = "localcal.log"; /** The calendar we're logged in to */ GCalendar calendar; /** Indicates whether we're online or not */ boolean online = true; /** * Log in to the Google Calendar service. * * @param calid * The calendar id. If this is your default Google Calendar, * it's the email address you use to login to Google Calendar, * e.g. "[email protected]". * <p> * If it's not your default calendar, you can get the calendar id * for the calendar you want by doing the following: * <ul> * <li>Go to your Google Calendar page * <li>On the left pane all your calendars are listed. Click on the * drop-down menu for the calendar you want, and choose * "Calendar settings". * <li>Under "Calendar Address" click on the [XML] button. A window * will pop up that will give you a URL of the form <pre> * "http://www.google.com/calendar/feeds/<token>@group.calendar.google.com/public/basic" * </pre> * <li>Your calendar id is "<token>@group.calendar.google.com" * </ul> * * @param gmtOffset * The offset, positive or negative, from GMT for the time zone for * the calendar * * @param user * your username for your Google Calendar account, e.g. * [email protected] * * @param password * your password for your Google Calendar account * * @param startDay * The starting day for this calendar in the format * <yyyy>-<mm>-<dd> * * @param endDay * The ending day inclusive for this calendar, in the format * <yyyy>-<mm>-<dd> * * @return a JSON Array containing the list of events from Google */ public void login(String calid, String gmtOffset, String user, String password, String startDay, String endDay, boolean drop) throws Exception { // Create the calendar, and if the login succeeds, start up the thread log("DerbyCalendarApplet.login(" + calid + ", " + gmtOffset + ", " + user + ", " + startDay + ", " + endDay + ")"); this.calid = calid; this.gmtOffset = gmtOffset; this.user = user; this.password = password; this.startDay = startDay; this.endDay = endDay; goOnline(); } private void startConsole(String dir) throws Exception { final String path = dir + "/" + CONSOLE_FILENAME; AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { log("Writing log to " + path); console = new PrintStream( new FileOutputStream(path)); System.setOut(console); System.setErr(console); return null; } } ); } /** * Go online. This method gets any pending requests and sends * them up to Google Calendar. */ public void goOnline() throws Exception { log("GOING ONLINE..."); this.online = true; try { // Log in to Google Calendar calendar = new GCalendar(calid, gmtOffset, user, password, startDay, endDay); RequestManager.submitRequests(calendar); } catch ( Exception e ) { e.printStackTrace(); throw e; } } public void goOffline() { log("GOING OFFLINE"); this.online = false; } public boolean isOnline() { return this.online; } /** * Refresh our calendar from Google Calendar and return a JSON string that * represents the array of entries for the given date range * * @return a JSON string that represents an array of all the entries * for the calendar. */ public String refresh() throws Exception { log("DerbyCalendarApplet.refresh()"); Collection<CalEvent> events = null; if ( isOnline() ) { try { events = calendar.getEvents(); // Refresh the database with the events we got from Google // Calendar EventManager.refresh(events); } catch ( NetworkDownException nde ) { log("The network is down, going offline"); goOffline(); } } if ( ! isOnline() ) { events = EventManager.getEvents(); } JSONArray jarray = new JSONArray(); for ( CalEvent event : events ) { jarray.put(event.getJSONObject()); } return jarray.toString(); } // Return a list of conflicts as a string so it can be reported // as an error public String getConflicts() { java.util.List<String> conflicts = RequestManager.getConflicts(); if ( conflicts.size() == 1 ) { return "There was 1 error during synchronization. Please " + "see the error log for details."; } else if ( conflicts.size() > 1 ) { return "There were " + conflicts.size() + " errors during " + "synchronization. Please see the error log for details."; } else { return null; } } /** * Add an entry to the calendar * * @param id * The unique identifier for this new entry * * @param date * The date for this entry, in the form of <yyyy>-<mm>-<dd> * * @param title * The title for the entry * * @return the new id returned by Google Calendar */ public String addEvent(String id, String date, String title) throws Exception { log("DerbyCalendarApplet.addEntry(" + id + ", " + date + ", " + title + ")"); CalEvent event = null; if ( isOnline() ) { try { event = calendar.addEvent(date, title); } catch ( NetworkDownException nde ) { log("The network is down, going offline"); goOffline(); } } // Now do the database operations -- store the event // locally, and if we're offline, also store the request // to add the event so we can ship it to Google Calendar // when we come back online try { DatabaseManager.beginTransaction(); if ( ! isOnline() ) { log("Storing request to add event"); RequestManager.storeAddEvent(id, date, title); event = new CalEvent(id, date, title, null, null); } log("Storing new event in the local database"); EventManager.addEvent(event); DatabaseManager.commitTransaction(); } catch ( Exception e ) { DatabaseManager.rollbackTransaction(); throw e; } return event.getJSONObject().toString(); -} + } public void updateEvent(String id, String title) throws Exception { log("DerbyCalendarApplet.updateEntry(" + id + ", " + title + ")"); CalEvent event = EventManager.getEvent(id); event.setTitle(title); if ( isOnline() ) { try { event = calendar.updateEvent(event); } catch ( NetworkDownException nde ) { log("The network is down, going offline"); goOffline(); } } // Now do the database operations -- store the event // locally, and if we're offline, also store the request // to add the event so we can ship it to Google Calendar // when we come back online try { DatabaseManager.beginTransaction(); if ( ! isOnline() ) { log("Storing request to update event"); RequestManager.storeUpdateEvent(event); } log("Updating event in the local database"); EventManager.updateEvent(event); DatabaseManager.commitTransaction(); } catch ( Exception e ) { DatabaseManager.rollbackTransaction(); throw e; } } public void deleteEvent(String id) throws Exception { log("DerbyCalendarApplet.deleteEntry(" + id + ")"); CalEvent event = EventManager.getEvent(id); if ( isOnline() ) { try { if ( event == null ) { throw new Exception("Can't find even in the database: " + id); } calendar.deleteEvent(event.getEditURL()); } catch ( NetworkDownException nde ) { log("The network is down, going offline"); goOffline(); } } // Now do the database operations -- store the event // locally, and if we're offline, also store the request // to add the event so we can ship it to Google Calendar // when we come back online try { DatabaseManager.beginTransaction(); if ( ! isOnline() ) { log("Storing request to delete event"); RequestManager.storeDeleteEvent(id, event.getEditURL()); } log("Deleting event in the local database"); EventManager.deleteEvent(id); DatabaseManager.commitTransaction(); } catch ( Exception e ) { DatabaseManager.rollbackTransaction(); throw e; } } /** * Empty out the calendar. Used mostly for testing */ public void clearCalendar() throws Exception { DatabaseManager.clearTables(); calendar.clearCalendar(); } private void log(String str) { System.out.println(str); } /** * Call this to turn on logging of SQL to derby.log, * for debuggig */ public void logSql() throws Exception { DatabaseManager.logSql(); } public void init() { log("Applet init, applet is " + this.hashCode()); try { AccessController.doPrivileged( new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { String userdir = System.getProperty("user.home"); String dbname = userdir + "/" + DBNAME; startConsole(userdir); DatabaseManager.initDatabase(dbname, "user", "secret", false); log("Database initialized, " + "database directory is " + dbname); return null; } } ); } catch ( PrivilegedActionException e ) { e.getException().printStackTrace(); } } public void start() { log("Applet start, applet is " + this.hashCode()); } public void stop() { log("Applet stop, applet is " + this.hashCode()); } public void destroy() { log("Applet destroy, applet is " + this.hashCode()); } /** Still need to figure this one out... public void paint(Graphics g) { g.drawString("Repainting", 50, 25); g.drawString(consoleStream.toString(), 50, 35); } */ }
true
true
public String addEvent(String id, String date, String title) throws Exception { log("DerbyCalendarApplet.addEntry(" + id + ", " + date + ", " + title + ")"); CalEvent event = null; if ( isOnline() ) { try { event = calendar.addEvent(date, title); } catch ( NetworkDownException nde ) { log("The network is down, going offline"); goOffline(); } } // Now do the database operations -- store the event // locally, and if we're offline, also store the request // to add the event so we can ship it to Google Calendar // when we come back online try { DatabaseManager.beginTransaction(); if ( ! isOnline() ) { log("Storing request to add event"); RequestManager.storeAddEvent(id, date, title); event = new CalEvent(id, date, title, null, null); } log("Storing new event in the local database"); EventManager.addEvent(event); DatabaseManager.commitTransaction(); } catch ( Exception e ) { DatabaseManager.rollbackTransaction(); throw e; } return event.getJSONObject().toString(); }
public String addEvent(String id, String date, String title) throws Exception { log("DerbyCalendarApplet.addEntry(" + id + ", " + date + ", " + title + ")"); CalEvent event = null; if ( isOnline() ) { try { event = calendar.addEvent(date, title); } catch ( NetworkDownException nde ) { log("The network is down, going offline"); goOffline(); } } // Now do the database operations -- store the event // locally, and if we're offline, also store the request // to add the event so we can ship it to Google Calendar // when we come back online try { DatabaseManager.beginTransaction(); if ( ! isOnline() ) { log("Storing request to add event"); RequestManager.storeAddEvent(id, date, title); event = new CalEvent(id, date, title, null, null); } log("Storing new event in the local database"); EventManager.addEvent(event); DatabaseManager.commitTransaction(); } catch ( Exception e ) { DatabaseManager.rollbackTransaction(); throw e; } return event.getJSONObject().toString(); }
diff --git a/utils/src/main/java/org/apache/ode/utils/LoggingInterceptor.java b/utils/src/main/java/org/apache/ode/utils/LoggingInterceptor.java index 5aed0aac..1368f7c8 100644 --- a/utils/src/main/java/org/apache/ode/utils/LoggingInterceptor.java +++ b/utils/src/main/java/org/apache/ode/utils/LoggingInterceptor.java @@ -1,161 +1,161 @@ package org.apache.ode.utils; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.Statement; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.sql.DataSource; import org.apache.commons.logging.Log; public class LoggingInterceptor<T> implements InvocationHandler { private static final Set<String> PARAMSTYPES = new HashSet<String>(); static { PARAMSTYPES.add("setArray"); PARAMSTYPES.add("setBigDecimal"); PARAMSTYPES.add("setBoolean"); PARAMSTYPES.add("setByte"); PARAMSTYPES.add("setBytes"); PARAMSTYPES.add("setDate"); PARAMSTYPES.add("setDouble"); PARAMSTYPES.add("setFloat"); PARAMSTYPES.add("setInt"); PARAMSTYPES.add("setLong"); PARAMSTYPES.add("setObject"); PARAMSTYPES.add("setRef"); PARAMSTYPES.add("setShort"); PARAMSTYPES.add("setString"); PARAMSTYPES.add("setTime"); PARAMSTYPES.add("setTimestamp"); PARAMSTYPES.add("setURL"); } private Log _log; private T _delegate; private TreeMap<String, Object> _paramsByName = new TreeMap<String, Object>(); private TreeMap<Integer, Object> _paramsByIdx = new TreeMap<Integer, Object>(); public LoggingInterceptor(T delegate, Log log) { _log = log; _delegate = delegate; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (method.getDeclaringClass() == DataSource.class && "getConnection".equals(method.getName())) { Connection conn = (Connection)method.invoke(_delegate, args); print("getConnection (tx=" + conn.getTransactionIsolation() + ")"); return Proxy.newProxyInstance(_delegate.getClass().getClassLoader(), new Class[] {Connection.class}, new LoggingInterceptor<Connection>(conn, _log)); } else if (method.getDeclaringClass() == Connection.class && Statement.class.isAssignableFrom(method.getReturnType())) { Statement stmt = (Statement)method.invoke(_delegate, args); print(method, args); return Proxy.newProxyInstance(_delegate.getClass().getClassLoader(), new Class[] {method.getReturnType()}, new LoggingInterceptor<Statement>(stmt, _log)); } else { print(method, args); return method.invoke(_delegate, args); } } catch (InvocationTargetException e) { throw e.getTargetException(); } } private void print(Method method, Object[] args) { if (shouldPrint()) { // JDBC Connection - if ("prepareStmt".equals(method.getName())) { + if ("prepareStatement".equals(method.getName())) { print("prepareStmt: " + args[0]); if (((String)args[0]).indexOf("ODE_SCOPE") > 0) { for (StackTraceElement traceElement : Thread.currentThread().getStackTrace()) { print(traceElement.toString()); } } } else if ("prepareCall".equals(method.getName())) { print("prepareCall: " + args[0]); } else if ("close".equals(method.getName())) { print("close()"); } else if ("commit".equals(method.getName())) { print("commit()"); } else if ("rollback".equals(method.getName())) { print("rollback()"); } else if ("setTransactionIsolation".equals(method.getName())) { print("Set isolation level to " + args[0]); } // JDBC Statement else if (method.getName().startsWith("execute")) { print(method.getName() + ", " + getParams()); } else if ("clearParameters".equals(method.getName())) { _paramsByIdx.clear(); _paramsByName.clear(); } else if ("setNull".equals(method.getName())) { if (String.class.isAssignableFrom(args[0].getClass())) { _paramsByName.put((String)args[0], null); } else if (Integer.class.isAssignableFrom(args[0].getClass())) { _paramsByIdx.put((Integer)args[0], null); } } else if (PARAMSTYPES.contains(method.getName())){ if (String.class.isAssignableFrom(args[0].getClass())) { _paramsByName.put((String)args[0], args[1]); } else if (Integer.class.isAssignableFrom(args[0].getClass())) { _paramsByIdx.put((Integer)args[0], args[1]); } } } } private String getParams() { if (_paramsByIdx.size() > 0 || _paramsByName.size() > 0) { StringBuffer buf = new StringBuffer(); buf.append("bound "); for (Map.Entry<Integer, Object> entry : _paramsByIdx.entrySet()) { try { buf.append("(").append(entry.getKey()).append(",").append(entry.getValue()).append(") "); } catch (Throwable e) { // We don't want to mess with the connection just for logging return "[e]"; } } for (Map.Entry<String, Object> entry : _paramsByName.entrySet()) { try { buf.append("(").append(entry.getKey()).append(",").append(entry.getValue()).append(") "); } catch (Throwable e) { // We don't want to mess with the connection just for logging return "[e]"; } } return buf.toString(); } return "w/o params"; } private boolean shouldPrint() { if (_log != null) return _log.isDebugEnabled(); else return true; } private void print(String str) { if (_log != null) _log.debug(str); else System.out.println(str); } public static DataSource createLoggingDS(DataSource ds, Log log) { return (DataSource)Proxy.newProxyInstance(ds.getClass().getClassLoader(), new Class[] {DataSource.class}, new LoggingInterceptor<DataSource>(ds,log)); } }
true
true
private void print(Method method, Object[] args) { if (shouldPrint()) { // JDBC Connection if ("prepareStmt".equals(method.getName())) { print("prepareStmt: " + args[0]); if (((String)args[0]).indexOf("ODE_SCOPE") > 0) { for (StackTraceElement traceElement : Thread.currentThread().getStackTrace()) { print(traceElement.toString()); } } } else if ("prepareCall".equals(method.getName())) { print("prepareCall: " + args[0]); } else if ("close".equals(method.getName())) { print("close()"); } else if ("commit".equals(method.getName())) { print("commit()"); } else if ("rollback".equals(method.getName())) { print("rollback()"); } else if ("setTransactionIsolation".equals(method.getName())) { print("Set isolation level to " + args[0]); } // JDBC Statement else if (method.getName().startsWith("execute")) { print(method.getName() + ", " + getParams()); } else if ("clearParameters".equals(method.getName())) { _paramsByIdx.clear(); _paramsByName.clear(); } else if ("setNull".equals(method.getName())) { if (String.class.isAssignableFrom(args[0].getClass())) { _paramsByName.put((String)args[0], null); } else if (Integer.class.isAssignableFrom(args[0].getClass())) { _paramsByIdx.put((Integer)args[0], null); } } else if (PARAMSTYPES.contains(method.getName())){ if (String.class.isAssignableFrom(args[0].getClass())) { _paramsByName.put((String)args[0], args[1]); } else if (Integer.class.isAssignableFrom(args[0].getClass())) { _paramsByIdx.put((Integer)args[0], args[1]); } } } }
private void print(Method method, Object[] args) { if (shouldPrint()) { // JDBC Connection if ("prepareStatement".equals(method.getName())) { print("prepareStmt: " + args[0]); if (((String)args[0]).indexOf("ODE_SCOPE") > 0) { for (StackTraceElement traceElement : Thread.currentThread().getStackTrace()) { print(traceElement.toString()); } } } else if ("prepareCall".equals(method.getName())) { print("prepareCall: " + args[0]); } else if ("close".equals(method.getName())) { print("close()"); } else if ("commit".equals(method.getName())) { print("commit()"); } else if ("rollback".equals(method.getName())) { print("rollback()"); } else if ("setTransactionIsolation".equals(method.getName())) { print("Set isolation level to " + args[0]); } // JDBC Statement else if (method.getName().startsWith("execute")) { print(method.getName() + ", " + getParams()); } else if ("clearParameters".equals(method.getName())) { _paramsByIdx.clear(); _paramsByName.clear(); } else if ("setNull".equals(method.getName())) { if (String.class.isAssignableFrom(args[0].getClass())) { _paramsByName.put((String)args[0], null); } else if (Integer.class.isAssignableFrom(args[0].getClass())) { _paramsByIdx.put((Integer)args[0], null); } } else if (PARAMSTYPES.contains(method.getName())){ if (String.class.isAssignableFrom(args[0].getClass())) { _paramsByName.put((String)args[0], args[1]); } else if (Integer.class.isAssignableFrom(args[0].getClass())) { _paramsByIdx.put((Integer)args[0], args[1]); } } } }
diff --git a/org.emftext.sdk/src/org/emftext/sdk/util/GenClassUtil.java b/org.emftext.sdk/src/org/emftext/sdk/util/GenClassUtil.java index c003fe7e5..7c2c11b4e 100644 --- a/org.emftext.sdk/src/org/emftext/sdk/util/GenClassUtil.java +++ b/org.emftext.sdk/src/org/emftext/sdk/util/GenClassUtil.java @@ -1,116 +1,118 @@ /******************************************************************************* * Copyright (c) 2006-2010 * Software Technology Group, Dresden University of Technology * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.util; import java.util.Collection; import java.util.List; import java.util.Map; import org.eclipse.emf.codegen.ecore.genmodel.GenClass; import org.eclipse.emf.codegen.ecore.genmodel.GenPackage; import org.emftext.sdk.concretesyntax.GenClassCache; /** * A utility class to work with EMF GenClasses. */ public class GenClassUtil { /** * Searches for 'genClass' in 'genClasses'. If a class with the * same qualified interface name is found, this method returns * true, otherwise false. * * @param genClasses the collection of classes to search in * @param genClass the class to search for * @param genClassCache * @return */ public boolean contains(Collection<GenClass> genClasses, GenClass genClass, GenClassCache genClassCache) { + String genClassInterfaceName = genClassCache.getQualifiedInterfaceName(genClass); for (GenClass next : genClasses) { - if (genClassCache.getQualifiedInterfaceName(next).equals(genClassCache.getQualifiedInterfaceName(genClass))) { + String nextInterfaceName = genClassCache.getQualifiedInterfaceName(next); + if (nextInterfaceName != null && nextInterfaceName.equals(genClassInterfaceName)) { return true; } } return false; } /** * Returns true if the given class is neither abstract nor * an interface. * * @param genClass * @return */ public boolean isConcrete(GenClass genClass) { return !genClass.isAbstract() && !genClass.isInterface(); } /** * Returns true if the given class is either abstract or * an interface. * * @param genClass * @return */ public boolean isNotConcrete(GenClass genClass) { return !isConcrete(genClass); } /** * Returns true if superClass is a superclass of subClass. * * @param superClass * @param subClass * @param genClassCache * @return */ public boolean isSuperClass(GenClass superClass, GenClass subClass, GenClassCache genClassCache) { List<GenClass> superClasses = subClass.getAllBaseGenClasses(); for (GenClass nextSuperclass : superClasses) { if (genClassCache.getQualifiedInterfaceName(nextSuperclass).equals(genClassCache.getQualifiedInterfaceName(superClass))) { return true; } } return false; } /** * Returns the code for a method call that obtains the EClass of the given * GenClass from the generated EPackage. * * @param genClass * @return */ public String getAccessor(GenClass genClass) { return genClass.getGenPackage().getQualifiedPackageInterfaceName() + ".eINSTANCE.get" + genClass.getClassifierAccessorName() + "()"; } /** * Returns the code for a method call that creates an instance of the EClass * of the given GenClass using the generated EFactory. * * @param genClass * @return */ public String getCreateObjectCall(GenClass genClass, String qualifiedDummyEObjectClassName) { GenPackage genPackage = genClass.getGenPackage(); if (Map.Entry.class.getName().equals(genClass.getEcoreClass().getInstanceClassName())) { return "new " + qualifiedDummyEObjectClassName + "("+ genPackage.getQualifiedPackageClassName() + ".eINSTANCE.get" + genClass.getName() + "(),\"" + genClass.getName() + "\")"; } else { return genPackage.getQualifiedFactoryInterfaceName() + ".eINSTANCE.create" + genClass.getName() + "()"; } } }
false
true
public boolean contains(Collection<GenClass> genClasses, GenClass genClass, GenClassCache genClassCache) { for (GenClass next : genClasses) { if (genClassCache.getQualifiedInterfaceName(next).equals(genClassCache.getQualifiedInterfaceName(genClass))) { return true; } } return false; }
public boolean contains(Collection<GenClass> genClasses, GenClass genClass, GenClassCache genClassCache) { String genClassInterfaceName = genClassCache.getQualifiedInterfaceName(genClass); for (GenClass next : genClasses) { String nextInterfaceName = genClassCache.getQualifiedInterfaceName(next); if (nextInterfaceName != null && nextInterfaceName.equals(genClassInterfaceName)) { return true; } } return false; }
diff --git a/src/main/java/de/elatexam/DeleteServlet.java b/src/main/java/de/elatexam/DeleteServlet.java index 4a19e7e..f0f6b42 100644 --- a/src/main/java/de/elatexam/DeleteServlet.java +++ b/src/main/java/de/elatexam/DeleteServlet.java @@ -1,51 +1,51 @@ /* Copyright (C) 2010 Steffen Dienst This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package de.elatexam; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import de.elatexam.dao.DataStoreTaskFactory; /** * @author Steffen Dienst * */ public class DeleteServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String handle = req.getParameter("id"); UserService userService = UserServiceFactory.getUserService(); - long taskdefHandle = Long.parseLong(handle); if (handle != null && userService.isUserLoggedIn()) { + long taskdefHandle = Long.parseLong(handle); DataStoreTaskFactory.getInstance().deleteTaskDef(userService.getCurrentUser().getNickname(), taskdefHandle); } resp.sendRedirect("/"); } }
false
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String handle = req.getParameter("id"); UserService userService = UserServiceFactory.getUserService(); long taskdefHandle = Long.parseLong(handle); if (handle != null && userService.isUserLoggedIn()) { DataStoreTaskFactory.getInstance().deleteTaskDef(userService.getCurrentUser().getNickname(), taskdefHandle); } resp.sendRedirect("/"); }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String handle = req.getParameter("id"); UserService userService = UserServiceFactory.getUserService(); if (handle != null && userService.isUserLoggedIn()) { long taskdefHandle = Long.parseLong(handle); DataStoreTaskFactory.getInstance().deleteTaskDef(userService.getCurrentUser().getNickname(), taskdefHandle); } resp.sendRedirect("/"); }
diff --git a/src/com/nsn/uwr/panio/calculations/tree/Subtraction.java b/src/com/nsn/uwr/panio/calculations/tree/Subtraction.java index dd9618c..970fc91 100644 --- a/src/com/nsn/uwr/panio/calculations/tree/Subtraction.java +++ b/src/com/nsn/uwr/panio/calculations/tree/Subtraction.java @@ -1,21 +1,21 @@ package com.nsn.uwr.panio.calculations.tree; import com.nsn.uwr.panio.calculations.Function; import com.nsn.uwr.panio.inputsparser.EOperand; @Function(EOperand.SUBTRACT) public class Subtraction extends AbstractBinaryFunction { public Subtraction(IValueElement arg1, IValueElement arg2) { - super(arg1, arg2); + super(arg1, arg1); } @Override public double getValue() { return getArg1().getValue() - getArg2().getValue(); } public String getString() { return getArg1().toString() + " - " + getArg2().toString(); } }
true
true
public Subtraction(IValueElement arg1, IValueElement arg2) { super(arg1, arg2); }
public Subtraction(IValueElement arg1, IValueElement arg2) { super(arg1, arg1); }
diff --git a/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java b/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java index 360d6dd61..671e66b6c 100644 --- a/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java +++ b/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java @@ -1,2296 +1,2296 @@ /* * Copyright 2009 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.jscomp.ExtractPrototypeMemberDeclarations.Pattern; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.Node; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * Pass factories and meta-data for native JSCompiler passes. * * @author [email protected] (Nick Santos) */ // TODO(nicksantos): This needs state for a variety of reasons. Some of it // is to satisfy the existing API. Some of it is because passes really do // need to share state in non-trivial ways. This should be audited and // cleaned up. public class DefaultPassConfig extends PassConfig { /* For the --mark-as-compiled pass */ private static final String COMPILED_CONSTANT_NAME = "COMPILED"; /* Constant name for Closure's locale */ private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE"; // Compiler errors when invalid combinations of passes are run. static final DiagnosticType TIGHTEN_TYPES_WITHOUT_TYPE_CHECK = DiagnosticType.error("JSC_TIGHTEN_TYPES_WITHOUT_TYPE_CHECK", "TightenTypes requires type checking. Please use --check_types."); static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR = DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR", "Rename prototypes and inline variables cannot be used together"); // Miscellaneous errors. static final DiagnosticType REPORT_PATH_IO_ERROR = DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR", "Error writing compiler report to {0}"); private static final DiagnosticType INPUT_MAP_PROP_PARSE = DiagnosticType.error("JSC_INPUT_MAP_PROP_PARSE", "Input property map parse error: {0}"); private static final DiagnosticType INPUT_MAP_VAR_PARSE = DiagnosticType.error("JSC_INPUT_MAP_VAR_PARSE", "Input variable map parse error: {0}"); private static final DiagnosticType NAME_REF_GRAPH_FILE_ERROR = DiagnosticType.error("JSC_NAME_REF_GRAPH_FILE_ERROR", "Error \"{1}\" writing name reference graph to \"{0}\"."); private static final DiagnosticType NAME_REF_REPORT_FILE_ERROR = DiagnosticType.error("JSC_NAME_REF_REPORT_FILE_ERROR", "Error \"{1}\" writing name reference report to \"{0}\"."); private static final java.util.regex.Pattern GLOBAL_SYMBOL_NAMESPACE_PATTERN = java.util.regex.Pattern.compile("^[a-zA-Z0-9$_]+$"); /** * A global namespace to share across checking passes. */ private GlobalNamespace namespaceForChecks = null; /** * A symbol table for registering references that get removed during * preprocessing. */ private PreprocessorSymbolTable preprocessorSymbolTable = null; /** * A type-tightener to share across optimization passes. */ private TightenTypes tightenTypes = null; /** Names exported by goog.exportSymbol. */ private Set<String> exportedNames = null; /** * Ids for cross-module method stubbing, so that each method has * a unique id. */ private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator = new CrossModuleMethodMotion.IdGenerator(); /** * Keys are arguments passed to getCssName() found during compilation; values * are the number of times the key appeared as an argument to getCssName(). */ private Map<String, Integer> cssNames = null; /** The variable renaming map */ private VariableMap variableMap = null; /** The property renaming map */ private VariableMap propertyMap = null; /** The naming map for anonymous functions */ private VariableMap anonymousFunctionNameMap = null; /** Fully qualified function names and globally unique ids */ private FunctionNames functionNames = null; /** String replacement map */ private VariableMap stringMap = null; /** Id generator map */ private String idGeneratorMap = null; public DefaultPassConfig(CompilerOptions options) { super(options); } @Override State getIntermediateState() { return new State( cssNames == null ? null : Maps.newHashMap(cssNames), exportedNames == null ? null : Collections.unmodifiableSet(exportedNames), crossModuleIdGenerator, variableMap, propertyMap, anonymousFunctionNameMap, stringMap, functionNames, idGeneratorMap); } @Override void setIntermediateState(State state) { this.cssNames = state.cssNames == null ? null : Maps.newHashMap(state.cssNames); this.exportedNames = state.exportedNames == null ? null : Sets.newHashSet(state.exportedNames); this.crossModuleIdGenerator = state.crossModuleIdGenerator; this.variableMap = state.variableMap; this.propertyMap = state.propertyMap; this.anonymousFunctionNameMap = state.anonymousFunctionNameMap; this.stringMap = state.stringMap; this.functionNames = state.functionNames; this.idGeneratorMap = state.idGeneratorMap; } GlobalNamespace getGlobalNamespace() { return namespaceForChecks; } PreprocessorSymbolTable getPreprocessorSymbolTable() { return preprocessorSymbolTable; } void maybeInitializePreprocessorSymbolTable(AbstractCompiler compiler) { if (options.ideMode) { Node root = compiler.getRoot(); if (preprocessorSymbolTable == null || preprocessorSymbolTable.getRootNode() != root) { preprocessorSymbolTable = new PreprocessorSymbolTable(root); } } } @Override protected List<PassFactory> getChecks() { List<PassFactory> checks = Lists.newArrayList(); if (options.closurePass) { checks.add(closureGoogScopeAliases); } if (options.nameAnonymousFunctionsOnly) { if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { checks.add(nameMappedAnonymousFunctions); } else if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { checks.add(nameUnmappedAnonymousFunctions); } return checks; } checks.add(checkSideEffects); if (options.checkSuspiciousCode || options.enables(DiagnosticGroups.GLOBAL_THIS) || options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) { checks.add(suspiciousCode); } if (options.checkControlStructures || options.enables(DiagnosticGroups.ES5_STRICT)) { checks.add(checkControlStructures); } if (options.checkRequires.isOn()) { checks.add(checkRequires); } if (options.checkProvides.isOn()) { checks.add(checkProvides); } // The following passes are more like "preprocessor" passes. // It's important that they run before most checking passes. // Perhaps this method should be renamed? if (options.generateExports) { checks.add(generateExports); } if (options.exportTestFunctions) { checks.add(exportTestFunctions); } if (options.closurePass) { checks.add(closurePrimitives.makeOneTimePass()); } if (options.jqueryPass) { checks.add(jqueryAliases.makeOneTimePass()); } if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) { checks.add(closureCheckGetCssName); } if (options.syntheticBlockStartMarker != null) { // This pass must run before the first fold constants pass. checks.add(createSyntheticBlocks); } checks.add(checkVars); if (options.computeFunctionSideEffects) { checks.add(checkRegExp); } if (options.aggressiveVarCheck.isOn()) { checks.add(checkVariableReferences); } // This pass should run before types are assigned. if (options.processObjectPropertyString) { checks.add(objectPropertyStringPreprocess); } if (options.checkTypes || options.inferTypes) { checks.add(resolveTypes.makeOneTimePass()); checks.add(inferTypes.makeOneTimePass()); if (options.checkTypes) { checks.add(checkTypes.makeOneTimePass()); } else { checks.add(inferJsDocInfo.makeOneTimePass()); } } if (options.checkUnreachableCode.isOn() || (options.checkTypes && options.checkMissingReturn.isOn())) { checks.add(checkControlFlow); } // CheckAccessControls only works if check types is on. if (options.checkTypes && (options.enables(DiagnosticGroups.ACCESS_CONTROLS) || options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) { checks.add(checkAccessControls); } if (options.checkGlobalNamesLevel.isOn()) { checks.add(checkGlobalNames); } if (options.enables(DiagnosticGroups.ES5_STRICT) || options.checkCaja) { checks.add(checkStrictMode); } // Replace 'goog.getCssName' before processing defines but after the // other checks have been done. if (options.closurePass) { checks.add(closureReplaceGetCssName); } // i18n // If you want to customize the compiler to use a different i18n pass, // you can create a PassConfig that calls replacePassFactory // to replace this. checks.add(options.messageBundle != null ? replaceMessages : createEmptyPass("replaceMessages")); if (options.getTweakProcessing().isOn()) { checks.add(processTweaks); } // Defines in code always need to be processed. checks.add(processDefines); if (options.instrumentationTemplate != null || options.recordFunctionInformation) { checks.add(computeFunctionNames); } if (options.nameReferenceGraphPath != null && !options.nameReferenceGraphPath.isEmpty()) { checks.add(printNameReferenceGraph); } if (options.nameReferenceReportPath != null && !options.nameReferenceReportPath.isEmpty()) { checks.add(printNameReferenceReport); } assertAllOneTimePasses(checks); return checks; } @Override protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); passes.add(garbageCollectChecks); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (options.replaceIdGenerators) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && (options.removeAbstractMethods || options.removeClosureAsserts)) { passes.add(closureCodeRemoval); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // ReplaceStrings runs after CollapseProperties in order to simplify // pulling in values of constants defined in enums structures. if (!options.replaceStringsFunctionDescriptions.isEmpty()) { passes.add(replaceStrings); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // This needs to come after the inline constants pass, which is run within // the code removing passes. if (options.closurePass) { passes.add(closureOptimizePrimitives); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); if (options.specializeInitialModule) { // When specializing the initial module, we want our fixups to be // as lean as possible, so we run the entire optimization loop to a // fixed point before specializing, then specialize, and then run the // main optimization loop again. passes.addAll(getMainOptimizationLoop()); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(specializeInitialModule.makeOneTimePass()); } passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. - if (options.removeUnusedVars) { + if (options.removeUnusedVars || options.removeUnusedLocalVars) { passes.add(removeUnusedVars); } } // Running this pass again is required to have goog.events compile down to // nothing when compiled on its own. if (options.smartNameRemoval) { passes.add(smartNamePass2); } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations || // renamePrefixNamescape relies on moveFunctionDeclarations // to preserve semantics. options.renamePrefixNamespace != null) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } // Passes after this point can no longer depend on normalized AST // assumptions. passes.add(markUnnormalized); if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); // coalesceVariables creates identity assignments and more redundant code // that can be removed, rerun the peephole optimizations to clean them // up. if (options.foldConstants) { passes.add(peepholeOptimizations); } } if (options.collapseVariableDeclarations) { passes.add(exploitAssign); passes.add(collapseVariableDeclarations); } // This pass works best after collapseVariableDeclarations. passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } if (options.groupVariableDeclarations) { passes.add(groupVariableDeclarations); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.foldConstants) { passes.add(latePeepholeOptimizations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } if (options.renamePrefixNamespace != null) { if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher( options.renamePrefixNamespace).matches()) { throw new IllegalArgumentException( "Illegal character in renamePrefixNamespace name: " + options.renamePrefixNamespace); } passes.add(rescopeGlobalSymbols); } passes.add(stripSideEffectProtection); // Safety checks passes.add(sanityCheckAst); passes.add(sanityCheckVars); return passes; } /** Creates the passes for the main optimization loop. */ private List<PassFactory> getMainOptimizationLoop() { List<PassFactory> passes = Lists.newArrayList(); if (options.inlineGetters) { passes.add(inlineSimpleMethods); } passes.addAll(getCodeRemovingPasses()); if (options.inlineFunctions || options.inlineLocalFunctions) { passes.add(inlineFunctions); } boolean runOptimizeCalls = options.optimizeCalls || options.optimizeParameters || options.optimizeReturns; if (options.removeUnusedVars || options.removeUnusedLocalVars) { if (options.deadAssignmentElimination) { passes.add(deadAssignmentsElimination); } if (!runOptimizeCalls) { passes.add(removeUnusedVars); } } if (runOptimizeCalls) { passes.add(optimizeCallsAndRemoveUnusedVars); } assertAllLoopablePasses(passes); return passes; } /** Creates several passes aimed at removing code. */ private List<PassFactory> getCodeRemovingPasses() { List<PassFactory> passes = Lists.newArrayList(); if (options.collapseObjectLiterals && !isInliningForbidden()) { passes.add(collapseObjectLiterals); } if (options.inlineVariables || options.inlineLocalVariables) { passes.add(inlineVariables); } else if (options.inlineConstantVars) { passes.add(inlineConstants); } if (options.foldConstants) { // These used to be one pass. passes.add(minimizeExitPoints); passes.add(peepholeOptimizations); } if (options.removeDeadCode) { passes.add(removeUnreachableCode); } if (options.removeUnusedPrototypeProperties) { passes.add(removeUnusedPrototypeProperties); passes.add(removeUnusedClassProperties); } assertAllLoopablePasses(passes); return passes; } /** * Checks for code that is probably wrong (such as stray expressions). */ final HotSwapPassFactory checkSideEffects = new HotSwapPassFactory("checkSideEffects", true) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { // The current approach to protecting "hidden" side-effects is to // wrap them in a function call that is stripped later, this shouldn't // be done in IDE mode where AST changes may be unexpected. boolean protectHiddenSideEffects = options.protectHiddenSideEffects && !options.ideMode; return new CheckSideEffects(compiler, options.checkSuspiciousCode ? CheckLevel.WARNING : CheckLevel.OFF, protectHiddenSideEffects); } }; /** * Checks for code that is probably wrong (such as stray expressions). */ final PassFactory stripSideEffectProtection = new PassFactory("stripSideEffectProtection", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CheckSideEffects.StripProtection(compiler); } }; /** * Checks for code that is probably wrong (such as stray expressions). */ // TODO(bolinfest): Write a CompilerPass for this. final HotSwapPassFactory suspiciousCode = new HotSwapPassFactory("suspiciousCode", true) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { List<Callback> sharedCallbacks = Lists.newArrayList(); if (options.checkSuspiciousCode) { sharedCallbacks.add(new CheckAccidentalSemicolon(CheckLevel.WARNING)); } if (options.enables(DiagnosticGroups.GLOBAL_THIS)) { sharedCallbacks.add(new CheckGlobalThis(compiler)); } if (options.enables(DiagnosticGroups.DEBUGGER_STATEMENT_PRESENT)) { sharedCallbacks.add(new CheckDebuggerStatement(compiler)); } return combineChecks(compiler, sharedCallbacks); } }; /** Verify that all the passes are one-time passes. */ private void assertAllOneTimePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(pass.isOneTimePass()); } } /** Verify that all the passes are multi-run passes. */ private void assertAllLoopablePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(!pass.isOneTimePass()); } } /** Checks for validity of the control structures. */ final HotSwapPassFactory checkControlStructures = new HotSwapPassFactory("checkControlStructures", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new ControlStructureCheck(compiler); } }; /** Checks that all constructed classes are goog.require()d. */ final HotSwapPassFactory checkRequires = new HotSwapPassFactory("checkRequires", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckRequiresForConstructors(compiler, options.checkRequires); } }; /** Makes sure @constructor is paired with goog.provides(). */ final HotSwapPassFactory checkProvides = new HotSwapPassFactory("checkProvides", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckProvides(compiler, options.checkProvides); } }; private static final DiagnosticType GENERATE_EXPORTS_ERROR = DiagnosticType.error( "JSC_GENERATE_EXPORTS_ERROR", "Exports can only be generated if export symbol/property " + "functions are set."); /** Generates exports for @export annotations. */ final PassFactory generateExports = new PassFactory("generateExports", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null && convention.getExportPropertyFunction() != null) { return new GenerateExports(compiler, convention.getExportSymbolFunction(), convention.getExportPropertyFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Generates exports for functions associated with JSUnit. */ final PassFactory exportTestFunctions = new PassFactory("exportTestFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null) { return new ExportTestFunctions(compiler, convention.getExportSymbolFunction(), convention.getExportPropertyFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Raw exports processing pass. */ final PassFactory gatherRawExports = new PassFactory("gatherRawExports", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final GatherRawExports pass = new GatherRawExports( compiler); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); if (exportedNames == null) { exportedNames = Sets.newHashSet(); } exportedNames.addAll(pass.getExportedVariableNames()); } }; } }; /** Closure pre-processing pass. */ @SuppressWarnings("deprecation") final HotSwapPassFactory closurePrimitives = new HotSwapPassFactory("processProvidesAndRequires", false) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { maybeInitializePreprocessorSymbolTable(compiler); final ProcessClosurePrimitives pass = new ProcessClosurePrimitives( compiler, preprocessorSymbolTable, options.brokenClosureRequiresLevel, options.rewriteNewDateGoogNow); return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); exportedNames = pass.getExportedVariableNames(); } @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { pass.hotSwapScript(scriptRoot, originalRoot); } }; } }; /** Expand jQuery Primitives and Aliases pass. */ final PassFactory jqueryAliases = new PassFactory("jqueryAliases", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ExpandJqueryAliases(compiler); } }; /** * The default i18n pass. * A lot of the options are not configurable, because ReplaceMessages * has a lot of legacy logic. */ final PassFactory replaceMessages = new PassFactory("replaceMessages", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ReplaceMessages(compiler, options.messageBundle, /* warn about message dupes */ true, /* allow messages with goog.getMsg */ JsMessage.Style.getFromParams(true, false), /* if we can't find a translation, don't worry about it. */ false); } }; /** Applies aliases and inlines goog.scope. */ final HotSwapPassFactory closureGoogScopeAliases = new HotSwapPassFactory("processGoogScopeAliases", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { maybeInitializePreprocessorSymbolTable(compiler); return new ScopedAliases( compiler, preprocessorSymbolTable, options.getAliasTransformationHandler()); } }; /** Checks that CSS class names are wrapped in goog.getCssName */ final PassFactory closureCheckGetCssName = new PassFactory("checkMissingGetCssName", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { String blacklist = options.checkMissingGetCssNameBlacklist; Preconditions.checkState(blacklist != null && !blacklist.isEmpty(), "Not checking use of goog.getCssName because of empty blacklist."); return new CheckMissingGetCssName( compiler, options.checkMissingGetCssNameLevel, blacklist); } }; /** * Processes goog.getCssName. The cssRenamingMap is used to lookup * replacement values for the classnames. If null, the raw class names are * inlined. */ final PassFactory closureReplaceGetCssName = new PassFactory("renameCssNames", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Integer> newCssNames = null; if (options.gatherCssNames) { newCssNames = Maps.newHashMap(); } (new ReplaceCssNames(compiler, newCssNames)).process( externs, jsRoot); cssNames = newCssNames; } }; } }; /** * Creates synthetic blocks to prevent FoldConstants from moving code * past markers in the source. */ final PassFactory createSyntheticBlocks = new PassFactory("createSyntheticBlocks", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CreateSyntheticBlocks(compiler, options.syntheticBlockStartMarker, options.syntheticBlockEndMarker); } }; /** Various peephole optimizations. */ final PassFactory peepholeOptimizations = new PassFactory("peepholeOptimizations", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final boolean late = false; return new PeepholeOptimizationsPass(compiler, new PeepholeSubstituteAlternateSyntax(late), new PeepholeReplaceKnownMethods(late), new PeepholeRemoveDeadCode(), new PeepholeFoldConstants(late), new PeepholeCollectPropertyAssignments()); } }; /** Same as peepholeOptimizations but aggressively merges code together */ final PassFactory latePeepholeOptimizations = new PassFactory("latePeepholeOptimizations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final boolean late = true; return new PeepholeOptimizationsPass(compiler, new StatementFusion(), new PeepholeRemoveDeadCode(), new PeepholeSubstituteAlternateSyntax(late), new PeepholeReplaceKnownMethods(late), new PeepholeFoldConstants(late), new ReorderConstantExpression()); } }; /** Checks that all variables are defined. */ final HotSwapPassFactory checkVars = new HotSwapPassFactory("checkVars", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler); } }; /** Checks for RegExp references. */ final PassFactory checkRegExp = new PassFactory("checkRegExp", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { final CheckRegExp pass = new CheckRegExp(compiler); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); compiler.setHasRegExpGlobalReferences( pass.isGlobalRegExpPropertiesUsed()); } }; } }; /** Checks that references to variables look reasonable. */ final HotSwapPassFactory checkVariableReferences = new HotSwapPassFactory("checkVariableReferences", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new VariableReferenceCheck( compiler, options.aggressiveVarCheck); } }; /** Pre-process goog.testing.ObjectPropertyString. */ final PassFactory objectPropertyStringPreprocess = new PassFactory("ObjectPropertyStringPreprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPreprocess(compiler); } }; /** Creates a typed scope and adds types to the type registry. */ final HotSwapPassFactory resolveTypes = new HotSwapPassFactory("resolveTypes", false) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new GlobalTypeResolver(compiler); } }; /** Runs type inference. */ final HotSwapPassFactory inferTypes = new HotSwapPassFactory("inferTypes", false) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); makeTypeInference(compiler).process(externs, root); } @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { makeTypeInference(compiler).inferTypes(scriptRoot); } }; } }; final HotSwapPassFactory inferJsDocInfo = new HotSwapPassFactory("inferJsDocInfo", false) { @Override protected HotSwapCompilerPass createInternal( final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); makeInferJsDocInfo(compiler).process(externs, root); } @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { makeInferJsDocInfo(compiler).hotSwapScript(scriptRoot, originalRoot); } }; } }; /** Checks type usage */ final HotSwapPassFactory checkTypes = new HotSwapPassFactory("checkTypes", false) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); TypeCheck check = makeTypeCheck(compiler); check.process(externs, root); compiler.getErrorManager().setTypedPercent(check.getTypedPercent()); } @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { makeTypeCheck(compiler).check(scriptRoot, false); } }; } }; /** * Checks possible execution paths of the program for problems: missing return * statements and dead code. */ final HotSwapPassFactory checkControlFlow = new HotSwapPassFactory("checkControlFlow", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { List<Callback> callbacks = Lists.newArrayList(); if (options.checkUnreachableCode.isOn()) { callbacks.add( new CheckUnreachableCode(compiler, options.checkUnreachableCode)); } if (options.checkMissingReturn.isOn() && options.checkTypes) { callbacks.add( new CheckMissingReturn(compiler, options.checkMissingReturn)); } return combineChecks(compiler, callbacks); } }; /** Checks access controls. Depends on type-inference. */ final HotSwapPassFactory checkAccessControls = new HotSwapPassFactory("checkAccessControls", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckAccessControls(compiler); } }; /** Executes the given callbacks with a {@link CombinedCompilerPass}. */ private static HotSwapCompilerPass combineChecks(AbstractCompiler compiler, List<Callback> callbacks) { Preconditions.checkArgument(callbacks.size() > 0); Callback[] array = callbacks.toArray(new Callback[callbacks.size()]); return new CombinedCompilerPass(compiler, array); } /** A compiler pass that resolves types in the global scope. */ class GlobalTypeResolver implements HotSwapCompilerPass { private final AbstractCompiler compiler; GlobalTypeResolver(AbstractCompiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { if (topScope == null) { regenerateGlobalTypedScope(compiler, root.getParent()); } else { compiler.getTypeRegistry().resolveTypesInScope(topScope); } } @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { patchGlobalTypedScope(compiler, scriptRoot); } } /** Checks global name usage. */ final PassFactory checkGlobalNames = new PassFactory("checkGlobalNames", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { // Create a global namespace for analysis by check passes. // Note that this class does all heavy computation lazily, // so it's OK to create it here. namespaceForChecks = new GlobalNamespace(compiler, jsRoot); new CheckGlobalNames(compiler, options.checkGlobalNamesLevel) .injectNamespace(namespaceForChecks).process(externs, jsRoot); } }; } }; /** Checks that the code is ES5 or Caja compliant. */ final PassFactory checkStrictMode = new PassFactory("checkStrictMode", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new StrictModeCheck(compiler, !options.checkSymbols, // don't check variables twice !options.checkCaja); // disable eval check if not Caja } }; /** Process goog.tweak.getTweak() calls. */ final PassFactory processTweaks = new PassFactory("processTweaks", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { new ProcessTweaks(compiler, options.getTweakProcessing().shouldStrip(), options.getTweakReplacements()).process(externs, jsRoot); } }; } }; /** Override @define-annotated constants. */ final PassFactory processDefines = new PassFactory("processDefines", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Node> replacements = getAdditionalReplacements(options); replacements.putAll(options.getDefineReplacements()); new ProcessDefines(compiler, replacements) .injectNamespace(namespaceForChecks).process(externs, jsRoot); } }; } }; /** Release references to data that is only needed during checks. */ final PassFactory garbageCollectChecks = new HotSwapPassFactory("garbageCollectChecks", true) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node jsRoot) { // Kill the global namespace so that it can be garbage collected // after all passes are through with it. namespaceForChecks = null; } @Override public void hotSwapScript(Node scriptRoot, Node originalRoot) { process(null, null); } }; } }; /** Checks that all constants are not modified */ final PassFactory checkConsts = new PassFactory("checkConsts", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConstCheck(compiler); } }; /** Computes the names of functions for later analysis. */ final PassFactory computeFunctionNames = new PassFactory("computeFunctionNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return ((functionNames = new FunctionNames(compiler))); } }; /** Skips Caja-private properties in for-in loops */ final PassFactory ignoreCajaProperties = new PassFactory("ignoreCajaProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new IgnoreCajaProperties(compiler); } }; /** Inserts runtime type assertions for debugging. */ final PassFactory runtimeTypeCheck = new PassFactory("runtimeTypeCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RuntimeTypeCheck(compiler, options.runtimeTypeCheckLogFunction); } }; /** Generates unique ids. */ final PassFactory replaceIdGenerators = new PassFactory("replaceIdGenerators", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { ReplaceIdGenerators pass = new ReplaceIdGenerators(compiler, options.idGenerators); pass.process(externs, root); idGeneratorMap = pass.getIdGeneratorMap(); } }; } }; /** Replace strings. */ final PassFactory replaceStrings = new PassFactory("replaceStrings", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { ReplaceStrings pass = new ReplaceStrings( compiler, options.replaceStringsPlaceholderToken, options.replaceStringsFunctionDescriptions, options.replaceStringsReservedStrings); pass.process(externs, root); stringMap = pass.getStringMap(); } }; } }; /** Optimizes the "arguments" array. */ final PassFactory optimizeArgumentsArray = new PassFactory("optimizeArgumentsArray", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new OptimizeArgumentsArray(compiler); } }; /** Remove variables set to goog.abstractMethod. */ final PassFactory closureCodeRemoval = new PassFactory("closureCodeRemoval", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ClosureCodeRemoval(compiler, options.removeAbstractMethods, options.removeClosureAsserts); } }; /** Special case optimizations for closure functions. */ final PassFactory closureOptimizePrimitives = new PassFactory("closureOptimizePrimitives", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ClosureOptimizePrimitives(compiler); } }; /** Puts global symbols into a single object. */ final PassFactory rescopeGlobalSymbols = new PassFactory("rescopeGlobalSymbols", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RescopeGlobalSymbols(compiler, options.renamePrefixNamespace); } }; /** Collapses names in the global scope. */ final PassFactory collapseProperties = new PassFactory("collapseProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseProperties( compiler, options.collapsePropertiesOnExternTypes, !isInliningForbidden()); } }; /** Rewrite properties as variables. */ final PassFactory collapseObjectLiterals = new PassFactory("collapseObjectLiterals", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineObjectLiterals( compiler, compiler.getUniqueNameIdSupplier()); } }; /** * Try to infer the actual types, which may be narrower * than the declared types. */ final PassFactory tightenTypesBuilder = new PassFactory("tightenTypes", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (!options.checkTypes) { return new ErrorPass(compiler, TIGHTEN_TYPES_WITHOUT_TYPE_CHECK); } tightenTypes = new TightenTypes(compiler); return tightenTypes; } }; /** Devirtualize property names based on type information. */ final PassFactory disambiguateProperties = new PassFactory("disambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (tightenTypes == null) { return DisambiguateProperties.forJSTypeSystem(compiler, options.propertyInvalidationErrors); } else { return DisambiguateProperties.forConcreteTypeSystem( compiler, tightenTypes, options.propertyInvalidationErrors); } } }; /** * Chain calls to functions that return this. */ final PassFactory chainCalls = new PassFactory("chainCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ChainCalls(compiler); } }; /** * Rewrite instance methods as static methods, to make them easier * to inline. */ final PassFactory devirtualizePrototypeMethods = new PassFactory("devirtualizePrototypeMethods", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DevirtualizePrototypeMethods(compiler); } }; /** * Optimizes unused function arguments, unused return values, and inlines * constant parameters. Also runs RemoveUnusedVars. */ final PassFactory optimizeCallsAndRemoveUnusedVars = new PassFactory("optimizeCalls_and_removeUnusedVars", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { OptimizeCalls passes = new OptimizeCalls(compiler); if (options.optimizeReturns) { // Remove unused return values. passes.addPass(new OptimizeReturns(compiler)); } if (options.optimizeParameters) { // Remove all parameters that are constants or unused. passes.addPass(new OptimizeParameters(compiler)); } if (options.optimizeCalls) { boolean removeOnlyLocals = options.removeUnusedLocalVars && !options.removeUnusedVars; boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; passes.addPass( new RemoveUnusedVars(compiler, !removeOnlyLocals, preserveAnonymousFunctionNames, true)); } return passes; } }; /** * Look for function calls that are pure, and annotate them * that way. */ final PassFactory markPureFunctions = new PassFactory("markPureFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PureFunctionIdentifier.Driver( compiler, options.debugFunctionSideEffectsPath, false); } }; /** * Look for function calls that have no side effects, and annotate them * that way. */ final PassFactory markNoSideEffectCalls = new PassFactory("markNoSideEffectCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MarkNoSideEffectCalls(compiler); } }; /** Inlines variables heuristically. */ final PassFactory inlineVariables = new PassFactory("inlineVariables", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (isInliningForbidden()) { // In old renaming schemes, inlining a variable can change whether // or not a property is renamed. This is bad, and those old renaming // schemes need to die. return new ErrorPass(compiler, CANNOT_USE_PROTOTYPE_AND_VAR); } else { InlineVariables.Mode mode; if (options.inlineVariables) { mode = InlineVariables.Mode.ALL; } else if (options.inlineLocalVariables) { mode = InlineVariables.Mode.LOCALS_ONLY; } else { throw new IllegalStateException("No variable inlining option set."); } return new InlineVariables(compiler, mode, true); } } }; /** Inlines variables that are marked as constants. */ final PassFactory inlineConstants = new PassFactory("inlineConstants", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineVariables( compiler, InlineVariables.Mode.CONSTANTS_ONLY, true); } }; /** * Perform local control flow optimizations. */ final PassFactory minimizeExitPoints = new PassFactory("minimizeExitPoints", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MinimizeExitPoints(compiler); } }; /** * Use data flow analysis to remove dead branches. */ final PassFactory removeUnreachableCode = new PassFactory("removeUnreachableCode", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new UnreachableCodeElimination(compiler, true); } }; /** * Remove prototype properties that do not appear to be used. */ final PassFactory removeUnusedPrototypeProperties = new PassFactory("removeUnusedPrototypeProperties", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RemoveUnusedPrototypeProperties( compiler, options.removeUnusedPrototypePropertiesInExterns, !options.removeUnusedVars); } }; /** * Remove prototype properties that do not appear to be used. */ final PassFactory removeUnusedClassProperties = new PassFactory("removeUnusedClassProperties", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RemoveUnusedClassProperties(compiler); } }; /** * Process smart name processing - removes unused classes and does referencing * starting with minimum set of names. */ final PassFactory smartNamePass = new PassFactory("smartNamePass", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnalyzer na = new NameAnalyzer(compiler, false); na.process(externs, root); String reportPath = options.reportPath; if (reportPath != null) { try { Files.write(na.getHtmlReport(), new File(reportPath), Charsets.UTF_8); } catch (IOException e) { compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath)); } } if (options.smartNameRemoval) { na.removeUnreferenced(); } } }; } }; /** * Process smart name processing - removes unused classes and does referencing * starting with minimum set of names. */ final PassFactory smartNamePass2 = new PassFactory("smartNamePass", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnalyzer na = new NameAnalyzer(compiler, false); na.process(externs, root); na.removeUnreferenced(); } }; } }; /** Inlines simple methods, like getters */ final PassFactory inlineSimpleMethods = new PassFactory("inlineSimpleMethods", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineSimpleMethods(compiler); } }; /** Kills dead assignments. */ final PassFactory deadAssignmentsElimination = new PassFactory("deadAssignmentsElimination", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DeadAssignmentsElimination(compiler); } }; /** Inlines function calls. */ final PassFactory inlineFunctions = new PassFactory("inlineFunctions", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean enableBlockInlining = !isInliningForbidden(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), options.inlineFunctions, options.inlineLocalFunctions, enableBlockInlining, options.assumeStrictThis() || options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT, options.assumeClosuresOnlyCaptureReferences); } }; /** Removes variables that are never used. */ final PassFactory removeUnusedVars = new PassFactory("removeUnusedVars", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean removeOnlyLocals = options.removeUnusedLocalVars && !options.removeUnusedVars; boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; return new RemoveUnusedVars( compiler, !removeOnlyLocals, preserveAnonymousFunctionNames, false); } }; /** * Move global symbols to a deeper common module */ final PassFactory crossModuleCodeMotion = new PassFactory("crossModuleCodeMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleCodeMotion(compiler, compiler.getModuleGraph()); } }; /** * Move methods to a deeper common module */ final PassFactory crossModuleMethodMotion = new PassFactory("crossModuleMethodMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleMethodMotion( compiler, crossModuleIdGenerator, // Only move properties in externs if we're not treating // them as exports. options.removeUnusedPrototypePropertiesInExterns); } }; /** * Specialize the initial module at the cost of later modules */ final PassFactory specializeInitialModule = new PassFactory("specializeInitialModule", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new SpecializeModule(compiler, devirtualizePrototypeMethods, inlineFunctions, removeUnusedPrototypeProperties); } }; /** A data-flow based variable inliner. */ final PassFactory flowSensitiveInlineVariables = new PassFactory("flowSensitiveInlineVariables", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FlowSensitiveInlineVariables(compiler); } }; /** Uses register-allocation algorithms to use fewer variables. */ final PassFactory coalesceVariableNames = new PassFactory("coalesceVariableNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CoalesceVariableNames(compiler, options.generatePseudoNames); } }; /** * Some simple, local collapses (e.g., {@code var x; var y;} becomes * {@code var x,y;}. */ final PassFactory exploitAssign = new PassFactory("exploitAssign", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PeepholeOptimizationsPass(compiler, new ExploitAssigns()); } }; /** * Some simple, local collapses (e.g., {@code var x; var y;} becomes * {@code var x,y;}. */ final PassFactory collapseVariableDeclarations = new PassFactory("collapseVariableDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseVariableDeclarations(compiler); } }; /** * Simple global collapses of variable declarations. */ final PassFactory groupVariableDeclarations = new PassFactory("groupVariableDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new GroupVariableDeclarations(compiler); } }; /** * Extracts common sub-expressions. */ final PassFactory extractPrototypeMemberDeclarations = new PassFactory("extractPrototypeMemberDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ExtractPrototypeMemberDeclarations( compiler, Pattern.USE_GLOBAL_TEMP); } }; /** Rewrites common function definitions to be more compact. */ final PassFactory rewriteFunctionExpressions = new PassFactory("rewriteFunctionExpressions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FunctionRewriter(compiler); } }; /** Collapses functions to not use the VAR keyword. */ final PassFactory collapseAnonymousFunctions = new PassFactory("collapseAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseAnonymousFunctions(compiler); } }; /** Moves function declarations to the top, to simulate actual hoisting. */ final PassFactory moveFunctionDeclarations = new PassFactory("moveFunctionDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MoveFunctionDeclarations(compiler); } }; final PassFactory nameUnmappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new NameAnonymousFunctions(compiler); } }; final PassFactory nameMappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnonymousFunctionsMapped naf = new NameAnonymousFunctionsMapped(compiler); naf.process(externs, root); anonymousFunctionNameMap = naf.getFunctionMap(); } }; } }; /** Alias external symbols. */ final PassFactory aliasExternals = new PassFactory("aliasExternals", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasExternals(compiler, compiler.getModuleGraph(), options.unaliasableGlobals, options.aliasableGlobals); } }; /** * Alias string literals with global variables, to avoid creating lots of * transient objects. */ final PassFactory aliasStrings = new PassFactory("aliasStrings", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasStrings( compiler, compiler.getModuleGraph(), options.aliasAllStrings ? null : options.aliasableStrings, options.aliasStringsBlacklist, options.outputJsStringUsage); } }; /** Aliases common keywords (true, false) */ final PassFactory aliasKeywords = new PassFactory("aliasKeywords", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasKeywords(compiler); } }; /** Handling for the ObjectPropertyString primitive. */ final PassFactory objectPropertyStringPostprocess = new PassFactory("ObjectPropertyStringPostprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPostprocess(compiler); } }; /** * Renames properties so that the two properties that never appear on * the same object get the same name. */ final PassFactory ambiguateProperties = new PassFactory("ambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AmbiguateProperties( compiler, options.anonymousFunctionNaming.getReservedCharacters()); } }; /** * Mark the point at which the normalized AST assumptions no longer hold. */ final PassFactory markUnnormalized = new PassFactory("markUnnormalized", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { compiler.setLifeCycleStage(LifeCycleStage.RAW); } }; } }; /** Denormalize the AST for code generation. */ final PassFactory denormalize = new PassFactory("denormalize", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new Denormalize(compiler); } }; /** Inverting name normalization. */ final PassFactory invertContextualRenaming = new PassFactory("invertNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler); } }; /** * Renames properties. */ final PassFactory renameProperties = new PassFactory("renameProperties", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputPropertyMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputPropertyMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_PROP_PARSE, e.getMessage())); } } final VariableMap prevPropertyMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { propertyMap = runPropertyRenaming( compiler, prevPropertyMap, externs, root); } }; } }; private VariableMap runPropertyRenaming( AbstractCompiler compiler, VariableMap prevPropertyMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); switch (options.propertyRenaming) { case HEURISTIC: RenamePrototypes rproto = new RenamePrototypes(compiler, false, reservedChars, prevPropertyMap); rproto.process(externs, root); return rproto.getPropertyMap(); case AGGRESSIVE_HEURISTIC: RenamePrototypes rproto2 = new RenamePrototypes(compiler, true, reservedChars, prevPropertyMap); rproto2.process(externs, root); return rproto2.getPropertyMap(); case ALL_UNQUOTED: RenameProperties rprop = new RenameProperties( compiler, options.propertyAffinity, options.generatePseudoNames, prevPropertyMap, reservedChars); rprop.process(externs, root); return rprop.getPropertyMap(); default: throw new IllegalStateException( "Unrecognized property renaming policy"); } } /** Renames variables. */ final PassFactory renameVars = new PassFactory("renameVars", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputVariableMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputVariableMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_VAR_PARSE, e.getMessage())); } } final VariableMap prevVariableMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { variableMap = runVariableRenaming( compiler, prevVariableMap, externs, root); } }; } }; private VariableMap runVariableRenaming( AbstractCompiler compiler, VariableMap prevVariableMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; RenameVars rn = new RenameVars( compiler, options.renamePrefix, options.variableRenaming == VariableRenamingPolicy.LOCAL, preserveAnonymousFunctionNames, options.generatePseudoNames, options.shadowVariables, prevVariableMap, reservedChars, exportedNames); rn.process(externs, root); return rn.getVariableMap(); } /** Renames labels */ final PassFactory renameLabels = new PassFactory("renameLabels", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RenameLabels(compiler); } }; /** Convert bracket access to dot access */ final PassFactory convertToDottedProperties = new PassFactory("convertToDottedProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConvertToDottedProperties(compiler); } }; /** Checks that all variables are defined. */ final PassFactory sanityCheckAst = new PassFactory("sanityCheckAst", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AstValidator(); } }; /** Checks that all variables are defined. */ final PassFactory sanityCheckVars = new PassFactory("sanityCheckVars", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler, true); } }; /** Adds instrumentations according to an instrumentation template. */ final PassFactory instrumentFunctions = new PassFactory("instrumentFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { try { FileReader templateFile = new FileReader(options.instrumentationTemplate); (new InstrumentFunctions( compiler, functionNames, options.instrumentationTemplate, options.appNameStr, templateFile)).process(externs, root); } catch (IOException e) { compiler.report( JSError.make(AbstractCompiler.READ_ERROR, options.instrumentationTemplate)); } } }; } }; /** * Create a no-op pass that can only run once. Used to break up loops. */ static PassFactory createEmptyPass(String name) { return new PassFactory(name, true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(); } }; } /** * Runs custom passes that are designated to run at a particular time. */ private PassFactory getCustomPasses( final CustomPassExecutionTime executionTime) { return new PassFactory("runCustomPasses", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(options.customPasses.get(executionTime)); } }; } /** * All inlining is forbidden in heuristic renaming mode, because inlining * will ruin the invariants that it depends on. */ private boolean isInliningForbidden() { return options.propertyRenaming == PropertyRenamingPolicy.HEURISTIC || options.propertyRenaming == PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC; } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial(final CompilerPass ... passes) { return runInSerial(Lists.newArrayList(passes)); } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial( final Collection<CompilerPass> passes) { return new CompilerPass() { @Override public void process(Node externs, Node root) { for (CompilerPass pass : passes) { pass.process(externs, root); } } }; } @VisibleForTesting static Map<String, Node> getAdditionalReplacements( CompilerOptions options) { Map<String, Node> additionalReplacements = Maps.newHashMap(); if (options.markAsCompiled || options.closurePass) { additionalReplacements.put(COMPILED_CONSTANT_NAME, IR.trueNode()); } if (options.closurePass && options.locale != null) { additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME, IR.string(options.locale)); } return additionalReplacements; } final PassFactory printNameReferenceGraph = new PassFactory("printNameReferenceGraph", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { NameReferenceGraphConstruction gc = new NameReferenceGraphConstruction(compiler); gc.process(externs, jsRoot); String graphFileName = options.nameReferenceGraphPath; try { Files.write(DotFormatter.toDot(gc.getNameReferenceGraph()), new File(graphFileName), Charsets.UTF_8); } catch (IOException e) { compiler.report( JSError.make( NAME_REF_GRAPH_FILE_ERROR, e.getMessage(), graphFileName)); } } }; } }; final PassFactory printNameReferenceReport = new PassFactory("printNameReferenceReport", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { NameReferenceGraphConstruction gc = new NameReferenceGraphConstruction(compiler); String reportFileName = options.nameReferenceReportPath; try { NameReferenceGraphReport report = new NameReferenceGraphReport(gc.getNameReferenceGraph()); Files.write(report.getHtmlReport(), new File(reportFileName), Charsets.UTF_8); } catch (IOException e) { compiler.report( JSError.make( NAME_REF_REPORT_FILE_ERROR, e.getMessage(), reportFileName)); } } }; } }; /** * A pass-factory that is good for {@code HotSwapCompilerPass} passes. */ abstract static class HotSwapPassFactory extends PassFactory { HotSwapPassFactory(String name, boolean isOneTimePass) { super(name, isOneTimePass); } @Override protected abstract HotSwapCompilerPass createInternal(AbstractCompiler compiler); @Override HotSwapCompilerPass getHotSwapPass(AbstractCompiler compiler) { return this.createInternal(compiler); } } }
true
true
protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); passes.add(garbageCollectChecks); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (options.replaceIdGenerators) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && (options.removeAbstractMethods || options.removeClosureAsserts)) { passes.add(closureCodeRemoval); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // ReplaceStrings runs after CollapseProperties in order to simplify // pulling in values of constants defined in enums structures. if (!options.replaceStringsFunctionDescriptions.isEmpty()) { passes.add(replaceStrings); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // This needs to come after the inline constants pass, which is run within // the code removing passes. if (options.closurePass) { passes.add(closureOptimizePrimitives); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); if (options.specializeInitialModule) { // When specializing the initial module, we want our fixups to be // as lean as possible, so we run the entire optimization loop to a // fixed point before specializing, then specialize, and then run the // main optimization loop again. passes.addAll(getMainOptimizationLoop()); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(specializeInitialModule.makeOneTimePass()); } passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } // Running this pass again is required to have goog.events compile down to // nothing when compiled on its own. if (options.smartNameRemoval) { passes.add(smartNamePass2); } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations || // renamePrefixNamescape relies on moveFunctionDeclarations // to preserve semantics. options.renamePrefixNamespace != null) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } // Passes after this point can no longer depend on normalized AST // assumptions. passes.add(markUnnormalized); if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); // coalesceVariables creates identity assignments and more redundant code // that can be removed, rerun the peephole optimizations to clean them // up. if (options.foldConstants) { passes.add(peepholeOptimizations); } } if (options.collapseVariableDeclarations) { passes.add(exploitAssign); passes.add(collapseVariableDeclarations); } // This pass works best after collapseVariableDeclarations. passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } if (options.groupVariableDeclarations) { passes.add(groupVariableDeclarations); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.foldConstants) { passes.add(latePeepholeOptimizations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } if (options.renamePrefixNamespace != null) { if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher( options.renamePrefixNamespace).matches()) { throw new IllegalArgumentException( "Illegal character in renamePrefixNamespace name: " + options.renamePrefixNamespace); } passes.add(rescopeGlobalSymbols); } passes.add(stripSideEffectProtection); // Safety checks passes.add(sanityCheckAst); passes.add(sanityCheckVars); return passes; }
protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); passes.add(garbageCollectChecks); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (options.replaceIdGenerators) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && (options.removeAbstractMethods || options.removeClosureAsserts)) { passes.add(closureCodeRemoval); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // ReplaceStrings runs after CollapseProperties in order to simplify // pulling in values of constants defined in enums structures. if (!options.replaceStringsFunctionDescriptions.isEmpty()) { passes.add(replaceStrings); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // This needs to come after the inline constants pass, which is run within // the code removing passes. if (options.closurePass) { passes.add(closureOptimizePrimitives); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); if (options.specializeInitialModule) { // When specializing the initial module, we want our fixups to be // as lean as possible, so we run the entire optimization loop to a // fixed point before specializing, then specialize, and then run the // main optimization loop again. passes.addAll(getMainOptimizationLoop()); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(specializeInitialModule.makeOneTimePass()); } passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars || options.removeUnusedLocalVars) { passes.add(removeUnusedVars); } } // Running this pass again is required to have goog.events compile down to // nothing when compiled on its own. if (options.smartNameRemoval) { passes.add(smartNamePass2); } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations || // renamePrefixNamescape relies on moveFunctionDeclarations // to preserve semantics. options.renamePrefixNamespace != null) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } // Passes after this point can no longer depend on normalized AST // assumptions. passes.add(markUnnormalized); if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); // coalesceVariables creates identity assignments and more redundant code // that can be removed, rerun the peephole optimizations to clean them // up. if (options.foldConstants) { passes.add(peepholeOptimizations); } } if (options.collapseVariableDeclarations) { passes.add(exploitAssign); passes.add(collapseVariableDeclarations); } // This pass works best after collapseVariableDeclarations. passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } if (options.groupVariableDeclarations) { passes.add(groupVariableDeclarations); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.foldConstants) { passes.add(latePeepholeOptimizations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } if (options.renamePrefixNamespace != null) { if (!GLOBAL_SYMBOL_NAMESPACE_PATTERN.matcher( options.renamePrefixNamespace).matches()) { throw new IllegalArgumentException( "Illegal character in renamePrefixNamespace name: " + options.renamePrefixNamespace); } passes.add(rescopeGlobalSymbols); } passes.add(stripSideEffectProtection); // Safety checks passes.add(sanityCheckAst); passes.add(sanityCheckVars); return passes; }
diff --git a/se.softhouse.garden.orchid.spring/src/main/java/se/softhouse/garden/orchid/spring/utils/LinkUtil.java b/se.softhouse.garden.orchid.spring/src/main/java/se/softhouse/garden/orchid/spring/utils/LinkUtil.java index 6e5b530..67bdd39 100644 --- a/se.softhouse.garden.orchid.spring/src/main/java/se/softhouse/garden/orchid/spring/utils/LinkUtil.java +++ b/se.softhouse.garden.orchid.spring/src/main/java/se/softhouse/garden/orchid/spring/utils/LinkUtil.java @@ -1,86 +1,90 @@ /** * Copyright (c) 2011, Mikael Svahn, Softhouse Consulting AB * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so: * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package se.softhouse.garden.orchid.spring.utils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; /** * @author Mikael Svahn * */ public class LinkUtil { static final String URL_TYPE_ABSOLUTE = "://"; /** * Sets the value of the URL */ public static UrlType getType(String url) { if (url.contains(URL_TYPE_ABSOLUTE)) { return UrlType.ABSOLUTE; } else if (url.startsWith("/")) { return UrlType.CONTEXT_RELATIVE; } else { return UrlType.RELATIVE; } } /** * Build the URL for the tag from the tag attributes and parameters. * * @param request2 * * @param response * * @return the URL value as a String * @throws JspException */ public static String createUrl(String link, HttpServletRequest request, HttpServletResponse response) { StringBuilder url = new StringBuilder(); UrlType type = getType(link); if (type == UrlType.CONTEXT_RELATIVE) { // add application context to url url.append(request.getContextPath()); } if (type != UrlType.RELATIVE && type != UrlType.ABSOLUTE && !link.startsWith("/")) { url.append("/"); } url.append(link); String urlStr = url.toString(); if (type != UrlType.ABSOLUTE && response != null) { // Add the session identifier if needed // (Do not embed the session identifier in a remote link!) - urlStr = response.encodeURL(urlStr); + try { + urlStr = response.encodeURL(urlStr); + } catch (Throwable e) { + // Ignore errors + } } return urlStr; } } /** * Internal enum that classifies URLs by type. */ enum UrlType { CONTEXT_RELATIVE, RELATIVE, ABSOLUTE }
true
true
public static String createUrl(String link, HttpServletRequest request, HttpServletResponse response) { StringBuilder url = new StringBuilder(); UrlType type = getType(link); if (type == UrlType.CONTEXT_RELATIVE) { // add application context to url url.append(request.getContextPath()); } if (type != UrlType.RELATIVE && type != UrlType.ABSOLUTE && !link.startsWith("/")) { url.append("/"); } url.append(link); String urlStr = url.toString(); if (type != UrlType.ABSOLUTE && response != null) { // Add the session identifier if needed // (Do not embed the session identifier in a remote link!) urlStr = response.encodeURL(urlStr); } return urlStr; }
public static String createUrl(String link, HttpServletRequest request, HttpServletResponse response) { StringBuilder url = new StringBuilder(); UrlType type = getType(link); if (type == UrlType.CONTEXT_RELATIVE) { // add application context to url url.append(request.getContextPath()); } if (type != UrlType.RELATIVE && type != UrlType.ABSOLUTE && !link.startsWith("/")) { url.append("/"); } url.append(link); String urlStr = url.toString(); if (type != UrlType.ABSOLUTE && response != null) { // Add the session identifier if needed // (Do not embed the session identifier in a remote link!) try { urlStr = response.encodeURL(urlStr); } catch (Throwable e) { // Ignore errors } } return urlStr; }
diff --git a/src/main/java/com/senseidb/clue/commands/DocSetInfoCommand.java b/src/main/java/com/senseidb/clue/commands/DocSetInfoCommand.java index a020291..391e7a0 100644 --- a/src/main/java/com/senseidb/clue/commands/DocSetInfoCommand.java +++ b/src/main/java/com/senseidb/clue/commands/DocSetInfoCommand.java @@ -1,135 +1,135 @@ package com.senseidb.clue.commands; import java.io.PrintStream; import java.util.Arrays; import java.util.List; import org.apache.lucene.index.AtomicReader; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.util.BytesRef; import com.senseidb.clue.ClueContext; public class DocSetInfoCommand extends ClueCommand { private static final int DEFAULT_BUCKET_SIZE = 1000; public DocSetInfoCommand(ClueContext ctx) { super(ctx); } @Override public String getName() { return "docsetinfo"; } @Override public String help() { return "doc id set info and stats"; } private static double[] PERCENTILES = new double[] { 50.0, 75.0, 90.0, 95.0, 99.0 }; @Override public void execute(String[] args, PrintStream out) throws Exception { String field = null; String termVal = null; int bucketSize = DEFAULT_BUCKET_SIZE; try{ field = args[0]; } catch(Exception e){ field = null; } try { bucketSize = Integer.parseInt(args[1]); } catch(Exception e){ } if (field != null){ String[] parts = field.split(":"); if (parts.length > 1){ field = parts[0]; termVal = parts[1]; } } if (field == null || termVal == null){ out.println("usage: field:term"); out.flush(); return; } IndexReader reader = ctx.getIndexReader(); List<AtomicReaderContext> leaves = reader.leaves(); for (AtomicReaderContext leaf : leaves) { AtomicReader atomicReader = leaf.reader(); Terms terms = atomicReader.terms(field); if (terms == null){ continue; } if (terms != null && termVal != null){ TermsEnum te = terms.iterator(null); if (te.seekExact(new BytesRef(termVal))){ DocsEnum iter = te.docs(atomicReader.getLiveDocs(), null); int docFreq = te.docFreq(); int minDocId = -1, maxDocId = -1; int doc, count = 0; int[] percentDocs = new int[PERCENTILES.length]; int percentileIdx = 0; while ((doc = iter.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { maxDocId = doc; if (minDocId == -1) { minDocId = doc; } count ++; double perDocs = (double) count / (double) docFreq * 100.0; while (percentileIdx < percentDocs.length) { if (perDocs > PERCENTILES[percentileIdx]) { percentDocs[percentileIdx] = doc; percentileIdx++; } else { break; } } } // calculate histogram int[] buckets = null; if (maxDocId > 0) { buckets = new int[maxDocId / bucketSize + 1]; iter = te.docs(atomicReader.getLiveDocs(), null); while ((doc = iter.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { int bucketIdx = doc / bucketSize; buckets[bucketIdx]++; } } double density = (double) docFreq / (double) (maxDocId - minDocId) ; out.println(String.format("min: %d, max: %d, count: %d, density: %.2f", minDocId, maxDocId, docFreq, density)); out.println("percentiles: " + Arrays.toString(PERCENTILES) + " => " + Arrays.toString(percentDocs)); - out.println("histograms: (bucketsize=" + bucketSize+")"); + out.println("histogram: (bucketsize=" + bucketSize+")"); out.println(Arrays.toString(buckets)); } } } } }
true
true
public void execute(String[] args, PrintStream out) throws Exception { String field = null; String termVal = null; int bucketSize = DEFAULT_BUCKET_SIZE; try{ field = args[0]; } catch(Exception e){ field = null; } try { bucketSize = Integer.parseInt(args[1]); } catch(Exception e){ } if (field != null){ String[] parts = field.split(":"); if (parts.length > 1){ field = parts[0]; termVal = parts[1]; } } if (field == null || termVal == null){ out.println("usage: field:term"); out.flush(); return; } IndexReader reader = ctx.getIndexReader(); List<AtomicReaderContext> leaves = reader.leaves(); for (AtomicReaderContext leaf : leaves) { AtomicReader atomicReader = leaf.reader(); Terms terms = atomicReader.terms(field); if (terms == null){ continue; } if (terms != null && termVal != null){ TermsEnum te = terms.iterator(null); if (te.seekExact(new BytesRef(termVal))){ DocsEnum iter = te.docs(atomicReader.getLiveDocs(), null); int docFreq = te.docFreq(); int minDocId = -1, maxDocId = -1; int doc, count = 0; int[] percentDocs = new int[PERCENTILES.length]; int percentileIdx = 0; while ((doc = iter.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { maxDocId = doc; if (minDocId == -1) { minDocId = doc; } count ++; double perDocs = (double) count / (double) docFreq * 100.0; while (percentileIdx < percentDocs.length) { if (perDocs > PERCENTILES[percentileIdx]) { percentDocs[percentileIdx] = doc; percentileIdx++; } else { break; } } } // calculate histogram int[] buckets = null; if (maxDocId > 0) { buckets = new int[maxDocId / bucketSize + 1]; iter = te.docs(atomicReader.getLiveDocs(), null); while ((doc = iter.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { int bucketIdx = doc / bucketSize; buckets[bucketIdx]++; } } double density = (double) docFreq / (double) (maxDocId - minDocId) ; out.println(String.format("min: %d, max: %d, count: %d, density: %.2f", minDocId, maxDocId, docFreq, density)); out.println("percentiles: " + Arrays.toString(PERCENTILES) + " => " + Arrays.toString(percentDocs)); out.println("histograms: (bucketsize=" + bucketSize+")"); out.println(Arrays.toString(buckets)); } } } }
public void execute(String[] args, PrintStream out) throws Exception { String field = null; String termVal = null; int bucketSize = DEFAULT_BUCKET_SIZE; try{ field = args[0]; } catch(Exception e){ field = null; } try { bucketSize = Integer.parseInt(args[1]); } catch(Exception e){ } if (field != null){ String[] parts = field.split(":"); if (parts.length > 1){ field = parts[0]; termVal = parts[1]; } } if (field == null || termVal == null){ out.println("usage: field:term"); out.flush(); return; } IndexReader reader = ctx.getIndexReader(); List<AtomicReaderContext> leaves = reader.leaves(); for (AtomicReaderContext leaf : leaves) { AtomicReader atomicReader = leaf.reader(); Terms terms = atomicReader.terms(field); if (terms == null){ continue; } if (terms != null && termVal != null){ TermsEnum te = terms.iterator(null); if (te.seekExact(new BytesRef(termVal))){ DocsEnum iter = te.docs(atomicReader.getLiveDocs(), null); int docFreq = te.docFreq(); int minDocId = -1, maxDocId = -1; int doc, count = 0; int[] percentDocs = new int[PERCENTILES.length]; int percentileIdx = 0; while ((doc = iter.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { maxDocId = doc; if (minDocId == -1) { minDocId = doc; } count ++; double perDocs = (double) count / (double) docFreq * 100.0; while (percentileIdx < percentDocs.length) { if (perDocs > PERCENTILES[percentileIdx]) { percentDocs[percentileIdx] = doc; percentileIdx++; } else { break; } } } // calculate histogram int[] buckets = null; if (maxDocId > 0) { buckets = new int[maxDocId / bucketSize + 1]; iter = te.docs(atomicReader.getLiveDocs(), null); while ((doc = iter.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { int bucketIdx = doc / bucketSize; buckets[bucketIdx]++; } } double density = (double) docFreq / (double) (maxDocId - minDocId) ; out.println(String.format("min: %d, max: %d, count: %d, density: %.2f", minDocId, maxDocId, docFreq, density)); out.println("percentiles: " + Arrays.toString(PERCENTILES) + " => " + Arrays.toString(percentDocs)); out.println("histogram: (bucketsize=" + bucketSize+")"); out.println(Arrays.toString(buckets)); } } } }
diff --git a/src/com/atlauncher/gui/InstanceInstallerDialog.java b/src/com/atlauncher/gui/InstanceInstallerDialog.java index d81b4f0d..a6d75b2f 100644 --- a/src/com/atlauncher/gui/InstanceInstallerDialog.java +++ b/src/com/atlauncher/gui/InstanceInstallerDialog.java @@ -1,484 +1,484 @@ /** * Copyright 2013 by ATLauncher and Contributors * * This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/. */ package com.atlauncher.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.concurrent.ExecutionException; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JTextField; import com.atlauncher.App; import com.atlauncher.data.Instance; import com.atlauncher.data.Pack; import com.atlauncher.data.Version; import com.atlauncher.workers.InstanceInstaller; public class InstanceInstallerDialog extends JDialog { private boolean isReinstall = false; private boolean isServer = false; private Pack pack = null; private Instance instance = null; private JPanel top; private JPanel middle; private JPanel bottom; private JButton install; private JButton cancel; private JProgressBar progressBar; private JProgressBar subProgressBar; private JLabel instanceNameLabel; private JTextField instanceNameField; private JLabel versionLabel; private JComboBox<Version> versionsDropDown; private JLabel installForLabel; private JCheckBox installForMe; private JLabel useLatestLWJGLLabel; private JCheckBox useLatestLWJGL; public InstanceInstallerDialog(Object object) { this(object, false, false); } public InstanceInstallerDialog(Pack pack, boolean isServer) { this((Object) pack, false, true); } public InstanceInstallerDialog(Object object, boolean isUpdate, final boolean isServer) { super(App.settings.getParent(), ModalityType.APPLICATION_MODAL); if (object instanceof Pack) { pack = (Pack) object; setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName()); if (isServer) { setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName() + " " + App.settings.getLocalizedString("common.server")); this.isServer = true; } } else { instance = (Instance) object; pack = instance.getRealPack(); isReinstall = true; // We're reinstalling setTitle(App.settings.getLocalizedString("common.reinstalling") + " " + instance.getName()); } setSize(400, 225); setLocationRelativeTo(App.settings.getParent()); setLayout(new BorderLayout()); setResizable(false); // Top Panel Stuff top = new JPanel(); top.add(new JLabel(((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName())); // Middle Panel Stuff middle = new JPanel(); middle.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; if (!this.isServer) { gbc.anchor = GridBagConstraints.BASELINE_TRAILING; instanceNameLabel = new JLabel(App.settings.getLocalizedString("instance.name") + ": "); middle.add(instanceNameLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; instanceNameField = new JTextField(17); instanceNameField.setText(((isReinstall) ? instance.getName() : pack.getName())); if (isReinstall) { instanceNameField.setEnabled(false); } middle.add(instanceNameField, gbc); gbc.gridx = 0; gbc.gridy++; } gbc.anchor = GridBagConstraints.BASELINE_TRAILING; versionLabel = new JLabel(App.settings.getLocalizedString("instance.versiontoinstall") + ": "); middle.add(versionLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; versionsDropDown = new JComboBox<Version>(); if (pack.isTester()) { for (int i = 0; i < pack.getDevVersionCount(); i++) { versionsDropDown.addItem(new Version(true, pack.getDevVersion(i), pack .getDevMinecraftVersion(i))); } } for (int i = 0; i < pack.getVersionCount(); i++) { versionsDropDown.addItem(new Version(false, pack.getVersion(i), pack .getMinecraftVersion(i))); } if (isUpdate) { versionsDropDown.setSelectedIndex(0); } else if (isReinstall) { versionsDropDown.setSelectedItem(instance.getVersion()); } versionsDropDown.setPreferredSize(new Dimension(200, 25)); versionsDropDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Version selected = (Version) versionsDropDown.getSelectedItem(); if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } }); middle.add(versionsDropDown, gbc); if (!this.isServer) { if (!isReinstall) { gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; installForLabel = new JLabel( App.settings.getLocalizedString("instance.installjustforme") + "? "); middle.add(installForLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; installForMe = new JCheckBox(); middle.add(installForMe, gbc); } gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; useLatestLWJGLLabel = new JLabel( App.settings.getLocalizedString("instance.uselatestlwjgl") + "? "); middle.add(useLatestLWJGLLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; useLatestLWJGL = new JCheckBox(); middle.add(useLatestLWJGL, gbc); } Version selected = (Version) versionsDropDown.getSelectedItem(); if (!isServer) { if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } // Bottom Panel Stuff bottom = new JPanel(); bottom.setLayout(new FlowLayout()); install = new JButton( ((isReinstall) ? (isUpdate ? App.settings.getLocalizedString("common.update") : App.settings.getLocalizedString("common.reinstall")) : App.settings.getLocalizedString("common.install"))); install.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isReinstall && !isServer && App.settings.isInstance(instanceNameField.getText())) { JOptionPane.showMessageDialog( App.settings.getParent(), "<html><center>" + App.settings.getLocalizedString("common.error") + "<br/><br/>" + App.settings.getLocalizedString("instance.alreadyinstance", instanceNameField.getText() + "<br/><br/>") + "</center></html>", App.settings .getLocalizedString("common.error"), JOptionPane.ERROR_MESSAGE); return; } final Version version = (Version) versionsDropDown.getSelectedItem(); final JDialog dialog = new JDialog(App.settings.getParent(), ((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName() + " " + version.getVersion(), ModalityType.DOCUMENT_MODAL); dialog.setLocationRelativeTo(App.settings.getParent()); dialog.setSize(300, 100); dialog.setResizable(false); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); final JLabel doing = new JLabel(App.settings.getLocalizedString( "instance.startingprocess", ((isReinstall) ? App.settings.getLocalizedString("common.reinstall") : App.settings.getLocalizedString("common.install")))); doing.setHorizontalAlignment(JLabel.CENTER); doing.setVerticalAlignment(JLabel.TOP); topPanel.add(doing); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); progressBar = new JProgressBar(0, 100); bottomPanel.add(progressBar, BorderLayout.NORTH); progressBar.setIndeterminate(true); subProgressBar = new JProgressBar(0, 100); bottomPanel.add(subProgressBar, BorderLayout.SOUTH); subProgressBar.setValue(0); subProgressBar.setVisible(false); dialog.add(topPanel, BorderLayout.CENTER); dialog.add(bottomPanel, BorderLayout.SOUTH); final InstanceInstaller instanceInstaller = new InstanceInstaller((isServer ? "" : instanceNameField.getText()), pack, version.getVersion(), version .getMinecraftVersion(), (useLatestLWJGL == null ? false : useLatestLWJGL .isSelected()), isReinstall, isServer) { protected void done() { Boolean success = false; int type; String text; String title; if (isCancelled()) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " - + version + + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.actioncancelled"); title = pack.getName() + " " - + version + + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")); if (isReinstall) { App.settings.setInstanceUnplayable(instance); } } else { try { success = get(); } catch (InterruptedException e) { App.settings.getConsole().logStackTrace(e); } catch (ExecutionException e) { App.settings.getConsole().logStackTrace(e); } if (success) { type = JOptionPane.INFORMATION_MESSAGE; text = pack.getName() + " " - + version + + version.getVersion() + " " + App.settings.getLocalizedString("common.hasbeen") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings .getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.findit"); - title = pack.getName() + " " + version + " " + title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.installed"); if (isReinstall) { instance.setVersion(version.getVersion()); instance.setMinecraftVersion(this.getMinecraftVersion()); instance.setModsInstalled(this.getModsInstalled()); instance.setJarOrder(this.getJarOrder()); instance.setIsNewLaunchMethod(this.isNewLaunchMethod()); if (this.isNewLaunchMethod()) { instance.setLibrariesNeeded(this.getLibrariesNeeded()); instance.setMinecraftArguments(this.getMinecraftArguments()); instance.setMainClass(this.getMainClass()); } if (version.isDevVersion()) { instance.setDevVersion(); } else { instance.setNotDevVersion(); } if (!instance.isPlayable()) { instance.setPlayable(); } } else if (isServer) { } else { App.settings.getInstances().add( new Instance(instanceNameField.getText(), pack .getName(), pack, installForMe.isSelected(), version.getVersion(), this .getMinecraftVersion(), this .getPermGen(), this.getModsInstalled(), this.getJarOrder(), this.getLibrariesNeeded(), this.getMinecraftArguments(), this .getMainClass(), version.isDevVersion(), this .isNewLaunchMethod())); // Add It } App.settings.saveInstances(); App.settings.reloadInstancesPanel(); if (pack.isLoggingEnabled() && App.settings.enableLogs()) { App.settings.apiCall(App.settings.getAccount() .getMinecraftUsername(), "packinstalled", pack.getID() + "", version.getVersion()); } } else { if (isReinstall) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " - + version + + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.reinstalled") + "<br/><br/>" + App.settings .getLocalizedString("instance.nolongerplayable") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; - title = pack.getName() + " " + version + " " + title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.reinstalled"); App.settings.setInstanceUnplayable(instance); } else { // Install failed so delete the folder and clear Temp Dir Utils.delete(this.getRootDirectory()); type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " - + version + + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.installed") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; - title = pack.getName() + " " + version + " " + title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.installed"); } } } dialog.dispose(); Utils.cleanTempDirectory(); JOptionPane.showMessageDialog(App.settings.getParent(), "<html><center>" + text + "</center></html>", title, type); } }; instanceInstaller.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } progressBar.setValue(progress); } else if ("subprogress" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } if (progress == 0) { subProgressBar.setVisible(false); } subProgressBar.setValue(progress); } else if ("subprogressint" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (!subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(true); } } else if ("doing" == evt.getPropertyName()) { String doingText = (String) evt.getNewValue(); doing.setText(doingText); } } }); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { instanceInstaller.cancel(true); } }); if (isReinstall) { instanceInstaller.setInstance(instance); } instanceInstaller.execute(); dispose(); dialog.setVisible(true); } }); cancel = new JButton(App.settings.getLocalizedString("common.cancel")); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); bottom.add(install); bottom.add(cancel); add(top, BorderLayout.NORTH); add(middle, BorderLayout.CENTER); add(bottom, BorderLayout.SOUTH); setVisible(true); } }
false
true
public InstanceInstallerDialog(Object object, boolean isUpdate, final boolean isServer) { super(App.settings.getParent(), ModalityType.APPLICATION_MODAL); if (object instanceof Pack) { pack = (Pack) object; setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName()); if (isServer) { setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName() + " " + App.settings.getLocalizedString("common.server")); this.isServer = true; } } else { instance = (Instance) object; pack = instance.getRealPack(); isReinstall = true; // We're reinstalling setTitle(App.settings.getLocalizedString("common.reinstalling") + " " + instance.getName()); } setSize(400, 225); setLocationRelativeTo(App.settings.getParent()); setLayout(new BorderLayout()); setResizable(false); // Top Panel Stuff top = new JPanel(); top.add(new JLabel(((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName())); // Middle Panel Stuff middle = new JPanel(); middle.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; if (!this.isServer) { gbc.anchor = GridBagConstraints.BASELINE_TRAILING; instanceNameLabel = new JLabel(App.settings.getLocalizedString("instance.name") + ": "); middle.add(instanceNameLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; instanceNameField = new JTextField(17); instanceNameField.setText(((isReinstall) ? instance.getName() : pack.getName())); if (isReinstall) { instanceNameField.setEnabled(false); } middle.add(instanceNameField, gbc); gbc.gridx = 0; gbc.gridy++; } gbc.anchor = GridBagConstraints.BASELINE_TRAILING; versionLabel = new JLabel(App.settings.getLocalizedString("instance.versiontoinstall") + ": "); middle.add(versionLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; versionsDropDown = new JComboBox<Version>(); if (pack.isTester()) { for (int i = 0; i < pack.getDevVersionCount(); i++) { versionsDropDown.addItem(new Version(true, pack.getDevVersion(i), pack .getDevMinecraftVersion(i))); } } for (int i = 0; i < pack.getVersionCount(); i++) { versionsDropDown.addItem(new Version(false, pack.getVersion(i), pack .getMinecraftVersion(i))); } if (isUpdate) { versionsDropDown.setSelectedIndex(0); } else if (isReinstall) { versionsDropDown.setSelectedItem(instance.getVersion()); } versionsDropDown.setPreferredSize(new Dimension(200, 25)); versionsDropDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Version selected = (Version) versionsDropDown.getSelectedItem(); if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } }); middle.add(versionsDropDown, gbc); if (!this.isServer) { if (!isReinstall) { gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; installForLabel = new JLabel( App.settings.getLocalizedString("instance.installjustforme") + "? "); middle.add(installForLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; installForMe = new JCheckBox(); middle.add(installForMe, gbc); } gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; useLatestLWJGLLabel = new JLabel( App.settings.getLocalizedString("instance.uselatestlwjgl") + "? "); middle.add(useLatestLWJGLLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; useLatestLWJGL = new JCheckBox(); middle.add(useLatestLWJGL, gbc); } Version selected = (Version) versionsDropDown.getSelectedItem(); if (!isServer) { if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } // Bottom Panel Stuff bottom = new JPanel(); bottom.setLayout(new FlowLayout()); install = new JButton( ((isReinstall) ? (isUpdate ? App.settings.getLocalizedString("common.update") : App.settings.getLocalizedString("common.reinstall")) : App.settings.getLocalizedString("common.install"))); install.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isReinstall && !isServer && App.settings.isInstance(instanceNameField.getText())) { JOptionPane.showMessageDialog( App.settings.getParent(), "<html><center>" + App.settings.getLocalizedString("common.error") + "<br/><br/>" + App.settings.getLocalizedString("instance.alreadyinstance", instanceNameField.getText() + "<br/><br/>") + "</center></html>", App.settings .getLocalizedString("common.error"), JOptionPane.ERROR_MESSAGE); return; } final Version version = (Version) versionsDropDown.getSelectedItem(); final JDialog dialog = new JDialog(App.settings.getParent(), ((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName() + " " + version.getVersion(), ModalityType.DOCUMENT_MODAL); dialog.setLocationRelativeTo(App.settings.getParent()); dialog.setSize(300, 100); dialog.setResizable(false); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); final JLabel doing = new JLabel(App.settings.getLocalizedString( "instance.startingprocess", ((isReinstall) ? App.settings.getLocalizedString("common.reinstall") : App.settings.getLocalizedString("common.install")))); doing.setHorizontalAlignment(JLabel.CENTER); doing.setVerticalAlignment(JLabel.TOP); topPanel.add(doing); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); progressBar = new JProgressBar(0, 100); bottomPanel.add(progressBar, BorderLayout.NORTH); progressBar.setIndeterminate(true); subProgressBar = new JProgressBar(0, 100); bottomPanel.add(subProgressBar, BorderLayout.SOUTH); subProgressBar.setValue(0); subProgressBar.setVisible(false); dialog.add(topPanel, BorderLayout.CENTER); dialog.add(bottomPanel, BorderLayout.SOUTH); final InstanceInstaller instanceInstaller = new InstanceInstaller((isServer ? "" : instanceNameField.getText()), pack, version.getVersion(), version .getMinecraftVersion(), (useLatestLWJGL == null ? false : useLatestLWJGL .isSelected()), isReinstall, isServer) { protected void done() { Boolean success = false; int type; String text; String title; if (isCancelled()) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version + " " + App.settings.getLocalizedString("common.wasnt") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.actioncancelled"); title = pack.getName() + " " + version + " " + App.settings.getLocalizedString("common.not") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")); if (isReinstall) { App.settings.setInstanceUnplayable(instance); } } else { try { success = get(); } catch (InterruptedException e) { App.settings.getConsole().logStackTrace(e); } catch (ExecutionException e) { App.settings.getConsole().logStackTrace(e); } if (success) { type = JOptionPane.INFORMATION_MESSAGE; text = pack.getName() + " " + version + " " + App.settings.getLocalizedString("common.hasbeen") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings .getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.findit"); title = pack.getName() + " " + version + " " + App.settings.getLocalizedString("common.installed"); if (isReinstall) { instance.setVersion(version.getVersion()); instance.setMinecraftVersion(this.getMinecraftVersion()); instance.setModsInstalled(this.getModsInstalled()); instance.setJarOrder(this.getJarOrder()); instance.setIsNewLaunchMethod(this.isNewLaunchMethod()); if (this.isNewLaunchMethod()) { instance.setLibrariesNeeded(this.getLibrariesNeeded()); instance.setMinecraftArguments(this.getMinecraftArguments()); instance.setMainClass(this.getMainClass()); } if (version.isDevVersion()) { instance.setDevVersion(); } else { instance.setNotDevVersion(); } if (!instance.isPlayable()) { instance.setPlayable(); } } else if (isServer) { } else { App.settings.getInstances().add( new Instance(instanceNameField.getText(), pack .getName(), pack, installForMe.isSelected(), version.getVersion(), this .getMinecraftVersion(), this .getPermGen(), this.getModsInstalled(), this.getJarOrder(), this.getLibrariesNeeded(), this.getMinecraftArguments(), this .getMainClass(), version.isDevVersion(), this .isNewLaunchMethod())); // Add It } App.settings.saveInstances(); App.settings.reloadInstancesPanel(); if (pack.isLoggingEnabled() && App.settings.enableLogs()) { App.settings.apiCall(App.settings.getAccount() .getMinecraftUsername(), "packinstalled", pack.getID() + "", version.getVersion()); } } else { if (isReinstall) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.reinstalled") + "<br/><br/>" + App.settings .getLocalizedString("instance.nolongerplayable") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.reinstalled"); App.settings.setInstanceUnplayable(instance); } else { // Install failed so delete the folder and clear Temp Dir Utils.delete(this.getRootDirectory()); type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.installed") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.installed"); } } } dialog.dispose(); Utils.cleanTempDirectory(); JOptionPane.showMessageDialog(App.settings.getParent(), "<html><center>" + text + "</center></html>", title, type); } }; instanceInstaller.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } progressBar.setValue(progress); } else if ("subprogress" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } if (progress == 0) { subProgressBar.setVisible(false); } subProgressBar.setValue(progress); } else if ("subprogressint" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (!subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(true); } } else if ("doing" == evt.getPropertyName()) { String doingText = (String) evt.getNewValue(); doing.setText(doingText); } } }); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { instanceInstaller.cancel(true); } }); if (isReinstall) { instanceInstaller.setInstance(instance); } instanceInstaller.execute(); dispose(); dialog.setVisible(true); } }); cancel = new JButton(App.settings.getLocalizedString("common.cancel")); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); bottom.add(install); bottom.add(cancel); add(top, BorderLayout.NORTH); add(middle, BorderLayout.CENTER); add(bottom, BorderLayout.SOUTH); setVisible(true); }
public InstanceInstallerDialog(Object object, boolean isUpdate, final boolean isServer) { super(App.settings.getParent(), ModalityType.APPLICATION_MODAL); if (object instanceof Pack) { pack = (Pack) object; setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName()); if (isServer) { setTitle(App.settings.getLocalizedString("common.installing") + " " + pack.getName() + " " + App.settings.getLocalizedString("common.server")); this.isServer = true; } } else { instance = (Instance) object; pack = instance.getRealPack(); isReinstall = true; // We're reinstalling setTitle(App.settings.getLocalizedString("common.reinstalling") + " " + instance.getName()); } setSize(400, 225); setLocationRelativeTo(App.settings.getParent()); setLayout(new BorderLayout()); setResizable(false); // Top Panel Stuff top = new JPanel(); top.add(new JLabel(((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName())); // Middle Panel Stuff middle = new JPanel(); middle.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; if (!this.isServer) { gbc.anchor = GridBagConstraints.BASELINE_TRAILING; instanceNameLabel = new JLabel(App.settings.getLocalizedString("instance.name") + ": "); middle.add(instanceNameLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; instanceNameField = new JTextField(17); instanceNameField.setText(((isReinstall) ? instance.getName() : pack.getName())); if (isReinstall) { instanceNameField.setEnabled(false); } middle.add(instanceNameField, gbc); gbc.gridx = 0; gbc.gridy++; } gbc.anchor = GridBagConstraints.BASELINE_TRAILING; versionLabel = new JLabel(App.settings.getLocalizedString("instance.versiontoinstall") + ": "); middle.add(versionLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; versionsDropDown = new JComboBox<Version>(); if (pack.isTester()) { for (int i = 0; i < pack.getDevVersionCount(); i++) { versionsDropDown.addItem(new Version(true, pack.getDevVersion(i), pack .getDevMinecraftVersion(i))); } } for (int i = 0; i < pack.getVersionCount(); i++) { versionsDropDown.addItem(new Version(false, pack.getVersion(i), pack .getMinecraftVersion(i))); } if (isUpdate) { versionsDropDown.setSelectedIndex(0); } else if (isReinstall) { versionsDropDown.setSelectedItem(instance.getVersion()); } versionsDropDown.setPreferredSize(new Dimension(200, 25)); versionsDropDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Version selected = (Version) versionsDropDown.getSelectedItem(); if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } }); middle.add(versionsDropDown, gbc); if (!this.isServer) { if (!isReinstall) { gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; installForLabel = new JLabel( App.settings.getLocalizedString("instance.installjustforme") + "? "); middle.add(installForLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; installForMe = new JCheckBox(); middle.add(installForMe, gbc); } gbc.gridx = 0; gbc.gridy++; gbc.anchor = GridBagConstraints.BASELINE_TRAILING; useLatestLWJGLLabel = new JLabel( App.settings.getLocalizedString("instance.uselatestlwjgl") + "? "); middle.add(useLatestLWJGLLabel, gbc); gbc.gridx++; gbc.anchor = GridBagConstraints.BASELINE_LEADING; useLatestLWJGL = new JCheckBox(); middle.add(useLatestLWJGL, gbc); } Version selected = (Version) versionsDropDown.getSelectedItem(); if (!isServer) { if (App.settings.getMinecraftInstallMethod(selected.getMinecraftVersion()) .equalsIgnoreCase("new")) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); } else if (pack.isLatestLWJGLEnabled()) { useLatestLWJGLLabel.setVisible(false); useLatestLWJGL.setVisible(false); useLatestLWJGL.setSelected(true); } else { useLatestLWJGLLabel.setVisible(true); useLatestLWJGL.setVisible(true); } } // Bottom Panel Stuff bottom = new JPanel(); bottom.setLayout(new FlowLayout()); install = new JButton( ((isReinstall) ? (isUpdate ? App.settings.getLocalizedString("common.update") : App.settings.getLocalizedString("common.reinstall")) : App.settings.getLocalizedString("common.install"))); install.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isReinstall && !isServer && App.settings.isInstance(instanceNameField.getText())) { JOptionPane.showMessageDialog( App.settings.getParent(), "<html><center>" + App.settings.getLocalizedString("common.error") + "<br/><br/>" + App.settings.getLocalizedString("instance.alreadyinstance", instanceNameField.getText() + "<br/><br/>") + "</center></html>", App.settings .getLocalizedString("common.error"), JOptionPane.ERROR_MESSAGE); return; } final Version version = (Version) versionsDropDown.getSelectedItem(); final JDialog dialog = new JDialog(App.settings.getParent(), ((isReinstall) ? App.settings.getLocalizedString("common.reinstalling") : App.settings.getLocalizedString("common.installing")) + " " + pack.getName() + " " + version.getVersion(), ModalityType.DOCUMENT_MODAL); dialog.setLocationRelativeTo(App.settings.getParent()); dialog.setSize(300, 100); dialog.setResizable(false); JPanel topPanel = new JPanel(); topPanel.setLayout(new BorderLayout()); final JLabel doing = new JLabel(App.settings.getLocalizedString( "instance.startingprocess", ((isReinstall) ? App.settings.getLocalizedString("common.reinstall") : App.settings.getLocalizedString("common.install")))); doing.setHorizontalAlignment(JLabel.CENTER); doing.setVerticalAlignment(JLabel.TOP); topPanel.add(doing); JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BorderLayout()); progressBar = new JProgressBar(0, 100); bottomPanel.add(progressBar, BorderLayout.NORTH); progressBar.setIndeterminate(true); subProgressBar = new JProgressBar(0, 100); bottomPanel.add(subProgressBar, BorderLayout.SOUTH); subProgressBar.setValue(0); subProgressBar.setVisible(false); dialog.add(topPanel, BorderLayout.CENTER); dialog.add(bottomPanel, BorderLayout.SOUTH); final InstanceInstaller instanceInstaller = new InstanceInstaller((isServer ? "" : instanceNameField.getText()), pack, version.getVersion(), version .getMinecraftVersion(), (useLatestLWJGL == null ? false : useLatestLWJGL .isSelected()), isReinstall, isServer) { protected void done() { Boolean success = false; int type; String text; String title; if (isCancelled()) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.actioncancelled"); title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings.getLocalizedString("common.installed")); if (isReinstall) { App.settings.setInstanceUnplayable(instance); } } else { try { success = get(); } catch (InterruptedException e) { App.settings.getConsole().logStackTrace(e); } catch (ExecutionException e) { App.settings.getConsole().logStackTrace(e); } if (success) { type = JOptionPane.INFORMATION_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.hasbeen") + " " + ((isReinstall) ? App.settings .getLocalizedString("common.reinstalled") : App.settings .getLocalizedString("common.installed")) + "<br/><br/>" + App.settings.getLocalizedString("instance.findit"); title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.installed"); if (isReinstall) { instance.setVersion(version.getVersion()); instance.setMinecraftVersion(this.getMinecraftVersion()); instance.setModsInstalled(this.getModsInstalled()); instance.setJarOrder(this.getJarOrder()); instance.setIsNewLaunchMethod(this.isNewLaunchMethod()); if (this.isNewLaunchMethod()) { instance.setLibrariesNeeded(this.getLibrariesNeeded()); instance.setMinecraftArguments(this.getMinecraftArguments()); instance.setMainClass(this.getMainClass()); } if (version.isDevVersion()) { instance.setDevVersion(); } else { instance.setNotDevVersion(); } if (!instance.isPlayable()) { instance.setPlayable(); } } else if (isServer) { } else { App.settings.getInstances().add( new Instance(instanceNameField.getText(), pack .getName(), pack, installForMe.isSelected(), version.getVersion(), this .getMinecraftVersion(), this .getPermGen(), this.getModsInstalled(), this.getJarOrder(), this.getLibrariesNeeded(), this.getMinecraftArguments(), this .getMainClass(), version.isDevVersion(), this .isNewLaunchMethod())); // Add It } App.settings.saveInstances(); App.settings.reloadInstancesPanel(); if (pack.isLoggingEnabled() && App.settings.enableLogs()) { App.settings.apiCall(App.settings.getAccount() .getMinecraftUsername(), "packinstalled", pack.getID() + "", version.getVersion()); } } else { if (isReinstall) { type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.reinstalled") + "<br/><br/>" + App.settings .getLocalizedString("instance.nolongerplayable") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.reinstalled"); App.settings.setInstanceUnplayable(instance); } else { // Install failed so delete the folder and clear Temp Dir Utils.delete(this.getRootDirectory()); type = JOptionPane.ERROR_MESSAGE; text = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.wasnt") + " " + App.settings.getLocalizedString("common.installed") + "<br/><br/>" + App.settings .getLocalizedString("instance.checkerrorlogs") + "!"; title = pack.getName() + " " + version.getVersion() + " " + App.settings.getLocalizedString("common.not") + " " + App.settings.getLocalizedString("common.installed"); } } } dialog.dispose(); Utils.cleanTempDirectory(); JOptionPane.showMessageDialog(App.settings.getParent(), "<html><center>" + text + "</center></html>", title, type); } }; instanceInstaller.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { if (progressBar.isIndeterminate()) { progressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } progressBar.setValue(progress); } else if ("subprogress" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(false); } int progress = (Integer) evt.getNewValue(); if (progress > 100) { progress = 100; } if (progress == 0) { subProgressBar.setVisible(false); } subProgressBar.setValue(progress); } else if ("subprogressint" == evt.getPropertyName()) { if (!subProgressBar.isVisible()) { subProgressBar.setVisible(true); } if (!subProgressBar.isIndeterminate()) { subProgressBar.setIndeterminate(true); } } else if ("doing" == evt.getPropertyName()) { String doingText = (String) evt.getNewValue(); doing.setText(doingText); } } }); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { instanceInstaller.cancel(true); } }); if (isReinstall) { instanceInstaller.setInstance(instance); } instanceInstaller.execute(); dispose(); dialog.setVisible(true); } }); cancel = new JButton(App.settings.getLocalizedString("common.cancel")); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); bottom.add(install); bottom.add(cancel); add(top, BorderLayout.NORTH); add(middle, BorderLayout.CENTER); add(bottom, BorderLayout.SOUTH); setVisible(true); }
diff --git a/plugins/net.lucky-dip.hamleditor/src/net/lucky_dip/hamleditor/editor/scanners/HamlCommentScanner.java b/plugins/net.lucky-dip.hamleditor/src/net/lucky_dip/hamleditor/editor/scanners/HamlCommentScanner.java index a5909fb..ef13808 100644 --- a/plugins/net.lucky-dip.hamleditor/src/net/lucky_dip/hamleditor/editor/scanners/HamlCommentScanner.java +++ b/plugins/net.lucky-dip.hamleditor/src/net/lucky_dip/hamleditor/editor/scanners/HamlCommentScanner.java @@ -1,28 +1,28 @@ package net.lucky_dip.hamleditor.editor.scanners; import net.lucky_dip.hamleditor.editor.IColorManager; import net.lucky_dip.hamleditor.editor.IHamlEditorColorConstants; import org.eclipse.jface.text.TextAttribute; import org.eclipse.jface.text.rules.IRule; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.MultiLineRule; import org.eclipse.jface.text.rules.RuleBasedScanner; import org.eclipse.jface.text.rules.SingleLineRule; import org.eclipse.jface.text.rules.Token; public class HamlCommentScanner extends RuleBasedScanner { public HamlCommentScanner(IColorManager manager) { IToken comment = new Token(new TextAttribute(manager.getColor(IHamlEditorColorConstants.HAML_COMMENT))); IRule[] rules = new IRule[3]; rules[0] = new SingleLineRule("/", null, comment, (char) 0, true); rules[1] = new MultiLineRule("<!--", "-->", comment, (char) 0, true); // FIXME Need to handle nested content and color that properly! - rules[1] = new SingleLineRule("-#", null, comment, (char) 0, true); + rules[2] = new SingleLineRule("-#", null, comment, (char) 0, true); setRules(rules); } }
true
true
public HamlCommentScanner(IColorManager manager) { IToken comment = new Token(new TextAttribute(manager.getColor(IHamlEditorColorConstants.HAML_COMMENT))); IRule[] rules = new IRule[3]; rules[0] = new SingleLineRule("/", null, comment, (char) 0, true); rules[1] = new MultiLineRule("<!--", "-->", comment, (char) 0, true); // FIXME Need to handle nested content and color that properly! rules[1] = new SingleLineRule("-#", null, comment, (char) 0, true); setRules(rules); }
public HamlCommentScanner(IColorManager manager) { IToken comment = new Token(new TextAttribute(manager.getColor(IHamlEditorColorConstants.HAML_COMMENT))); IRule[] rules = new IRule[3]; rules[0] = new SingleLineRule("/", null, comment, (char) 0, true); rules[1] = new MultiLineRule("<!--", "-->", comment, (char) 0, true); // FIXME Need to handle nested content and color that properly! rules[2] = new SingleLineRule("-#", null, comment, (char) 0, true); setRules(rules); }
diff --git a/src/org/bonsaimind/easyminelauncher/Main.java b/src/org/bonsaimind/easyminelauncher/Main.java index 253600c..f193f59 100644 --- a/src/org/bonsaimind/easyminelauncher/Main.java +++ b/src/org/bonsaimind/easyminelauncher/Main.java @@ -1,488 +1,488 @@ /* * Copyright 2012 Robert 'Bobby' Zenz. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY Robert 'Bobby' Zenz ''AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of Robert 'Bobby' Zenz. */ package org.bonsaimind.easyminelauncher; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Timer; import java.util.TimerTask; import javax.swing.JInternalFrame; import javax.swing.JOptionPane; public class Main { private static String name = "EasyMineLauncher"; private static String version = "0.14"; public static void main(String[] args) { String jarDir = ""; String jar = ""; String lwjglDir = ""; String password = ""; String nativeDir = ""; List<String> additionalJars = new ArrayList<String>(); boolean noFrame = false; String optionsFileFrom = ""; List<String> options = new ArrayList<String>(); boolean demo = false; String parentDir = ""; String port = null; String server = null; boolean authenticate = false; AuthenticationFailureBehavior authenticationFailureBehavior = AuthenticationFailureBehavior.ALERT_BREAK; int keepAliveTick = 300; String sessionId = "0"; String launcherVersion = "381"; String username = "Username"; boolean keepUsername = false; String texturepack = ""; String title = "Minecraft (" + name + ")"; boolean maximized = false; int width = 800; int height = 600; int x = -1; int y = -1; boolean alwaysOnTop = false; boolean fullscreen = false; // Parse arguments for (String arg : args) { if (arg.startsWith("--jar-dir=")) { jarDir = arg.substring(10); } else if (arg.startsWith("--jar=")) { jar = arg.substring(6); } else if (arg.startsWith("--lwjgl-dir=")) { lwjglDir = arg.substring(12); } else if (arg.startsWith("--mppass=")) { password = arg.substring(9); } else if (arg.startsWith("--password=")) { password = arg.substring(11); } else if (arg.startsWith("--native-dir=")) { nativeDir = arg.substring(13); } else if (arg.startsWith("--additional-jar=")) { String param = arg.substring(17); additionalJars.addAll(Arrays.asList(param.split(","))); } else if (arg.equals("--no-frame")) { noFrame = true; } else if (arg.startsWith("--parent-dir=")) { parentDir = arg.substring(13); } else if (arg.startsWith("--port=")) { port = arg.substring(7); } else if (arg.startsWith("--server=")) { server = arg.substring(9); } else if (arg.equals("--authenticate")) { authenticate = true; } else if (arg.startsWith("--authentication-failure=")) { - authenticationFailureBehavior = AuthenticationFailureBehavior.valueOf(arg.substring(23)); + authenticationFailureBehavior = AuthenticationFailureBehavior.valueOf(arg.substring(25)); } else if (arg.startsWith("--keep-alive-tick=")) { keepAliveTick = Integer.parseInt(arg.substring(18)); } else if (arg.startsWith("--session-id=")) { sessionId = arg.substring(13); } else if (arg.startsWith("--launcher-version=")) { launcherVersion = arg.substring(19); } else if (arg.startsWith("--options-file=")) { optionsFileFrom = arg.substring(15); } else if (arg.startsWith("--set-option=")) { options.add(arg.substring(13)); } else if (arg.startsWith("--texturepack=")) { texturepack = arg.substring(14); } else if (arg.startsWith("--title=")) { title = arg.substring(8); } else if (arg.startsWith("--username=")) { username = arg.substring(11); } else if (arg.equals("--keep-username")) { keepUsername = true; } else if (arg.equals("--demo")) { demo = true; } else if (arg.equals("--version")) { printVersion(); return; } else if (arg.startsWith("--width=")) { width = Integer.parseInt(arg.substring(8)); } else if (arg.startsWith("--height=")) { height = Integer.parseInt(arg.substring(9)); } else if (arg.startsWith("--x=")) { x = Integer.parseInt(arg.substring(4)); } else if (arg.startsWith("--y=")) { y = Integer.parseInt(arg.substring(4)); } else if (arg.equals("--maximized")) { maximized = true; } else if (arg.equals("--always-on-top")) { alwaysOnTop = true; } else if (arg.equals("--fullscreen")) { fullscreen = true; } else if (arg.equals("--help")) { printHelp(); return; } else { System.err.println("Unknown parameter: " + arg); printHelp(); return; } } // Check the arguments if (jarDir.isEmpty() && jar.isEmpty()) { jarDir = new File(new File(System.getProperty("user.home"), ".minecraft").toString(), "bin").toString(); } if (jarDir.isEmpty()) { jarDir = new File(jar).getParent(); } else { jarDir = new File(jarDir).getAbsolutePath(); jar = jarDir; } if (lwjglDir.isEmpty()) { lwjglDir = jarDir; } if (nativeDir.isEmpty()) { nativeDir = new File(jarDir, "natives").getAbsolutePath(); } if (!parentDir.isEmpty()) { System.setProperty("user.home", parentDir); // This is needed for the Forge ModLoader and maybe others. System.setProperty("minecraft.applet.TargetDirectory", parentDir); } else { parentDir = System.getProperty("user.home"); } parentDir = new File(parentDir, ".minecraft").toString(); // Now try if we manage to login... if (authenticate) { try { AuthenticationResult result = authenticate(username, password, launcherVersion); sessionId = result.getSessionId(); // Only launch the keep alive ticker if the login was successfull. if (keepAliveTick > 0) { Timer timer = new Timer("Authentication Keep Alive", true); final String finalUsername = username; final String finalSessionId = sessionId; timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("Authentication Keep Alive."); try { keepAlive(finalUsername, finalSessionId); } catch (AuthenticationException ex) { System.err.println("Authentication-Keep-Alive failed!"); System.err.println(ex); } } }, keepAliveTick * 1000, keepAliveTick * 1000); } if (!keepUsername) { username = result.getUsername(); } } catch (AuthenticationException ex) { System.err.println(ex); if (ex.getCause() != null) { System.err.println(ex.getCause()); } // Alert the user if (authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_BREAK || authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_CONTINUE) { JOptionPane.showMessageDialog(new JInternalFrame(), ex.getMessage(), "Failed to authenticate...", JOptionPane.ERROR_MESSAGE); } // STOP! if (authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_BREAK || authenticationFailureBehavior == AuthenticationFailureBehavior.SILENT_BREAK) { return; } } } // Let's work with the options.txt, shall we? OptionsFile optionsFile = new OptionsFile(parentDir); if (!optionsFileFrom.isEmpty()) { optionsFile.setPath(optionsFileFrom); } if (optionsFile.exists() && optionsFile.read()) { // Reset the path in case we used an external options.txt. optionsFile.setPath(parentDir); } else { System.out.println("Failed to read options.txt from \"" + optionsFile.getPath() + "\" or it does not exist!"); } // Set the texturepack. if (!texturepack.isEmpty() && optionsFile.isRead()) { optionsFile.setTexturePack(texturepack); } // Set the options. if (!options.isEmpty() && optionsFile.isRead()) { for (String option : options) { int splitIdx = option.indexOf(":"); if (splitIdx > 0) { // we don't want not-named options either. optionsFile.setOption(option.substring(0, splitIdx), option.substring(splitIdx + 1)); } } } // Now write back. if (optionsFile.isRead()) { if (!optionsFile.write()) { System.out.println("Failed to write options.txt!"); } } // Some checks. if (height <= 0) { height = 600; } if (width <= 0) { width = 800; } // Load the launcher if (!additionalJars.isEmpty()) { try { // This might fix issues for Mods which assume that they // are loaded via the real launcher...not sure, thought adding // it would be a good idea. List<URL> urls = new ArrayList<URL>(); for (String item : additionalJars) { urls.add(new File(item).toURI().toURL()); } if (!extendClassLoaders(urls.toArray(new URL[urls.size() - 1]))) { System.err.println("Failed to inject additional jars!"); return; } } catch (MalformedURLException ex) { System.err.println("Failed to load additional jars!"); System.err.println(ex); return; } } // Let's tell the Forge ModLoader (and others) that it is supposed // to load our applet and not that of the official launcher. System.setProperty("minecraft.applet.WrapperClass", "org.bonsaimind.easyminelauncher.ContainerApplet"); // Create the applet. ContainerApplet container = new ContainerApplet(); // Pass arguments to the applet. container.setDemo(demo); container.setUsername(username); if (server != null) { container.setServer(server, port != null ? port : "25565"); } container.setMpPass(password); container.setSessionId(sessionId); // Create and set up the frame. ContainerFrame frame = new ContainerFrame(title); if (fullscreen) { Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize(); frame.setAlwaysOnTop(true); frame.setUndecorated(true); frame.setSize(dimensions.width, dimensions.height); frame.setLocation(0, 0); } else { frame.setAlwaysOnTop(alwaysOnTop); frame.setUndecorated(noFrame); frame.setSize(width, height); // It is more likely that no location is set...I think. frame.setLocation( x == -1 ? frame.getX() : x, y == -1 ? frame.getY() : y); if (maximized) { frame.setExtendedState(Frame.MAXIMIZED_BOTH); } } frame.setContainerApplet(container); frame.setVisible(true); // Load container.loadNatives(nativeDir); if (container.loadJarsAndApplet(jar, lwjglDir)) { container.init(); container.start(); } else { System.err.println("Failed to load Minecraft! Exiting."); // Exit just to be sure. System.exit(0); } } private static AuthenticationResult authenticate(String username, String password, String launcherVersion) throws AuthenticationException { try { username = URLEncoder.encode(username, "UTF-8"); password = URLEncoder.encode(password, "UTF-8"); launcherVersion = URLEncoder.encode(launcherVersion, "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new AuthenticationException("Failed to encode username, password or launcher version!", ex); } String request = String.format("user=%s&password=%s&version=%s", username, password, launcherVersion); String response = httpRequest("https://login.minecraft.net", request); String[] splitted = response.split(":"); if (splitted.length < 5) { throw new AuthenticationException(response); } return new AuthenticationResult(splitted); } /** * This is mostly from here: http://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java * @param url * @return */ private static boolean extendClassLoaders(URL[] urls) { // Extend the ClassLoader of the current thread. URLClassLoader loader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader()); Thread.currentThread().setContextClassLoader(loader); // Extend the SystemClassLoader...this is needed for mods which will // use the WhatEver.getClass().getClassLoader() method to retrieve // a ClassLoader. URLClassLoader systemLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); try { Method addURLMethod = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class}); addURLMethod.setAccessible(true); for (URL url : urls) { addURLMethod.invoke(systemLoader, url); } return true; } catch (NoSuchMethodException ex) { System.err.println(ex); } catch (SecurityException ex) { System.err.println(ex); } catch (IllegalAccessException ex) { System.err.println(ex); } catch (InvocationTargetException ex) { System.err.println(ex); } return false; } private static String httpRequest(String url, String content) throws AuthenticationException { byte[] contentBytes = null; try { contentBytes = content.getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { throw new AuthenticationException("Failed to convert content!", ex); } URLConnection connection = null; try { connection = new URL(url).openConnection(); } catch (MalformedURLException ex) { throw new AuthenticationException("It wasn't me!", ex); } catch (IOException ex) { throw new AuthenticationException("Failed to connect to authentication server!", ex); } connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(contentBytes.length)); try { OutputStream requestStream = connection.getOutputStream(); requestStream.write(contentBytes, 0, contentBytes.length); requestStream.close(); } catch (IOException ex) { throw new AuthenticationException("Failed to read response!", ex); } String response = ""; try { BufferedReader responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); response = responseStream.readLine(); responseStream.close(); } catch (IOException ex) { throw new AuthenticationException("Failed to read response!", ex); } return response; } private static void keepAlive(String username, String sessionId) throws AuthenticationException { httpRequest("https://login.minecraft.net", String.format("?name={0}&session={1}", username, sessionId)); } private static void printVersion() { System.out.println(name + " " + version); System.out.println("Copyright 2012 Robert 'Bobby' Zenz. All rights reserved."); System.out.println("Licensed under 2-clause-BSD."); } private static void printHelp() { System.out.println("Usage: " + name + ".jar [OPTIONS]"); System.out.println("Launch Minecraft directly."); System.out.println(""); InputStream stream = Main.class.getResourceAsStream("/org/bonsaimind/easyminelauncher/help.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; try { while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (IOException ex) { System.err.println(ex); } } }
true
true
public static void main(String[] args) { String jarDir = ""; String jar = ""; String lwjglDir = ""; String password = ""; String nativeDir = ""; List<String> additionalJars = new ArrayList<String>(); boolean noFrame = false; String optionsFileFrom = ""; List<String> options = new ArrayList<String>(); boolean demo = false; String parentDir = ""; String port = null; String server = null; boolean authenticate = false; AuthenticationFailureBehavior authenticationFailureBehavior = AuthenticationFailureBehavior.ALERT_BREAK; int keepAliveTick = 300; String sessionId = "0"; String launcherVersion = "381"; String username = "Username"; boolean keepUsername = false; String texturepack = ""; String title = "Minecraft (" + name + ")"; boolean maximized = false; int width = 800; int height = 600; int x = -1; int y = -1; boolean alwaysOnTop = false; boolean fullscreen = false; // Parse arguments for (String arg : args) { if (arg.startsWith("--jar-dir=")) { jarDir = arg.substring(10); } else if (arg.startsWith("--jar=")) { jar = arg.substring(6); } else if (arg.startsWith("--lwjgl-dir=")) { lwjglDir = arg.substring(12); } else if (arg.startsWith("--mppass=")) { password = arg.substring(9); } else if (arg.startsWith("--password=")) { password = arg.substring(11); } else if (arg.startsWith("--native-dir=")) { nativeDir = arg.substring(13); } else if (arg.startsWith("--additional-jar=")) { String param = arg.substring(17); additionalJars.addAll(Arrays.asList(param.split(","))); } else if (arg.equals("--no-frame")) { noFrame = true; } else if (arg.startsWith("--parent-dir=")) { parentDir = arg.substring(13); } else if (arg.startsWith("--port=")) { port = arg.substring(7); } else if (arg.startsWith("--server=")) { server = arg.substring(9); } else if (arg.equals("--authenticate")) { authenticate = true; } else if (arg.startsWith("--authentication-failure=")) { authenticationFailureBehavior = AuthenticationFailureBehavior.valueOf(arg.substring(23)); } else if (arg.startsWith("--keep-alive-tick=")) { keepAliveTick = Integer.parseInt(arg.substring(18)); } else if (arg.startsWith("--session-id=")) { sessionId = arg.substring(13); } else if (arg.startsWith("--launcher-version=")) { launcherVersion = arg.substring(19); } else if (arg.startsWith("--options-file=")) { optionsFileFrom = arg.substring(15); } else if (arg.startsWith("--set-option=")) { options.add(arg.substring(13)); } else if (arg.startsWith("--texturepack=")) { texturepack = arg.substring(14); } else if (arg.startsWith("--title=")) { title = arg.substring(8); } else if (arg.startsWith("--username=")) { username = arg.substring(11); } else if (arg.equals("--keep-username")) { keepUsername = true; } else if (arg.equals("--demo")) { demo = true; } else if (arg.equals("--version")) { printVersion(); return; } else if (arg.startsWith("--width=")) { width = Integer.parseInt(arg.substring(8)); } else if (arg.startsWith("--height=")) { height = Integer.parseInt(arg.substring(9)); } else if (arg.startsWith("--x=")) { x = Integer.parseInt(arg.substring(4)); } else if (arg.startsWith("--y=")) { y = Integer.parseInt(arg.substring(4)); } else if (arg.equals("--maximized")) { maximized = true; } else if (arg.equals("--always-on-top")) { alwaysOnTop = true; } else if (arg.equals("--fullscreen")) { fullscreen = true; } else if (arg.equals("--help")) { printHelp(); return; } else { System.err.println("Unknown parameter: " + arg); printHelp(); return; } } // Check the arguments if (jarDir.isEmpty() && jar.isEmpty()) { jarDir = new File(new File(System.getProperty("user.home"), ".minecraft").toString(), "bin").toString(); } if (jarDir.isEmpty()) { jarDir = new File(jar).getParent(); } else { jarDir = new File(jarDir).getAbsolutePath(); jar = jarDir; } if (lwjglDir.isEmpty()) { lwjglDir = jarDir; } if (nativeDir.isEmpty()) { nativeDir = new File(jarDir, "natives").getAbsolutePath(); } if (!parentDir.isEmpty()) { System.setProperty("user.home", parentDir); // This is needed for the Forge ModLoader and maybe others. System.setProperty("minecraft.applet.TargetDirectory", parentDir); } else { parentDir = System.getProperty("user.home"); } parentDir = new File(parentDir, ".minecraft").toString(); // Now try if we manage to login... if (authenticate) { try { AuthenticationResult result = authenticate(username, password, launcherVersion); sessionId = result.getSessionId(); // Only launch the keep alive ticker if the login was successfull. if (keepAliveTick > 0) { Timer timer = new Timer("Authentication Keep Alive", true); final String finalUsername = username; final String finalSessionId = sessionId; timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("Authentication Keep Alive."); try { keepAlive(finalUsername, finalSessionId); } catch (AuthenticationException ex) { System.err.println("Authentication-Keep-Alive failed!"); System.err.println(ex); } } }, keepAliveTick * 1000, keepAliveTick * 1000); } if (!keepUsername) { username = result.getUsername(); } } catch (AuthenticationException ex) { System.err.println(ex); if (ex.getCause() != null) { System.err.println(ex.getCause()); } // Alert the user if (authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_BREAK || authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_CONTINUE) { JOptionPane.showMessageDialog(new JInternalFrame(), ex.getMessage(), "Failed to authenticate...", JOptionPane.ERROR_MESSAGE); } // STOP! if (authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_BREAK || authenticationFailureBehavior == AuthenticationFailureBehavior.SILENT_BREAK) { return; } } } // Let's work with the options.txt, shall we? OptionsFile optionsFile = new OptionsFile(parentDir); if (!optionsFileFrom.isEmpty()) { optionsFile.setPath(optionsFileFrom); } if (optionsFile.exists() && optionsFile.read()) { // Reset the path in case we used an external options.txt. optionsFile.setPath(parentDir); } else { System.out.println("Failed to read options.txt from \"" + optionsFile.getPath() + "\" or it does not exist!"); } // Set the texturepack. if (!texturepack.isEmpty() && optionsFile.isRead()) { optionsFile.setTexturePack(texturepack); } // Set the options. if (!options.isEmpty() && optionsFile.isRead()) { for (String option : options) { int splitIdx = option.indexOf(":"); if (splitIdx > 0) { // we don't want not-named options either. optionsFile.setOption(option.substring(0, splitIdx), option.substring(splitIdx + 1)); } } } // Now write back. if (optionsFile.isRead()) { if (!optionsFile.write()) { System.out.println("Failed to write options.txt!"); } } // Some checks. if (height <= 0) { height = 600; } if (width <= 0) { width = 800; } // Load the launcher if (!additionalJars.isEmpty()) { try { // This might fix issues for Mods which assume that they // are loaded via the real launcher...not sure, thought adding // it would be a good idea. List<URL> urls = new ArrayList<URL>(); for (String item : additionalJars) { urls.add(new File(item).toURI().toURL()); } if (!extendClassLoaders(urls.toArray(new URL[urls.size() - 1]))) { System.err.println("Failed to inject additional jars!"); return; } } catch (MalformedURLException ex) { System.err.println("Failed to load additional jars!"); System.err.println(ex); return; } } // Let's tell the Forge ModLoader (and others) that it is supposed // to load our applet and not that of the official launcher. System.setProperty("minecraft.applet.WrapperClass", "org.bonsaimind.easyminelauncher.ContainerApplet"); // Create the applet. ContainerApplet container = new ContainerApplet(); // Pass arguments to the applet. container.setDemo(demo); container.setUsername(username); if (server != null) { container.setServer(server, port != null ? port : "25565"); } container.setMpPass(password); container.setSessionId(sessionId); // Create and set up the frame. ContainerFrame frame = new ContainerFrame(title); if (fullscreen) { Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize(); frame.setAlwaysOnTop(true); frame.setUndecorated(true); frame.setSize(dimensions.width, dimensions.height); frame.setLocation(0, 0); } else { frame.setAlwaysOnTop(alwaysOnTop); frame.setUndecorated(noFrame); frame.setSize(width, height); // It is more likely that no location is set...I think. frame.setLocation( x == -1 ? frame.getX() : x, y == -1 ? frame.getY() : y); if (maximized) { frame.setExtendedState(Frame.MAXIMIZED_BOTH); } } frame.setContainerApplet(container); frame.setVisible(true); // Load container.loadNatives(nativeDir); if (container.loadJarsAndApplet(jar, lwjglDir)) { container.init(); container.start(); } else { System.err.println("Failed to load Minecraft! Exiting."); // Exit just to be sure. System.exit(0); } }
public static void main(String[] args) { String jarDir = ""; String jar = ""; String lwjglDir = ""; String password = ""; String nativeDir = ""; List<String> additionalJars = new ArrayList<String>(); boolean noFrame = false; String optionsFileFrom = ""; List<String> options = new ArrayList<String>(); boolean demo = false; String parentDir = ""; String port = null; String server = null; boolean authenticate = false; AuthenticationFailureBehavior authenticationFailureBehavior = AuthenticationFailureBehavior.ALERT_BREAK; int keepAliveTick = 300; String sessionId = "0"; String launcherVersion = "381"; String username = "Username"; boolean keepUsername = false; String texturepack = ""; String title = "Minecraft (" + name + ")"; boolean maximized = false; int width = 800; int height = 600; int x = -1; int y = -1; boolean alwaysOnTop = false; boolean fullscreen = false; // Parse arguments for (String arg : args) { if (arg.startsWith("--jar-dir=")) { jarDir = arg.substring(10); } else if (arg.startsWith("--jar=")) { jar = arg.substring(6); } else if (arg.startsWith("--lwjgl-dir=")) { lwjglDir = arg.substring(12); } else if (arg.startsWith("--mppass=")) { password = arg.substring(9); } else if (arg.startsWith("--password=")) { password = arg.substring(11); } else if (arg.startsWith("--native-dir=")) { nativeDir = arg.substring(13); } else if (arg.startsWith("--additional-jar=")) { String param = arg.substring(17); additionalJars.addAll(Arrays.asList(param.split(","))); } else if (arg.equals("--no-frame")) { noFrame = true; } else if (arg.startsWith("--parent-dir=")) { parentDir = arg.substring(13); } else if (arg.startsWith("--port=")) { port = arg.substring(7); } else if (arg.startsWith("--server=")) { server = arg.substring(9); } else if (arg.equals("--authenticate")) { authenticate = true; } else if (arg.startsWith("--authentication-failure=")) { authenticationFailureBehavior = AuthenticationFailureBehavior.valueOf(arg.substring(25)); } else if (arg.startsWith("--keep-alive-tick=")) { keepAliveTick = Integer.parseInt(arg.substring(18)); } else if (arg.startsWith("--session-id=")) { sessionId = arg.substring(13); } else if (arg.startsWith("--launcher-version=")) { launcherVersion = arg.substring(19); } else if (arg.startsWith("--options-file=")) { optionsFileFrom = arg.substring(15); } else if (arg.startsWith("--set-option=")) { options.add(arg.substring(13)); } else if (arg.startsWith("--texturepack=")) { texturepack = arg.substring(14); } else if (arg.startsWith("--title=")) { title = arg.substring(8); } else if (arg.startsWith("--username=")) { username = arg.substring(11); } else if (arg.equals("--keep-username")) { keepUsername = true; } else if (arg.equals("--demo")) { demo = true; } else if (arg.equals("--version")) { printVersion(); return; } else if (arg.startsWith("--width=")) { width = Integer.parseInt(arg.substring(8)); } else if (arg.startsWith("--height=")) { height = Integer.parseInt(arg.substring(9)); } else if (arg.startsWith("--x=")) { x = Integer.parseInt(arg.substring(4)); } else if (arg.startsWith("--y=")) { y = Integer.parseInt(arg.substring(4)); } else if (arg.equals("--maximized")) { maximized = true; } else if (arg.equals("--always-on-top")) { alwaysOnTop = true; } else if (arg.equals("--fullscreen")) { fullscreen = true; } else if (arg.equals("--help")) { printHelp(); return; } else { System.err.println("Unknown parameter: " + arg); printHelp(); return; } } // Check the arguments if (jarDir.isEmpty() && jar.isEmpty()) { jarDir = new File(new File(System.getProperty("user.home"), ".minecraft").toString(), "bin").toString(); } if (jarDir.isEmpty()) { jarDir = new File(jar).getParent(); } else { jarDir = new File(jarDir).getAbsolutePath(); jar = jarDir; } if (lwjglDir.isEmpty()) { lwjglDir = jarDir; } if (nativeDir.isEmpty()) { nativeDir = new File(jarDir, "natives").getAbsolutePath(); } if (!parentDir.isEmpty()) { System.setProperty("user.home", parentDir); // This is needed for the Forge ModLoader and maybe others. System.setProperty("minecraft.applet.TargetDirectory", parentDir); } else { parentDir = System.getProperty("user.home"); } parentDir = new File(parentDir, ".minecraft").toString(); // Now try if we manage to login... if (authenticate) { try { AuthenticationResult result = authenticate(username, password, launcherVersion); sessionId = result.getSessionId(); // Only launch the keep alive ticker if the login was successfull. if (keepAliveTick > 0) { Timer timer = new Timer("Authentication Keep Alive", true); final String finalUsername = username; final String finalSessionId = sessionId; timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("Authentication Keep Alive."); try { keepAlive(finalUsername, finalSessionId); } catch (AuthenticationException ex) { System.err.println("Authentication-Keep-Alive failed!"); System.err.println(ex); } } }, keepAliveTick * 1000, keepAliveTick * 1000); } if (!keepUsername) { username = result.getUsername(); } } catch (AuthenticationException ex) { System.err.println(ex); if (ex.getCause() != null) { System.err.println(ex.getCause()); } // Alert the user if (authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_BREAK || authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_CONTINUE) { JOptionPane.showMessageDialog(new JInternalFrame(), ex.getMessage(), "Failed to authenticate...", JOptionPane.ERROR_MESSAGE); } // STOP! if (authenticationFailureBehavior == AuthenticationFailureBehavior.ALERT_BREAK || authenticationFailureBehavior == AuthenticationFailureBehavior.SILENT_BREAK) { return; } } } // Let's work with the options.txt, shall we? OptionsFile optionsFile = new OptionsFile(parentDir); if (!optionsFileFrom.isEmpty()) { optionsFile.setPath(optionsFileFrom); } if (optionsFile.exists() && optionsFile.read()) { // Reset the path in case we used an external options.txt. optionsFile.setPath(parentDir); } else { System.out.println("Failed to read options.txt from \"" + optionsFile.getPath() + "\" or it does not exist!"); } // Set the texturepack. if (!texturepack.isEmpty() && optionsFile.isRead()) { optionsFile.setTexturePack(texturepack); } // Set the options. if (!options.isEmpty() && optionsFile.isRead()) { for (String option : options) { int splitIdx = option.indexOf(":"); if (splitIdx > 0) { // we don't want not-named options either. optionsFile.setOption(option.substring(0, splitIdx), option.substring(splitIdx + 1)); } } } // Now write back. if (optionsFile.isRead()) { if (!optionsFile.write()) { System.out.println("Failed to write options.txt!"); } } // Some checks. if (height <= 0) { height = 600; } if (width <= 0) { width = 800; } // Load the launcher if (!additionalJars.isEmpty()) { try { // This might fix issues for Mods which assume that they // are loaded via the real launcher...not sure, thought adding // it would be a good idea. List<URL> urls = new ArrayList<URL>(); for (String item : additionalJars) { urls.add(new File(item).toURI().toURL()); } if (!extendClassLoaders(urls.toArray(new URL[urls.size() - 1]))) { System.err.println("Failed to inject additional jars!"); return; } } catch (MalformedURLException ex) { System.err.println("Failed to load additional jars!"); System.err.println(ex); return; } } // Let's tell the Forge ModLoader (and others) that it is supposed // to load our applet and not that of the official launcher. System.setProperty("minecraft.applet.WrapperClass", "org.bonsaimind.easyminelauncher.ContainerApplet"); // Create the applet. ContainerApplet container = new ContainerApplet(); // Pass arguments to the applet. container.setDemo(demo); container.setUsername(username); if (server != null) { container.setServer(server, port != null ? port : "25565"); } container.setMpPass(password); container.setSessionId(sessionId); // Create and set up the frame. ContainerFrame frame = new ContainerFrame(title); if (fullscreen) { Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize(); frame.setAlwaysOnTop(true); frame.setUndecorated(true); frame.setSize(dimensions.width, dimensions.height); frame.setLocation(0, 0); } else { frame.setAlwaysOnTop(alwaysOnTop); frame.setUndecorated(noFrame); frame.setSize(width, height); // It is more likely that no location is set...I think. frame.setLocation( x == -1 ? frame.getX() : x, y == -1 ? frame.getY() : y); if (maximized) { frame.setExtendedState(Frame.MAXIMIZED_BOTH); } } frame.setContainerApplet(container); frame.setVisible(true); // Load container.loadNatives(nativeDir); if (container.loadJarsAndApplet(jar, lwjglDir)) { container.init(); container.start(); } else { System.err.println("Failed to load Minecraft! Exiting."); // Exit just to be sure. System.exit(0); } }
diff --git a/algorithms/src/org/macademia/algs/Kmeans.java b/algorithms/src/org/macademia/algs/Kmeans.java index 3a8d78f..e4a8746 100644 --- a/algorithms/src/org/macademia/algs/Kmeans.java +++ b/algorithms/src/org/macademia/algs/Kmeans.java @@ -1,168 +1,168 @@ package org.macademia.algs; import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: research * Date: 6/11/13 * Time: 4:55 PM * To change this template use File | Settings | File Templates. */ public class Kmeans { private Cluster[] clusters; private float[][] data; private Point[] centroids; public Kmeans(float[][] data) { this.data = data; } public float[][] getData() { return data; } public void setData(float[][] data) { this.data = data; } private class Cluster { private int id; private Point[] points; private Cluster() { } private Cluster(int id, Point[] points) { this.id = id; this.points = points; } private int getId() { return id; } private void setId(int id) { this.id = id; } private Point[] getPoints() { return points; } private void setPoints(Point[] points) { this.points = points; } } private class Point { private float [] data; private int id; private int cluster; private Point() { return; } private Point(int cluster, float[] data, int id) { this.cluster = cluster; this.data = data; this.id = id; } private float[] getData() { return data; } private void setData(float[] data) { this.data = data; } private int getId() { return id; } private void setId(int id) { this.id = id; } private int getCluster() { return cluster; } private void setCluster(int cluster) { this.cluster = cluster; } } /** * * @param p1 the Point object for the first point * @param p2 the Point object for the second point * @return the distance between the two points */ public double getDistance(Point p1, Point p2) { float [] coordinates1 = p1.data; float [] coordinates2 = p2.data; double sum = 0; - for (int i=0; i < point.length; i++) { + for (int i=0; i < coordinates1.length; i++) { sum += Math.pow(Math.abs(coordinates1[i]-coordinates2[i]), 2); } return Math.sqrt(sum); } /** * Return the clusters computed using Lloyd's algorithm * @param data a matrix of floats * @param k the desired number of clusters * @return an array of k cluster ids */ public int[] getClusters(float[][] data, int k){ } /** * returns k points, where the value of each dimension of the points is * bounded by the minimum and maximum of that dimension over all points * @param data * @param k * @return an array of k points */ public Point[] getKRandomPoints(float[][] data, int k){ } /** * * returns the id of the center that is closest to the given point * @param point * @param centroids * @return the id of the cluster */ public int getBestClusterForPoint(Point point, Point[] centroids){ } /** * Computes the intra-cluster variance over all clusters * @param clusters * @param centroids * @return */ public double getVariance(Cluster[] clusters, Point[] centroids){ } /** * Computes the centroids of each cluster * @param clusters */ public void computeCentroids(Cluster[] clusters){ } }
true
true
public double getDistance(Point p1, Point p2) { float [] coordinates1 = p1.data; float [] coordinates2 = p2.data; double sum = 0; for (int i=0; i < point.length; i++) { sum += Math.pow(Math.abs(coordinates1[i]-coordinates2[i]), 2); } return Math.sqrt(sum); }
public double getDistance(Point p1, Point p2) { float [] coordinates1 = p1.data; float [] coordinates2 = p2.data; double sum = 0; for (int i=0; i < coordinates1.length; i++) { sum += Math.pow(Math.abs(coordinates1[i]-coordinates2[i]), 2); } return Math.sqrt(sum); }
diff --git a/src/rules/Promote.java b/src/rules/Promote.java index 21d571e..5bbf8c9 100644 --- a/src/rules/Promote.java +++ b/src/rules/Promote.java @@ -1,220 +1,220 @@ package rules; import java.io.Serializable; import java.lang.reflect.Method; import java.util.HashMap; import javax.swing.JOptionPane; import logic.Game; import logic.Piece; import logic.PieceBuilder; /** * Promote.java * * Class to hold methods controlling promotion of different Piece types * * @author Drew Hannay & Alisa Maas * * CSCI 335, Wheaton College, Spring 2011 * Phase 2 * April 7, 2011 */ public class Promote implements Serializable { /** * Generated Serial Version ID */ private static final long serialVersionUID = -2346237261367453073L; /** * The current Game object. */ private Game g; /** * The name of the method to call. */ private String name; /** * The method to call. */ private transient Method doMethod; /** * The method to undo. */ private transient Method undoMethod; /** * A hashmap for convenience. */ private static HashMap<String, Method> doMethods = new HashMap<String, Method>(); /** * A hashmap for convenience. */ private static HashMap<String, Method> undoMethods = new HashMap<String, Method>(); /** * What the piece was promoted from */ private static String lastPromoted; /** * What it was promoted to. */ private static String klazz; static { try { doMethods.put("classic", Promote.class.getMethod("classicPromotion", Piece.class, boolean.class, String.class)); undoMethods.put("classic", Promote.class.getMethod("classicUndo", Piece.class)); doMethods.put("noPromos", Promote.class.getMethod("noPromo", Piece.class, boolean.class, String.class)); undoMethods.put("noPromos", Promote.class.getMethod("noPromoUndo", Piece.class)); } catch (Exception e) { e.printStackTrace(); } } /** * @param name The name of the method to use. */ public Promote(String name) { doMethod = doMethods.get(name); undoMethod = undoMethods.get(name); this.name = name; } /** * In this case, only pawns can promote, * allow the user to pick which class it promotes to. * @param p The piece to promote * @param verified Whether it has been verified that this * is ok * @param promo What the piece was promoted to. * @return The promoted Piece. */ public Piece classicPromotion(Piece p, boolean verified, String promo) { lastPromoted = p.getName(); - if (!verified && promo == null) { + if (!verified && promo == null&&g.isBlackMove()==p.isBlack()) { klazz = ""; if(p.getPromotesTo().size()==1) klazz = p.getPromotesTo().get(0); while (klazz.equals("")) { String result = (String) JOptionPane.showInputDialog(null, "Select the Promotion type:", "Promo choice", JOptionPane.PLAIN_MESSAGE, null, p.getPromotesTo().toArray(), null); if (result == null) { continue; } try { klazz = result; } catch (Exception e) { e.printStackTrace(); } } } else if (promo != null) { klazz = promo; } try { Piece promoted = PieceBuilder.makePiece(klazz,p.isBlack(), p.getSquare(), p.getBoard()); if (promoted.isBlack()) { g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted); } else { g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted); } promoted.getLegalDests().clear(); promoted.setMoveCount(p.getMoveCount()); return promoted; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Revert the piece back to what it was. * @param p The piece to unpromote * @return The unpromoted piece. */ public Piece classicUndo(Piece p) { try { Piece promoted = PieceBuilder.makePiece(lastPromoted,p.isBlack(), p.getSquare(), p.getBoard()); if (promoted.isBlack()) { g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted); } else { g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted); } promoted.getLegalDests().clear(); promoted.setMoveCount(p.getMoveCount()); return promoted; } catch (Exception e) { e.printStackTrace(); } return null; } /** * @param p The piece to promote * @param verified Whether the piece can be promoted * @param promo What to promote from. * @return The promoted Piece. */ public Piece execute(Piece p, boolean verified, String promo) { try { if (doMethod == null) { doMethod = doMethods.get(name); } return (Piece) doMethod.invoke(this, p, verified, promo); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Don't allow promotion. * @param p The piece to "promote" * @param b Unused * @param c Unused * @return the original piece. */ public Piece noPromo(Piece p, boolean b, String c) { return p; } /** * Return the original piece * @param p The piece to "unpromote" * @return The original piece. */ public Piece noPromoUndo(Piece p) { return p; } /** * @param g Setter for g. */ public void setGame(Game g) { this.g = g; } /** * @param p The piece to unpromote * @return The unpromoted piece. */ public Piece undo(Piece p) { try { if (undoMethod == null) { undoMethod = undoMethods.get(name); } return (Piece) undoMethod.invoke(this, p); } catch (Exception e) { e.printStackTrace(); return null; } } }
true
true
public Piece classicPromotion(Piece p, boolean verified, String promo) { lastPromoted = p.getName(); if (!verified && promo == null) { klazz = ""; if(p.getPromotesTo().size()==1) klazz = p.getPromotesTo().get(0); while (klazz.equals("")) { String result = (String) JOptionPane.showInputDialog(null, "Select the Promotion type:", "Promo choice", JOptionPane.PLAIN_MESSAGE, null, p.getPromotesTo().toArray(), null); if (result == null) { continue; } try { klazz = result; } catch (Exception e) { e.printStackTrace(); } } } else if (promo != null) { klazz = promo; } try { Piece promoted = PieceBuilder.makePiece(klazz,p.isBlack(), p.getSquare(), p.getBoard()); if (promoted.isBlack()) { g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted); } else { g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted); } promoted.getLegalDests().clear(); promoted.setMoveCount(p.getMoveCount()); return promoted; } catch (Exception e) { e.printStackTrace(); } return null; }
public Piece classicPromotion(Piece p, boolean verified, String promo) { lastPromoted = p.getName(); if (!verified && promo == null&&g.isBlackMove()==p.isBlack()) { klazz = ""; if(p.getPromotesTo().size()==1) klazz = p.getPromotesTo().get(0); while (klazz.equals("")) { String result = (String) JOptionPane.showInputDialog(null, "Select the Promotion type:", "Promo choice", JOptionPane.PLAIN_MESSAGE, null, p.getPromotesTo().toArray(), null); if (result == null) { continue; } try { klazz = result; } catch (Exception e) { e.printStackTrace(); } } } else if (promo != null) { klazz = promo; } try { Piece promoted = PieceBuilder.makePiece(klazz,p.isBlack(), p.getSquare(), p.getBoard()); if (promoted.isBlack()) { g.getBlackTeam().set(g.getBlackTeam().indexOf(p), promoted); } else { g.getWhiteTeam().set(g.getWhiteTeam().indexOf(p), promoted); } promoted.getLegalDests().clear(); promoted.setMoveCount(p.getMoveCount()); return promoted; } catch (Exception e) { e.printStackTrace(); } return null; }
diff --git a/servlet/src/main/java/hello/DbPoolServlet.java b/servlet/src/main/java/hello/DbPoolServlet.java index 79ed1b32c..d78f94622 100644 --- a/servlet/src/main/java/hello/DbPoolServlet.java +++ b/servlet/src/main/java/hello/DbPoolServlet.java @@ -1,98 +1,105 @@ package hello; import java.io.*; import java.sql.*; import java.util.*; import java.util.concurrent.*; import javax.annotation.*; import javax.servlet.*; import javax.servlet.http.*; import javax.sql.*; /** * Database connectivity (with a Servlet-container managed pool) test. */ @SuppressWarnings("serial") public class DbPoolServlet extends HttpServlet { // Database details. private static final String DB_QUERY = "SELECT * FROM World WHERE id = ?"; private static final int DB_ROWS = 10000; // Database connection pool. @Resource(name="jdbc/hello_world") private DataSource mysqlDataSource; @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Set content type to JSON res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON); // Reference the data source. final DataSource source = mysqlDataSource; // Get the count of queries to run. int count = 1; try { count = Integer.parseInt(req.getParameter("queries")); // Bounds check. if (count > 500) { count = 500; } if (count < 1) { count = 1; } } catch (NumberFormatException nfexc) { // Do nothing. } // Fetch some rows from the database. final World[] worlds = new World[count]; final Random random = ThreadLocalRandom.current(); try (Connection conn = source.getConnection()) { try (PreparedStatement statement = conn.prepareStatement(DB_QUERY, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { // Run the query the number of times requested. for (int i = 0; i < count; i++) { final int id = random.nextInt(DB_ROWS) + 1; statement.setInt(1, id); try (ResultSet results = statement.executeQuery()) { if (results.next()) { worlds[i] = new World(id, results.getInt("randomNumber")); } } } } } catch (SQLException sqlex) { System.err.println("SQL Exception: " + sqlex); } // Write JSON encoded message to the response. try { - Common.MAPPER.writeValue(res.getOutputStream(), worlds); + if (count == 1) + { + Common.MAPPER.writeValue(res.getOutputStream(), worlds[0]); + } + else + { + Common.MAPPER.writeValue(res.getOutputStream(), worlds); + } } catch (IOException ioe) { // do nothing } } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Set content type to JSON res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON); // Reference the data source. final DataSource source = mysqlDataSource; // Get the count of queries to run. int count = 1; try { count = Integer.parseInt(req.getParameter("queries")); // Bounds check. if (count > 500) { count = 500; } if (count < 1) { count = 1; } } catch (NumberFormatException nfexc) { // Do nothing. } // Fetch some rows from the database. final World[] worlds = new World[count]; final Random random = ThreadLocalRandom.current(); try (Connection conn = source.getConnection()) { try (PreparedStatement statement = conn.prepareStatement(DB_QUERY, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { // Run the query the number of times requested. for (int i = 0; i < count; i++) { final int id = random.nextInt(DB_ROWS) + 1; statement.setInt(1, id); try (ResultSet results = statement.executeQuery()) { if (results.next()) { worlds[i] = new World(id, results.getInt("randomNumber")); } } } } } catch (SQLException sqlex) { System.err.println("SQL Exception: " + sqlex); } // Write JSON encoded message to the response. try { Common.MAPPER.writeValue(res.getOutputStream(), worlds); } catch (IOException ioe) { // do nothing } }
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Set content type to JSON res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON); // Reference the data source. final DataSource source = mysqlDataSource; // Get the count of queries to run. int count = 1; try { count = Integer.parseInt(req.getParameter("queries")); // Bounds check. if (count > 500) { count = 500; } if (count < 1) { count = 1; } } catch (NumberFormatException nfexc) { // Do nothing. } // Fetch some rows from the database. final World[] worlds = new World[count]; final Random random = ThreadLocalRandom.current(); try (Connection conn = source.getConnection()) { try (PreparedStatement statement = conn.prepareStatement(DB_QUERY, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { // Run the query the number of times requested. for (int i = 0; i < count; i++) { final int id = random.nextInt(DB_ROWS) + 1; statement.setInt(1, id); try (ResultSet results = statement.executeQuery()) { if (results.next()) { worlds[i] = new World(id, results.getInt("randomNumber")); } } } } } catch (SQLException sqlex) { System.err.println("SQL Exception: " + sqlex); } // Write JSON encoded message to the response. try { if (count == 1) { Common.MAPPER.writeValue(res.getOutputStream(), worlds[0]); } else { Common.MAPPER.writeValue(res.getOutputStream(), worlds); } } catch (IOException ioe) { // do nothing } }
diff --git a/htroot/htdocsdefault/welcome.java b/htroot/htdocsdefault/welcome.java index d80562369..731b1b96a 100644 --- a/htroot/htdocsdefault/welcome.java +++ b/htroot/htdocsdefault/welcome.java @@ -1,83 +1,83 @@ // welcome.java // ----------------------- // part of the AnomicHTTPD caching proxy // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // last change: 05.08.2004 // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. // you must compile this file with // javac -classpath .:../Classes index.java // if the shell's current path is HTROOT import java.util.*; import de.anomic.tools.*; import de.anomic.server.*; import de.anomic.yacy.*; import de.anomic.http.*; public class welcome { public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { // return variable that accumulates replacements serverObjects prop = new serverObjects(); // set values String s; int pos; // update seed info yacyCore.peerActions.updateMySeed(); prop.put("peername", env.getConfig("peerName", "<nameless>")); prop.put("peerdomain", env.getConfig("peerName", "<nameless>").toLowerCase()); prop.put("peeraddress", yacyCore.seedDB.mySeed.getAddress()); prop.put("hostname", serverCore.publicIP().getHostName()); prop.put("hostip", serverCore.publicIP().getHostAddress()); prop.put("port", env.getConfig("port", "8080")); prop.put("clientip", header.get("CLIENTIP", "")); String peertype = (yacyCore.seedDB.mySeed == null) ? "virgin" : yacyCore.seedDB.mySeed.get("PeerType", "virgin"); boolean senior = (peertype.equals("senior")) || (peertype.equals("principal")); if (senior) prop.put("couldcan", "can"); else prop.put("couldcan", "could"); - if (senior) prop.put("seniorinfo", "This peer runs in senior mode which means that your peer can be accessed using the addresses shown above."); else prop.put("seniorinfo", "<b>Nobody can access your peer from the outside of your intranet. You must open your firewall and/or set a 'virtual server' at your router settings to enable access to the addresses as shown below.</b>"); + if (senior) prop.put("seniorinfo", "This peer runs in senior mode which means that your peer can be accessed using the addresses shown above."); else prop.put("seniorinfo", "<b>Nobody can access your peer from the outside of your intranet. You must open your firewall and/or set a 'virtual server' in the settings of your router to enable access to the addresses as shown below.</b>"); prop.put("wwwpath", "<application_root_path>/" + env.getConfig("htDocsPath", "DATA/HTDOCS")); // return rewrite properties return prop; } }
true
true
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { // return variable that accumulates replacements serverObjects prop = new serverObjects(); // set values String s; int pos; // update seed info yacyCore.peerActions.updateMySeed(); prop.put("peername", env.getConfig("peerName", "<nameless>")); prop.put("peerdomain", env.getConfig("peerName", "<nameless>").toLowerCase()); prop.put("peeraddress", yacyCore.seedDB.mySeed.getAddress()); prop.put("hostname", serverCore.publicIP().getHostName()); prop.put("hostip", serverCore.publicIP().getHostAddress()); prop.put("port", env.getConfig("port", "8080")); prop.put("clientip", header.get("CLIENTIP", "")); String peertype = (yacyCore.seedDB.mySeed == null) ? "virgin" : yacyCore.seedDB.mySeed.get("PeerType", "virgin"); boolean senior = (peertype.equals("senior")) || (peertype.equals("principal")); if (senior) prop.put("couldcan", "can"); else prop.put("couldcan", "could"); if (senior) prop.put("seniorinfo", "This peer runs in senior mode which means that your peer can be accessed using the addresses shown above."); else prop.put("seniorinfo", "<b>Nobody can access your peer from the outside of your intranet. You must open your firewall and/or set a 'virtual server' at your router settings to enable access to the addresses as shown below.</b>"); prop.put("wwwpath", "<application_root_path>/" + env.getConfig("htDocsPath", "DATA/HTDOCS")); // return rewrite properties return prop; }
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { // return variable that accumulates replacements serverObjects prop = new serverObjects(); // set values String s; int pos; // update seed info yacyCore.peerActions.updateMySeed(); prop.put("peername", env.getConfig("peerName", "<nameless>")); prop.put("peerdomain", env.getConfig("peerName", "<nameless>").toLowerCase()); prop.put("peeraddress", yacyCore.seedDB.mySeed.getAddress()); prop.put("hostname", serverCore.publicIP().getHostName()); prop.put("hostip", serverCore.publicIP().getHostAddress()); prop.put("port", env.getConfig("port", "8080")); prop.put("clientip", header.get("CLIENTIP", "")); String peertype = (yacyCore.seedDB.mySeed == null) ? "virgin" : yacyCore.seedDB.mySeed.get("PeerType", "virgin"); boolean senior = (peertype.equals("senior")) || (peertype.equals("principal")); if (senior) prop.put("couldcan", "can"); else prop.put("couldcan", "could"); if (senior) prop.put("seniorinfo", "This peer runs in senior mode which means that your peer can be accessed using the addresses shown above."); else prop.put("seniorinfo", "<b>Nobody can access your peer from the outside of your intranet. You must open your firewall and/or set a 'virtual server' in the settings of your router to enable access to the addresses as shown below.</b>"); prop.put("wwwpath", "<application_root_path>/" + env.getConfig("htDocsPath", "DATA/HTDOCS")); // return rewrite properties return prop; }
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/PrefetchSubscription.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/PrefetchSubscription.java index 43f31633a..250231789 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/PrefetchSubscription.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/PrefetchSubscription.java @@ -1,748 +1,750 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.broker.region; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.jms.InvalidSelectorException; import javax.jms.JMSException; import org.apache.activemq.ActiveMQMessageAudit; import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.region.cursors.PendingMessageCursor; import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor; import org.apache.activemq.command.ConsumerControl; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessageDispatch; import org.apache.activemq.command.MessageDispatchNotification; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.MessagePull; import org.apache.activemq.command.Response; import org.apache.activemq.thread.Scheduler; import org.apache.activemq.transaction.Synchronization; import org.apache.activemq.usage.SystemUsage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A subscription that honors the pre-fetch option of the ConsumerInfo. * * @version $Revision: 1.15 $ */ public abstract class PrefetchSubscription extends AbstractSubscription { private static final Log LOG = LogFactory.getLog(PrefetchSubscription.class); protected static final Scheduler scheduler = Scheduler.getInstance(); protected PendingMessageCursor pending; protected final List<MessageReference> dispatched = new CopyOnWriteArrayList<MessageReference>(); protected int prefetchExtension; protected long enqueueCounter; protected long dispatchCounter; protected long dequeueCounter; private int maxProducersToAudit=32; private int maxAuditDepth=2048; protected final SystemUsage usageManager; private final Object pendingLock = new Object(); private final Object dispatchLock = new Object(); protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); private boolean slowConsumer; private CountDownLatch okForAckAsDispatchDone = new CountDownLatch(1); public PrefetchSubscription(Broker broker, SystemUsage usageManager, ConnectionContext context, ConsumerInfo info, PendingMessageCursor cursor) throws InvalidSelectorException { super(broker,context, info); this.usageManager=usageManager; pending = cursor; } public PrefetchSubscription(Broker broker,SystemUsage usageManager, ConnectionContext context, ConsumerInfo info) throws InvalidSelectorException { this(broker,usageManager,context, info, new VMPendingMessageCursor()); } /** * Allows a message to be pulled on demand by a client */ public Response pullMessage(ConnectionContext context, MessagePull pull) throws Exception { // The slave should not deliver pull messages. TODO: when the slave // becomes a master, // He should send a NULL message to all the consumers to 'wake them up' // in case // they were waiting for a message. if (getPrefetchSize() == 0 && !isSlave()) { final long dispatchCounterBeforePull; synchronized(this) { prefetchExtension++; dispatchCounterBeforePull = dispatchCounter; } // Have the destination push us some messages. for (Destination dest : destinations) { dest.iterate(); } dispatchPending(); synchronized(this) { // If there was nothing dispatched.. we may need to setup a timeout. if (dispatchCounterBeforePull == dispatchCounter) { // immediate timeout used by receiveNoWait() if (pull.getTimeout() == -1) { // Send a NULL message. add(QueueMessageReference.NULL_MESSAGE); dispatchPending(); } if (pull.getTimeout() > 0) { scheduler.executeAfterDelay(new Runnable() { public void run() { pullTimeout(dispatchCounterBeforePull); } }, pull.getTimeout()); } } } } return null; } /** * Occurs when a pull times out. If nothing has been dispatched since the * timeout was setup, then send the NULL message. */ final void pullTimeout(long dispatchCounterBeforePull) { synchronized (pendingLock) { if (dispatchCounterBeforePull == dispatchCounter) { try { add(QueueMessageReference.NULL_MESSAGE); dispatchPending(); } catch (Exception e) { context.getConnection().serviceException(e); } } } } public void add(MessageReference node) throws Exception { synchronized (pendingLock) { // The destination may have just been removed... if( !destinations.contains(node.getRegionDestination()) && node!=QueueMessageReference.NULL_MESSAGE) { // perhaps we should inform the caller that we are no longer valid to dispatch to? return; } enqueueCounter++; pending.addMessageLast(node); } dispatchPending(); } public void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception { synchronized(pendingLock) { try { pending.reset(); while (pending.hasNext()) { MessageReference node = pending.next(); if (node.getMessageId().equals(mdn.getMessageId())) { // Synchronize between dispatched list and removal of messages from pending list // related to remove subscription action synchronized(dispatchLock) { pending.remove(); createMessageDispatch(node, node.getMessage()); dispatched.add(node); onDispatch(node, node.getMessage()); } return; } } } finally { pending.release(); } } throw new JMSException( "Slave broker out of sync with master: Dispatched message (" + mdn.getMessageId() + ") was not in the pending list for " + mdn.getConsumerId() + " on " + mdn.getDestination().getPhysicalName()); } public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception { // Handle the standard acknowledgment case. boolean callDispatchMatched = false; Destination destination = null; if (!isSlave()) { - while(!okForAckAsDispatchDone.await(100, TimeUnit.MILLISECONDS)) { - LOG.warn("Ack before disaptch, waiting for recovery dispatch: " + ack); + if (!okForAckAsDispatchDone.await(0l, TimeUnit.MILLISECONDS)) { + // suppress unexpected ack exception in this expected case + LOG.warn("Ignoring ack received before dispatch; result of failover with an outstanding ack. Acked messages will be replayed if present on this broker. Ignored ack: " + ack); + return; } } if (LOG.isTraceEnabled()) { LOG.trace("ack:" + ack); } synchronized(dispatchLock) { if (ack.isStandardAck()) { // First check if the ack matches the dispatched. When using failover this might // not be the case. We don't ever want to ack the wrong messages. assertAckMatchesDispatched(ack); // Acknowledge all dispatched messages up till the message id of // the acknowledgment. int index = 0; boolean inAckRange = false; List<MessageReference> removeList = new ArrayList<MessageReference>(); for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { // Don't remove the nodes until we are committed. if (!context.isInTransaction()) { dequeueCounter++; if (!this.getConsumerInfo().isBrowser()) { node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); } node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); removeList.add(node); } else { // setup a Synchronization to remove nodes from the // dispatched list. context.getTransaction().addSynchronization( new Synchronization() { public void afterCommit() throws Exception { synchronized(dispatchLock) { dequeueCounter++; dispatched.remove(node); node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); prefetchExtension--; } } public void afterRollback() throws Exception { synchronized(dispatchLock) { node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); } } }); } index++; acknowledge(context, ack, node); if (ack.getLastMessageId().equals(messageId)) { if (context.isInTransaction()) { // extend prefetch window only if not a pulling // consumer if (getPrefetchSize() != 0) { prefetchExtension = Math.max( prefetchExtension, index ); } } else { prefetchExtension = Math.max(0, prefetchExtension - index); } destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } for (final MessageReference node : removeList) { dispatched.remove(node); } // this only happens after a reconnect - get an ack which is not // valid if (!callDispatchMatched) { LOG.error("Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isIndividualAck()) { // Message was delivered and acknowledge - but only delete the // individual message for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getLastMessageId().equals(messageId)) { // this should never be within a transaction node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); destination = node.getRegionDestination(); acknowledge(context, ack, node); dispatched.remove(node); prefetchExtension = Math.max(0, prefetchExtension - 1); callDispatchMatched = true; break; } } }else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch // counters. int index = 0; for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) { final MessageReference node = iter.next(); if( node.isExpired() ) { node.getRegionDestination().messageExpired(context, this, node); dispatched.remove(node); } if (ack.getLastMessageId().equals(node.getMessageId())) { prefetchExtension = Math.max(prefetchExtension, index + 1); destination = node.getRegionDestination(); callDispatchMatched = true; break; } } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isRedeliveredAck()) { // Message was re-delivered but it was not yet considered to be // a DLQ message. // Acknowledge all dispatched messages up till the message id of // the ack. boolean inAckRange = false; for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { if (ack.getLastMessageId().equals(messageId)) { destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isPoisonAck()) { // TODO: what if the message is already in a DLQ??? // Handle the poison ACK case: we need to send the message to a // DLQ if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } // Acknowledge all dispatched messages up till the message id of // the // acknowledgment. int index = 0; boolean inAckRange = false; List<MessageReference> removeList = new ArrayList<MessageReference>(); for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { sendToDLQ(context, node); node.getRegionDestination().getDestinationStatistics() .getDequeues().increment(); node.getRegionDestination().getDestinationStatistics() .getInflight().increment(); removeList.add(node); dequeueCounter++; index++; acknowledge(context, ack, node); if (ack.getLastMessageId().equals(messageId)) { prefetchExtension = Math.max(0, prefetchExtension - (index + 1)); destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } for (final MessageReference node : removeList) { dispatched.remove(node); } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } } if (callDispatchMatched && destination != null) { destination.wakeup(); dispatchPending(); } else { if (isSlave()) { throw new JMSException( "Slave broker out of sync with master: Acknowledgment (" + ack + ") was not in the dispatch list: " + dispatched); } else { LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): " + ack); } } } /** * Checks an ack versus the contents of the dispatched list. * * @param ack * @param firstAckedMsg * @param lastAckedMsg * @throws JMSException if it does not match */ protected void assertAckMatchesDispatched(MessageAck ack) throws JMSException { MessageId firstAckedMsg = ack.getFirstMessageId(); MessageId lastAckedMsg = ack.getLastMessageId(); int checkCount = 0; boolean checkFoundStart = false; boolean checkFoundEnd = false; for (MessageReference node : dispatched) { if (firstAckedMsg == null) { checkFoundStart = true; } else if (!checkFoundStart && firstAckedMsg.equals(node.getMessageId())) { checkFoundStart = true; } if (checkFoundStart) { checkCount++; } if (lastAckedMsg != null && lastAckedMsg.equals(node.getMessageId())) { checkFoundEnd = true; break; } } if (!checkFoundStart && firstAckedMsg != null) throw new JMSException("Unmatched acknowledege: " + ack + "; Could not find Message-ID " + firstAckedMsg + " in dispatched-list (start of ack)"); if (!checkFoundEnd && lastAckedMsg != null) throw new JMSException("Unmatched acknowledege: " + ack + "; Could not find Message-ID " + lastAckedMsg + " in dispatched-list (end of ack)"); if (ack.getMessageCount() != checkCount && !ack.isInTransaction()) { throw new JMSException("Unmatched acknowledege: " + ack + "; Expected message count (" + ack.getMessageCount() + ") differs from count in dispatched-list (" + checkCount + ")"); } } /** * @param context * @param node * @throws IOException * @throws Exception */ protected void sendToDLQ(final ConnectionContext context, final MessageReference node) throws IOException, Exception { broker.sendToDeadLetterQueue(context, node); } public int getInFlightSize() { return dispatched.size(); } /** * Used to determine if the broker can dispatch to the consumer. * * @return */ public boolean isFull() { return dispatched.size() - prefetchExtension >= info.getPrefetchSize(); } /** * @return true when 60% or more room is left for dispatching messages */ public boolean isLowWaterMark() { return (dispatched.size() - prefetchExtension) <= (info.getPrefetchSize() * .4); } /** * @return true when 10% or less room is left for dispatching messages */ public boolean isHighWaterMark() { return (dispatched.size() - prefetchExtension) >= (info.getPrefetchSize() * .9); } public int countBeforeFull() { return info.getPrefetchSize() + prefetchExtension - dispatched.size(); } public int getPendingQueueSize() { return pending.size(); } public int getDispatchedQueueSize() { return dispatched.size(); } public long getDequeueCounter() { return dequeueCounter; } public long getDispatchedCounter() { return dispatchCounter; } public long getEnqueueCounter() { return enqueueCounter; } public boolean isRecoveryRequired() { return pending.isRecoveryRequired(); } public PendingMessageCursor getPending() { return this.pending; } public void setPending(PendingMessageCursor pending) { this.pending = pending; if (this.pending!=null) { this.pending.setSystemUsage(usageManager); } } public void add(ConnectionContext context, Destination destination) throws Exception { synchronized(pendingLock) { super.add(context, destination); pending.add(context, destination); } } public List<MessageReference> remove(ConnectionContext context, Destination destination) throws Exception { List<MessageReference> rc = new ArrayList<MessageReference>(); synchronized(pendingLock) { super.remove(context, destination); // Synchronized to DispatchLock synchronized(dispatchLock) { for (MessageReference r : dispatched) { if( r.getRegionDestination() == destination) { rc.add((QueueMessageReference)r); } } } // TODO Dispatched messages should be decremented from Inflight stat // Here is a potential problem concerning Inflight stat: // Messages not already committed or rolled back may not be removed from dispatched list at the moment // Except if each commit or rollback callback action comes before remove of subscriber. rc.addAll(pending.remove(context, destination)); } return rc; } protected void dispatchPending() throws IOException { if (!isSlave()) { synchronized(pendingLock) { try { int numberToDispatch = countBeforeFull(); if (numberToDispatch > 0) { slowConsumer=false; pending.setMaxBatchSize(numberToDispatch); int count = 0; pending.reset(); while (pending.hasNext() && !isFull() && count < numberToDispatch) { MessageReference node = pending.next(); if (node == null) { break; } // Synchronize between dispatched list and remove of message from pending list // related to remove subscription action synchronized(dispatchLock) { pending.remove(); if( !isDropped(node) && canDispatch(node)) { // Message may have been sitting in the pending // list a while waiting for the consumer to ak the message. if (node!=QueueMessageReference.NULL_MESSAGE && node.isExpired()) { //increment number to dispatch numberToDispatch++; node.getRegionDestination().messageExpired(context, this, node); continue; } dispatch(node); count++; } } } }else { if (!slowConsumer) { slowConsumer=true; ConnectionContext c = new ConnectionContext(); c.setBroker(context.getBroker()); for (Destination dest :destinations) { dest.slowConsumer(c,this); } } } } finally { pending.release(); } } } } protected boolean dispatch(final MessageReference node) throws IOException { final Message message = node.getMessage(); if (message == null) { return false; } okForAckAsDispatchDone.countDown(); // No reentrant lock - Patch needed to IndirectMessageReference on method lock if (!isSlave()) { MessageDispatch md = createMessageDispatch(node, message); // NULL messages don't count... they don't get Acked. if (node != QueueMessageReference.NULL_MESSAGE) { dispatchCounter++; dispatched.add(node); } else { prefetchExtension = Math.max(0, prefetchExtension - 1); } if (info.isDispatchAsync()) { md.setTransmitCallback(new Runnable() { public void run() { // Since the message gets queued up in async dispatch, // we don't want to // decrease the reference count until it gets put on the // wire. onDispatch(node, message); } }); context.getConnection().dispatchAsync(md); } else { context.getConnection().dispatchSync(md); onDispatch(node, message); } return true; } else { return false; } } protected void onDispatch(final MessageReference node, final Message message) { if (node.getRegionDestination() != null) { if (node != QueueMessageReference.NULL_MESSAGE) { node.getRegionDestination().getDestinationStatistics().getDispatched().increment(); node.getRegionDestination().getDestinationStatistics().getInflight().increment(); } } if (LOG.isTraceEnabled()) { LOG.trace(info.getDestination().getPhysicalName() + " dispatched: " + message.getMessageId()); } if (info.isDispatchAsync()) { try { dispatchPending(); } catch (IOException e) { context.getConnection().serviceExceptionAsync(e); } } } /** * inform the MessageConsumer on the client to change it's prefetch * * @param newPrefetch */ public void updateConsumerPrefetch(int newPrefetch) { if (context != null && context.getConnection() != null && context.getConnection().isManageable()) { ConsumerControl cc = new ConsumerControl(); cc.setConsumerId(info.getConsumerId()); cc.setPrefetch(newPrefetch); context.getConnection().dispatchAsync(cc); } } /** * @param node * @param message * @return MessageDispatch */ protected MessageDispatch createMessageDispatch(MessageReference node, Message message) { if (node == QueueMessageReference.NULL_MESSAGE) { MessageDispatch md = new MessageDispatch(); md.setMessage(null); md.setConsumerId(info.getConsumerId()); md.setDestination(null); return md; } else { MessageDispatch md = new MessageDispatch(); md.setConsumerId(info.getConsumerId()); md.setDestination(node.getRegionDestination().getActiveMQDestination()); md.setMessage(message); md.setRedeliveryCounter(node.getRedeliveryCounter()); return md; } } /** * Use when a matched message is about to be dispatched to the client. * * @param node * @return false if the message should not be dispatched to the client * (another sub may have already dispatched it for example). * @throws IOException */ protected abstract boolean canDispatch(MessageReference node) throws IOException; protected abstract boolean isDropped(MessageReference node); /** * Used during acknowledgment to remove the message. * * @throws IOException */ protected abstract void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference node) throws IOException; public int getMaxProducersToAudit() { return maxProducersToAudit; } public void setMaxProducersToAudit(int maxProducersToAudit) { this.maxProducersToAudit = maxProducersToAudit; } public int getMaxAuditDepth() { return maxAuditDepth; } public void setMaxAuditDepth(int maxAuditDepth) { this.maxAuditDepth = maxAuditDepth; } }
true
true
public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception { // Handle the standard acknowledgment case. boolean callDispatchMatched = false; Destination destination = null; if (!isSlave()) { while(!okForAckAsDispatchDone.await(100, TimeUnit.MILLISECONDS)) { LOG.warn("Ack before disaptch, waiting for recovery dispatch: " + ack); } } if (LOG.isTraceEnabled()) { LOG.trace("ack:" + ack); } synchronized(dispatchLock) { if (ack.isStandardAck()) { // First check if the ack matches the dispatched. When using failover this might // not be the case. We don't ever want to ack the wrong messages. assertAckMatchesDispatched(ack); // Acknowledge all dispatched messages up till the message id of // the acknowledgment. int index = 0; boolean inAckRange = false; List<MessageReference> removeList = new ArrayList<MessageReference>(); for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { // Don't remove the nodes until we are committed. if (!context.isInTransaction()) { dequeueCounter++; if (!this.getConsumerInfo().isBrowser()) { node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); } node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); removeList.add(node); } else { // setup a Synchronization to remove nodes from the // dispatched list. context.getTransaction().addSynchronization( new Synchronization() { public void afterCommit() throws Exception { synchronized(dispatchLock) { dequeueCounter++; dispatched.remove(node); node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); prefetchExtension--; } } public void afterRollback() throws Exception { synchronized(dispatchLock) { node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); } } }); } index++; acknowledge(context, ack, node); if (ack.getLastMessageId().equals(messageId)) { if (context.isInTransaction()) { // extend prefetch window only if not a pulling // consumer if (getPrefetchSize() != 0) { prefetchExtension = Math.max( prefetchExtension, index ); } } else { prefetchExtension = Math.max(0, prefetchExtension - index); } destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } for (final MessageReference node : removeList) { dispatched.remove(node); } // this only happens after a reconnect - get an ack which is not // valid if (!callDispatchMatched) { LOG.error("Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isIndividualAck()) { // Message was delivered and acknowledge - but only delete the // individual message for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getLastMessageId().equals(messageId)) { // this should never be within a transaction node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); destination = node.getRegionDestination(); acknowledge(context, ack, node); dispatched.remove(node); prefetchExtension = Math.max(0, prefetchExtension - 1); callDispatchMatched = true; break; } } }else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch // counters. int index = 0; for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) { final MessageReference node = iter.next(); if( node.isExpired() ) { node.getRegionDestination().messageExpired(context, this, node); dispatched.remove(node); } if (ack.getLastMessageId().equals(node.getMessageId())) { prefetchExtension = Math.max(prefetchExtension, index + 1); destination = node.getRegionDestination(); callDispatchMatched = true; break; } } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isRedeliveredAck()) { // Message was re-delivered but it was not yet considered to be // a DLQ message. // Acknowledge all dispatched messages up till the message id of // the ack. boolean inAckRange = false; for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { if (ack.getLastMessageId().equals(messageId)) { destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isPoisonAck()) { // TODO: what if the message is already in a DLQ??? // Handle the poison ACK case: we need to send the message to a // DLQ if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } // Acknowledge all dispatched messages up till the message id of // the // acknowledgment. int index = 0; boolean inAckRange = false; List<MessageReference> removeList = new ArrayList<MessageReference>(); for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { sendToDLQ(context, node); node.getRegionDestination().getDestinationStatistics() .getDequeues().increment(); node.getRegionDestination().getDestinationStatistics() .getInflight().increment(); removeList.add(node); dequeueCounter++; index++; acknowledge(context, ack, node); if (ack.getLastMessageId().equals(messageId)) { prefetchExtension = Math.max(0, prefetchExtension - (index + 1)); destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } for (final MessageReference node : removeList) { dispatched.remove(node); } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } } if (callDispatchMatched && destination != null) { destination.wakeup(); dispatchPending(); } else { if (isSlave()) { throw new JMSException( "Slave broker out of sync with master: Acknowledgment (" + ack + ") was not in the dispatch list: " + dispatched); } else { LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): " + ack); } } }
public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception { // Handle the standard acknowledgment case. boolean callDispatchMatched = false; Destination destination = null; if (!isSlave()) { if (!okForAckAsDispatchDone.await(0l, TimeUnit.MILLISECONDS)) { // suppress unexpected ack exception in this expected case LOG.warn("Ignoring ack received before dispatch; result of failover with an outstanding ack. Acked messages will be replayed if present on this broker. Ignored ack: " + ack); return; } } if (LOG.isTraceEnabled()) { LOG.trace("ack:" + ack); } synchronized(dispatchLock) { if (ack.isStandardAck()) { // First check if the ack matches the dispatched. When using failover this might // not be the case. We don't ever want to ack the wrong messages. assertAckMatchesDispatched(ack); // Acknowledge all dispatched messages up till the message id of // the acknowledgment. int index = 0; boolean inAckRange = false; List<MessageReference> removeList = new ArrayList<MessageReference>(); for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { // Don't remove the nodes until we are committed. if (!context.isInTransaction()) { dequeueCounter++; if (!this.getConsumerInfo().isBrowser()) { node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); } node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); removeList.add(node); } else { // setup a Synchronization to remove nodes from the // dispatched list. context.getTransaction().addSynchronization( new Synchronization() { public void afterCommit() throws Exception { synchronized(dispatchLock) { dequeueCounter++; dispatched.remove(node); node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); prefetchExtension--; } } public void afterRollback() throws Exception { synchronized(dispatchLock) { node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); } } }); } index++; acknowledge(context, ack, node); if (ack.getLastMessageId().equals(messageId)) { if (context.isInTransaction()) { // extend prefetch window only if not a pulling // consumer if (getPrefetchSize() != 0) { prefetchExtension = Math.max( prefetchExtension, index ); } } else { prefetchExtension = Math.max(0, prefetchExtension - index); } destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } for (final MessageReference node : removeList) { dispatched.remove(node); } // this only happens after a reconnect - get an ack which is not // valid if (!callDispatchMatched) { LOG.error("Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isIndividualAck()) { // Message was delivered and acknowledge - but only delete the // individual message for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getLastMessageId().equals(messageId)) { // this should never be within a transaction node.getRegionDestination().getDestinationStatistics().getDequeues().increment(); node.getRegionDestination().getDestinationStatistics().getInflight().decrement(); destination = node.getRegionDestination(); acknowledge(context, ack, node); dispatched.remove(node); prefetchExtension = Math.max(0, prefetchExtension - 1); callDispatchMatched = true; break; } } }else if (ack.isDeliveredAck()) { // Message was delivered but not acknowledged: update pre-fetch // counters. int index = 0; for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) { final MessageReference node = iter.next(); if( node.isExpired() ) { node.getRegionDestination().messageExpired(context, this, node); dispatched.remove(node); } if (ack.getLastMessageId().equals(node.getMessageId())) { prefetchExtension = Math.max(prefetchExtension, index + 1); destination = node.getRegionDestination(); callDispatchMatched = true; break; } } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isRedeliveredAck()) { // Message was re-delivered but it was not yet considered to be // a DLQ message. // Acknowledge all dispatched messages up till the message id of // the ack. boolean inAckRange = false; for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { if (ack.getLastMessageId().equals(messageId)) { destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } else if (ack.isPoisonAck()) { // TODO: what if the message is already in a DLQ??? // Handle the poison ACK case: we need to send the message to a // DLQ if (ack.isInTransaction()) { throw new JMSException("Poison ack cannot be transacted: " + ack); } // Acknowledge all dispatched messages up till the message id of // the // acknowledgment. int index = 0; boolean inAckRange = false; List<MessageReference> removeList = new ArrayList<MessageReference>(); for (final MessageReference node : dispatched) { MessageId messageId = node.getMessageId(); if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { inAckRange = true; } if (inAckRange) { sendToDLQ(context, node); node.getRegionDestination().getDestinationStatistics() .getDequeues().increment(); node.getRegionDestination().getDestinationStatistics() .getInflight().increment(); removeList.add(node); dequeueCounter++; index++; acknowledge(context, ack, node); if (ack.getLastMessageId().equals(messageId)) { prefetchExtension = Math.max(0, prefetchExtension - (index + 1)); destination = node.getRegionDestination(); callDispatchMatched = true; break; } } } for (final MessageReference node : removeList) { dispatched.remove(node); } if (!callDispatchMatched) { throw new JMSException( "Could not correlate acknowledgment with dispatched message: " + ack); } } } if (callDispatchMatched && destination != null) { destination.wakeup(); dispatchPending(); } else { if (isSlave()) { throw new JMSException( "Slave broker out of sync with master: Acknowledgment (" + ack + ") was not in the dispatch list: " + dispatched); } else { LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): " + ack); } } }
diff --git a/client/net/minecraftforge/client/model/AdvancedModelLoader.java b/client/net/minecraftforge/client/model/AdvancedModelLoader.java index d2e888237..f5137d1dd 100644 --- a/client/net/minecraftforge/client/model/AdvancedModelLoader.java +++ b/client/net/minecraftforge/client/model/AdvancedModelLoader.java @@ -1,82 +1,82 @@ package net.minecraftforge.client.model; import java.io.InputStream; import java.net.URL; import java.util.Collection; import java.util.Map; import net.minecraftforge.client.model.obj.ObjModelLoader; import com.google.common.collect.Maps; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * Common interface for advanced model loading from files, based on file suffix * Model support can be queried through the {@link #getSupportedSuffixes()} method. * Instances can be created by calling {@link #loadModel(String)} with a class-loadable-path * * @author cpw * */ @SideOnly(Side.CLIENT) public class AdvancedModelLoader { private static Map<String, IModelCustomLoader> instances = Maps.newHashMap(); /** * Register a new model handler * @param modelHandler The model handler to register */ public static void registerModelHandler(IModelCustomLoader modelHandler) { for (String suffix : modelHandler.getSuffixes()) { instances.put(suffix, modelHandler); } } /** * Load the model from the supplied classpath resolvable resource name * @param resourceName The resource name * @return A model * @throws IllegalArgumentException if the resource name cannot be understood * @throws ModelFormatException if the underlying model handler cannot parse the model format */ public static IModelCustom loadModel(String resourceName) throws IllegalArgumentException, ModelFormatException { int i = resourceName.lastIndexOf('.'); if (i == -1) { FMLLog.severe("The resource name %s is not valid", resourceName); throw new IllegalArgumentException("The resource name is not valid"); } - String suffix = resourceName.substring(i); + String suffix = resourceName.substring(i+1); IModelCustomLoader loader = instances.get(suffix); if (loader == null) { FMLLog.severe("The resource name %s is not supported", resourceName); throw new IllegalArgumentException("The resource name is not supported"); } URL resource = AdvancedModelLoader.class.getResource(resourceName); if (resource == null) { FMLLog.severe("The resource name %s could not be found", resourceName); throw new IllegalArgumentException("The resource name could not be found"); } return loader.loadInstance(resourceName, resource); } public static Collection<String> getSupportedSuffixes() { return instances.keySet(); } static { registerModelHandler(new ObjModelLoader()); } }
true
true
public static IModelCustom loadModel(String resourceName) throws IllegalArgumentException, ModelFormatException { int i = resourceName.lastIndexOf('.'); if (i == -1) { FMLLog.severe("The resource name %s is not valid", resourceName); throw new IllegalArgumentException("The resource name is not valid"); } String suffix = resourceName.substring(i); IModelCustomLoader loader = instances.get(suffix); if (loader == null) { FMLLog.severe("The resource name %s is not supported", resourceName); throw new IllegalArgumentException("The resource name is not supported"); } URL resource = AdvancedModelLoader.class.getResource(resourceName); if (resource == null) { FMLLog.severe("The resource name %s could not be found", resourceName); throw new IllegalArgumentException("The resource name could not be found"); } return loader.loadInstance(resourceName, resource); }
public static IModelCustom loadModel(String resourceName) throws IllegalArgumentException, ModelFormatException { int i = resourceName.lastIndexOf('.'); if (i == -1) { FMLLog.severe("The resource name %s is not valid", resourceName); throw new IllegalArgumentException("The resource name is not valid"); } String suffix = resourceName.substring(i+1); IModelCustomLoader loader = instances.get(suffix); if (loader == null) { FMLLog.severe("The resource name %s is not supported", resourceName); throw new IllegalArgumentException("The resource name is not supported"); } URL resource = AdvancedModelLoader.class.getResource(resourceName); if (resource == null) { FMLLog.severe("The resource name %s could not be found", resourceName); throw new IllegalArgumentException("The resource name could not be found"); } return loader.loadInstance(resourceName, resource); }
diff --git a/src/ch/hsr/hsrlunch/util/CheckRessources.java b/src/ch/hsr/hsrlunch/util/CheckRessources.java index 78dbff9..a5e0d67 100644 --- a/src/ch/hsr/hsrlunch/util/CheckRessources.java +++ b/src/ch/hsr/hsrlunch/util/CheckRessources.java @@ -1,40 +1,40 @@ package ch.hsr.hsrlunch.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; public class CheckRessources { public static boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } public static boolean isOnHSRwifi(Context context) { if (isOnline(context)) { WifiManager wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ssid = wifiInfo.getSSID(); if (ssid == null) { return false; } - if (ssid.equals("HSR-Secure")) { + if (ssid.contains("HSR-Secure")) { return true; } } return false; } }
true
true
public static boolean isOnHSRwifi(Context context) { if (isOnline(context)) { WifiManager wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ssid = wifiInfo.getSSID(); if (ssid == null) { return false; } if (ssid.equals("HSR-Secure")) { return true; } } return false; }
public static boolean isOnHSRwifi(Context context) { if (isOnline(context)) { WifiManager wifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ssid = wifiInfo.getSSID(); if (ssid == null) { return false; } if (ssid.contains("HSR-Secure")) { return true; } } return false; }
diff --git a/src/ru/skupriyanov/src/Main.java b/src/ru/skupriyanov/src/Main.java index ee8420c..404e143 100644 --- a/src/ru/skupriyanov/src/Main.java +++ b/src/ru/skupriyanov/src/Main.java @@ -1,83 +1,84 @@ package ru.skupriyanov.src; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingWorker; import com.sun.jna.NativeLibrary; public class Main { private static final int SLEEPING_TIME_MILLIS = 10000; private static final NativeLibrary USER32_LIBRARY_INSTANCE = NativeLibrary .getInstance("user32"); private static JButton startButton; private static JButton stopButton; private static boolean continueCycle = true; public static void main(String[] args) { drawFrame(); } private static void drawFrame() { final JFrame frame = new JFrame("Cursor mover"); frame.setSize(200, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); JPanel panel = new JPanel(); startButton = new JButton("Start"); stopButton = new JButton("Stop"); panel.add(startButton); panel.add(stopButton); frame.add(panel); final CursorController cursorController = new CursorController(); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { + continueCycle = true; cursorController.execute(); } }); stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { continueCycle = false; } }); frame.setVisible(true); } private static class CursorController extends SwingWorker<Void, Void> { @Override protected Void doInBackground() throws Exception { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Random randomX = new Random(); Random randomY = new Random(); while (continueCycle) { Object[] callArguments = { randomX.nextInt(screenSize.width - 1), randomY.nextInt(screenSize.height - 1) }; USER32_LIBRARY_INSTANCE.getFunction("SetCursorPos").invoke( callArguments); Thread.sleep(SLEEPING_TIME_MILLIS); } return null; } } }
true
true
private static void drawFrame() { final JFrame frame = new JFrame("Cursor mover"); frame.setSize(200, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); JPanel panel = new JPanel(); startButton = new JButton("Start"); stopButton = new JButton("Stop"); panel.add(startButton); panel.add(stopButton); frame.add(panel); final CursorController cursorController = new CursorController(); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { cursorController.execute(); } }); stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { continueCycle = false; } }); frame.setVisible(true); }
private static void drawFrame() { final JFrame frame = new JFrame("Cursor mover"); frame.setSize(200, 100); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); JPanel panel = new JPanel(); startButton = new JButton("Start"); stopButton = new JButton("Stop"); panel.add(startButton); panel.add(stopButton); frame.add(panel); final CursorController cursorController = new CursorController(); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { continueCycle = true; cursorController.execute(); } }); stopButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { continueCycle = false; } }); frame.setVisible(true); }
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IPopupCalendar.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IPopupCalendar.java index 0242234c0..86e67cf1b 100644 --- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IPopupCalendar.java +++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IPopupCalendar.java @@ -1,74 +1,75 @@ package com.itmill.toolkit.terminal.gwt.client.ui; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.PopupListener; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.Widget; import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection; import com.itmill.toolkit.terminal.gwt.client.Paintable; import com.itmill.toolkit.terminal.gwt.client.UIDL; public class IPopupCalendar extends ITextualDate implements Paintable, ClickListener, PopupListener { private IButton calendarToggle; private CalendarPanel calendar; private ToolkitOverlay popup; public IPopupCalendar() { super(); calendarToggle = new IButton(); calendarToggle.setText("..."); calendarToggle.addClickListener(this); add(calendarToggle); calendar = new CalendarPanel(this); popup = new ToolkitOverlay(true); popup.setStyleName(IDateField.CLASSNAME + "-popup"); popup.setWidget(calendar); popup.addPopupListener(this); } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { super.updateFromUIDL(uidl, client); if (date != null) { calendar.updateCalendar(); } calendarToggle.setEnabled(enabled); } public void onClick(Widget sender) { if (sender == calendarToggle) { calendar.updateCalendar(); popup.show(); // clear previous values popup.setWidth(""); popup.setHeight(""); int w = calendar.getOffsetWidth(); int h = calendar.getOffsetHeight(); int t = calendarToggle.getAbsoluteTop(); int l = calendarToggle.getAbsoluteLeft(); - if (l + w > Window.getClientWidth()) { - l = Window.getClientWidth() - w; + if (l + w > Window.getClientWidth() + Window.getScrollLeft()) { + l = Window.getClientWidth() + Window.getScrollLeft() - w; } - if (t + h > Window.getClientHeight()) { - t = Window.getClientHeight() - h - - calendarToggle.getOffsetHeight() - 2; + if (t + h > Window.getClientHeight() + Window.getScrollTop()) { + t = Window.getClientHeight() + Window.getScrollTop() - h + - calendarToggle.getOffsetHeight() - 30; + l += calendarToggle.getOffsetWidth(); } popup.setPopupPosition(l, t + calendarToggle.getOffsetHeight() + 2); popup.setWidth(w + "px"); popup.setHeight(h + "px"); } } public void onPopupClosed(PopupPanel sender, boolean autoClosed) { if (sender == popup) { buildDate(); } } }
false
true
public void onClick(Widget sender) { if (sender == calendarToggle) { calendar.updateCalendar(); popup.show(); // clear previous values popup.setWidth(""); popup.setHeight(""); int w = calendar.getOffsetWidth(); int h = calendar.getOffsetHeight(); int t = calendarToggle.getAbsoluteTop(); int l = calendarToggle.getAbsoluteLeft(); if (l + w > Window.getClientWidth()) { l = Window.getClientWidth() - w; } if (t + h > Window.getClientHeight()) { t = Window.getClientHeight() - h - calendarToggle.getOffsetHeight() - 2; } popup.setPopupPosition(l, t + calendarToggle.getOffsetHeight() + 2); popup.setWidth(w + "px"); popup.setHeight(h + "px"); } }
public void onClick(Widget sender) { if (sender == calendarToggle) { calendar.updateCalendar(); popup.show(); // clear previous values popup.setWidth(""); popup.setHeight(""); int w = calendar.getOffsetWidth(); int h = calendar.getOffsetHeight(); int t = calendarToggle.getAbsoluteTop(); int l = calendarToggle.getAbsoluteLeft(); if (l + w > Window.getClientWidth() + Window.getScrollLeft()) { l = Window.getClientWidth() + Window.getScrollLeft() - w; } if (t + h > Window.getClientHeight() + Window.getScrollTop()) { t = Window.getClientHeight() + Window.getScrollTop() - h - calendarToggle.getOffsetHeight() - 30; l += calendarToggle.getOffsetWidth(); } popup.setPopupPosition(l, t + calendarToggle.getOffsetHeight() + 2); popup.setWidth(w + "px"); popup.setHeight(h + "px"); } }
diff --git a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/internal/services/EclipseAdapter.java b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/internal/services/EclipseAdapter.java index 24dbcdfa7..993c880b1 100644 --- a/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/internal/services/EclipseAdapter.java +++ b/bundles/org.eclipse.e4.core.services/src/org/eclipse/e4/core/internal/services/EclipseAdapter.java @@ -1,73 +1,73 @@ /******************************************************************************* * Copyright (c) 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.e4.core.internal.services; import javax.inject.Inject; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IAdapterManager; import org.eclipse.e4.core.services.Adapter; import org.eclipse.e4.core.services.context.IEclipseContext; public class EclipseAdapter extends Adapter { private IAdapterManager adapterManager; private IEclipseContext context; @Inject public EclipseAdapter() { } @SuppressWarnings("unchecked") @Override public <T> T adapt(Object element, Class<T> adapterType) { Assert.isNotNull(adapterType); if (element == null) { return null; } if (adapterType.isInstance(element)) { return (T) element; } if (element instanceof IAdaptable) { IAdaptable adaptable = (IAdaptable) element; Object result = adaptable.getAdapter(adapterType); if (result != null) { // Sanity-check Assert.isTrue(adapterType.isInstance(result)); return (T) result; } } if (adapterManager == null) adapterManager = lookupAdapterManager(); if (adapterManager == null) { // TODO should we log the fact that there is no adapter manager? Maybe just once return null; } - Object result = adapterManager.getAdapter(element, adapterType); + Object result = adapterManager.loadAdapter(element, adapterType.getName()); if (result != null) { // Sanity-check Assert.isTrue(adapterType.isInstance(result)); return (T) result; } return null; } private IAdapterManager lookupAdapterManager() { return (IAdapterManager) context.get(IAdapterManager.class.getName()); } public void contextSet(IEclipseContext context) { this.context = context; } }
true
true
public <T> T adapt(Object element, Class<T> adapterType) { Assert.isNotNull(adapterType); if (element == null) { return null; } if (adapterType.isInstance(element)) { return (T) element; } if (element instanceof IAdaptable) { IAdaptable adaptable = (IAdaptable) element; Object result = adaptable.getAdapter(adapterType); if (result != null) { // Sanity-check Assert.isTrue(adapterType.isInstance(result)); return (T) result; } } if (adapterManager == null) adapterManager = lookupAdapterManager(); if (adapterManager == null) { // TODO should we log the fact that there is no adapter manager? Maybe just once return null; } Object result = adapterManager.getAdapter(element, adapterType); if (result != null) { // Sanity-check Assert.isTrue(adapterType.isInstance(result)); return (T) result; } return null; }
public <T> T adapt(Object element, Class<T> adapterType) { Assert.isNotNull(adapterType); if (element == null) { return null; } if (adapterType.isInstance(element)) { return (T) element; } if (element instanceof IAdaptable) { IAdaptable adaptable = (IAdaptable) element; Object result = adaptable.getAdapter(adapterType); if (result != null) { // Sanity-check Assert.isTrue(adapterType.isInstance(result)); return (T) result; } } if (adapterManager == null) adapterManager = lookupAdapterManager(); if (adapterManager == null) { // TODO should we log the fact that there is no adapter manager? Maybe just once return null; } Object result = adapterManager.loadAdapter(element, adapterType.getName()); if (result != null) { // Sanity-check Assert.isTrue(adapterType.isInstance(result)); return (T) result; } return null; }
diff --git a/src/me/ellbristow/greylistVote/greylistVote.java b/src/me/ellbristow/greylistVote/greylistVote.java index a7f4e27..eefffa1 100644 --- a/src/me/ellbristow/greylistVote/greylistVote.java +++ b/src/me/ellbristow/greylistVote/greylistVote.java @@ -1,164 +1,184 @@ package me.ellbristow.greylistVote; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class greylistVote extends JavaPlugin { public static greylistVote plugin; public final Logger logger = Logger.getLogger("Minecraft"); public final greyBlockListener blockListener = new greyBlockListener(this); protected FileConfiguration config; private FileConfiguration usersConfig = null; private File usersFile = null; @Override public void onDisable() { PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info(pdfFile.getName() + " is now disabled."); } @Override public void onEnable() { PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled."); PluginManager pm = getServer().getPluginManager(); pm.registerEvent(Event.Type.BLOCK_PLACE, this.blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_BREAK, this.blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_IGNITE, this.blockListener, Event.Priority.Normal, this); this.config = this.getConfig(); this.config.set("required_votes", this.config.getInt("required_votes")); this.saveConfig(); this.usersConfig = this.getUsersConfig(); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { - if (commandLabel.equalsIgnoreCase("greylist")) { + if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getPlayer(args[0]); if (target == null) { // Player not online sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } if (!(sender instanceof Player)) { // Voter is the console sender.sendMessage(ChatColor.RED + "Sorry! The console can't vote!"); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } if (target.hasPermission("greylistvote.approved")) { // Target already approved sender.sendMessage(ChatColor.WHITE + target.getName() + ChatColor.RED + " has already been approved!"); return true; } int reqVotes = this.config.getInt("required_votes"); - String voteList = this.usersConfig.getString(target + ".votes", null); + String voteList = this.usersConfig.getString(target.getName() + ".votes", null); if (voteList == null) { // No votes received for this target player if (reqVotes <= 1) { // Enough votes received this.setApproved(target); return true; } this.usersConfig.set(target.getName() + ".votes", sender.getName()); } else { // Target has votes already String[] voteArray = voteList.split(","); boolean found = false; for (String vote : voteArray) { if (vote == sender.getName()) { found = true; } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } sender.sendMessage(ChatColor.GOLD + "Your greylist vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be greylisted!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be greylisted!"); } } - this.usersConfig.set(target.getName() + ".votes", voteList + ", " + sender.getName()); + this.usersConfig.set(target.getName() + ".votes", voteList + "," + sender.getName()); if (voteArray.length + 1 >= reqVotes) { // Enough votes received this.setApproved(target); return true; } } this.saveUsersConfig(); return true; } } + else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) { + Player target = getServer().getPlayer(args[0]); + if (target == null) { + // Player not online + sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); + return false; + } + String voteList = this.usersConfig.getString(target.getName() + ".votes", null); + if (voteList == null) { + sender.sendMessage(target.getDisplayName() + ChatColor.GOLD + " has not received any votes."); + } + else { + sender.sendMessage(target.getDisplayName() + ChatColor.GOLD + " has received votes from:"); + String[] voteArray = voteList.split(","); + for (String vote : voteArray) { + sender.sendMessage(ChatColor.GOLD + " " + vote); + } + } + return true; + } return false; } public void setApproved(Player target) { PermissionAttachment attachment = target.addAttachment(plugin); attachment.setPermission("greylistvote.approved", true); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " has been greylisted!"); } else { chatPlayer.sendMessage("You have been greylisted! Go forth and buildify!"); } } } public void loadUsersConfig() { if (this.usersFile == null) { this.usersFile = new File(getDataFolder(),"users.yml"); } this.usersConfig = YamlConfiguration.loadConfiguration(this.usersFile); } public FileConfiguration getUsersConfig() { if (this.usersConfig == null) { this.loadUsersConfig(); } return this.usersConfig; } public void saveUsersConfig() { if (this.usersConfig == null || this.usersFile == null) { return; } try { this.usersConfig.save(this.usersFile); } catch (IOException ex) { this.logger.log(Level.SEVERE, "Could not save " + this.usersFile, ex ); } } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("greylist")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getPlayer(args[0]); if (target == null) { // Player not online sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } if (!(sender instanceof Player)) { // Voter is the console sender.sendMessage(ChatColor.RED + "Sorry! The console can't vote!"); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } if (target.hasPermission("greylistvote.approved")) { // Target already approved sender.sendMessage(ChatColor.WHITE + target.getName() + ChatColor.RED + " has already been approved!"); return true; } int reqVotes = this.config.getInt("required_votes"); String voteList = this.usersConfig.getString(target + ".votes", null); if (voteList == null) { // No votes received for this target player if (reqVotes <= 1) { // Enough votes received this.setApproved(target); return true; } this.usersConfig.set(target.getName() + ".votes", sender.getName()); } else { // Target has votes already String[] voteArray = voteList.split(","); boolean found = false; for (String vote : voteArray) { if (vote == sender.getName()) { found = true; } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } sender.sendMessage(ChatColor.GOLD + "Your greylist vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be greylisted!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be greylisted!"); } } this.usersConfig.set(target.getName() + ".votes", voteList + ", " + sender.getName()); if (voteArray.length + 1 >= reqVotes) { // Enough votes received this.setApproved(target); return true; } } this.saveUsersConfig(); return true; } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getPlayer(args[0]); if (target == null) { // Player not online sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } if (!(sender instanceof Player)) { // Voter is the console sender.sendMessage(ChatColor.RED + "Sorry! The console can't vote!"); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } if (target.hasPermission("greylistvote.approved")) { // Target already approved sender.sendMessage(ChatColor.WHITE + target.getName() + ChatColor.RED + " has already been approved!"); return true; } int reqVotes = this.config.getInt("required_votes"); String voteList = this.usersConfig.getString(target.getName() + ".votes", null); if (voteList == null) { // No votes received for this target player if (reqVotes <= 1) { // Enough votes received this.setApproved(target); return true; } this.usersConfig.set(target.getName() + ".votes", sender.getName()); } else { // Target has votes already String[] voteArray = voteList.split(","); boolean found = false; for (String vote : voteArray) { if (vote == sender.getName()) { found = true; } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } sender.sendMessage(ChatColor.GOLD + "Your greylist vote for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " has been accepted!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + " to be greylisted!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " voted for you to be greylisted!"); } } this.usersConfig.set(target.getName() + ".votes", voteList + "," + sender.getName()); if (voteArray.length + 1 >= reqVotes) { // Enough votes received this.setApproved(target); return true; } } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) { Player target = getServer().getPlayer(args[0]); if (target == null) { // Player not online sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + " not found or not online!"); return false; } String voteList = this.usersConfig.getString(target.getName() + ".votes", null); if (voteList == null) { sender.sendMessage(target.getDisplayName() + ChatColor.GOLD + " has not received any votes."); } else { sender.sendMessage(target.getDisplayName() + ChatColor.GOLD + " has received votes from:"); String[] voteArray = voteList.split(","); for (String vote : voteArray) { sender.sendMessage(ChatColor.GOLD + " " + vote); } } return true; } return false; }
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.edit/src/org/wso2/developerstudio/eclipse/esb/provider/ApiResourceItemProvider.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.edit/src/org/wso2/developerstudio/eclipse/esb/provider/ApiResourceItemProvider.java index 90a02a4a7..7a827e6c8 100755 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.edit/src/org/wso2/developerstudio/eclipse/esb/provider/ApiResourceItemProvider.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.edit/src/org/wso2/developerstudio/eclipse/esb/provider/ApiResourceItemProvider.java @@ -1,386 +1,386 @@ /** * Copyright 2009-2010 WSO2, Inc. (http://wso2.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.esb.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; import org.wso2.developerstudio.eclipse.esb.ApiResource; import org.wso2.developerstudio.eclipse.esb.ApiResourceUrlStyle; import org.wso2.developerstudio.eclipse.esb.EsbFactory; import org.wso2.developerstudio.eclipse.esb.EsbPackage; import org.wso2.developerstudio.eclipse.esb.ModelObjectState; /** * This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.esb.ApiResource} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ApiResourceItemProvider extends ModelObjectItemProvider implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ApiResourceItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { ApiResource apiResource = (ApiResource) object; if (itemPropertyDescriptors != null) { itemPropertyDescriptors.clear(); } super.getPropertyDescriptors(object); addUrlStylePropertyDescriptor(object); if(apiResource.getUrlStyle().equals(ApiResourceUrlStyle.URI_TEMPLATE)){ addUriTemplatePropertyDescriptor(object); - } else if (apiResource.getUrlStyle().equals(ApiResourceUrlStyle.URI_TEMPLATE)){ + } else if (apiResource.getUrlStyle().equals(ApiResourceUrlStyle.URL_MAPPING)){ addUrlMappingPropertyDescriptor(object); } addAllowGetPropertyDescriptor(object); addAllowPostPropertyDescriptor(object); addAllowPutPropertyDescriptor(object); addAllowDeletePropertyDescriptor(object); addAllowOptionsPropertyDescriptor(object); return itemPropertyDescriptors; } /** * This adds a property descriptor for the Url Style feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ protected void addUrlStylePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ApiResource_urlStyle_feature"), getString("_UI_ApiResource_urlStyle_description"), EsbPackage.Literals.API_RESOURCE__URL_STYLE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Uri Template feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ protected void addUriTemplatePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ApiResource_uriTemplate_feature"), getString("_UI_PropertyDescriptor_description", "_UI_ApiResource_uriTemplate_feature", "_UI_ApiResource_type"), EsbPackage.Literals.API_RESOURCE__URI_TEMPLATE, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Url Mapping feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ protected void addUrlMappingPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ApiResource_urlMapping_feature"), getString("_UI_PropertyDescriptor_description", "_UI_ApiResource_urlMapping_feature", "_UI_ApiResource_type"), EsbPackage.Literals.API_RESOURCE__URL_MAPPING, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, "Basic", null)); } /** * This adds a property descriptor for the Allow Get feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addAllowGetPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ApiResource_allowGet_feature"), getString("_UI_ApiResource_allowGet_description"), EsbPackage.Literals.API_RESOURCE__ALLOW_GET, true, false, false, ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE, getString("_UI_MethodsPropertyCategory"), null)); } /** * This adds a property descriptor for the Allow Post feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addAllowPostPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ApiResource_allowPost_feature"), getString("_UI_ApiResource_allowPost_description"), EsbPackage.Literals.API_RESOURCE__ALLOW_POST, true, false, false, ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE, getString("_UI_MethodsPropertyCategory"), null)); } /** * This adds a property descriptor for the Allow Put feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addAllowPutPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ApiResource_allowPut_feature"), getString("_UI_ApiResource_allowPut_description"), EsbPackage.Literals.API_RESOURCE__ALLOW_PUT, true, false, false, ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE, getString("_UI_MethodsPropertyCategory"), null)); } /** * This adds a property descriptor for the Allow Delete feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addAllowDeletePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ApiResource_allowDelete_feature"), getString("_UI_ApiResource_allowDelete_description"), EsbPackage.Literals.API_RESOURCE__ALLOW_DELETE, true, false, false, ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE, getString("_UI_MethodsPropertyCategory"), null)); } /** * This adds a property descriptor for the Allow Options feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addAllowOptionsPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_ApiResource_allowOptions_feature"), getString("_UI_ApiResource_allowOptions_description"), EsbPackage.Literals.API_RESOURCE__ALLOW_OPTIONS, true, false, false, ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE, getString("_UI_MethodsPropertyCategory"), null)); } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(EsbPackage.Literals.API_RESOURCE__IN_SEQUENCE_CONFIGURATION); childrenFeatures.add(EsbPackage.Literals.API_RESOURCE__OUT_SEQUENCE_CONFIGURATION); childrenFeatures.add(EsbPackage.Literals.API_RESOURCE__FAULT_SEQUENCE_CONFIGURATION); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns ApiResource.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/ApiResource")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ @Override public String getText(Object object) { return getString("_UI_ApiResource_type"); } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(ApiResource.class)) { case EsbPackage.API_RESOURCE__URL_STYLE: case EsbPackage.API_RESOURCE__URI_TEMPLATE: case EsbPackage.API_RESOURCE__URL_MAPPING: case EsbPackage.API_RESOURCE__ALLOW_GET: case EsbPackage.API_RESOURCE__ALLOW_POST: case EsbPackage.API_RESOURCE__ALLOW_PUT: case EsbPackage.API_RESOURCE__ALLOW_DELETE: case EsbPackage.API_RESOURCE__ALLOW_OPTIONS: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; case EsbPackage.API_RESOURCE__IN_SEQUENCE_CONFIGURATION: case EsbPackage.API_RESOURCE__OUT_SEQUENCE_CONFIGURATION: case EsbPackage.API_RESOURCE__FAULT_SEQUENCE_CONFIGURATION: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.API_RESOURCE__IN_SEQUENCE_CONFIGURATION, EsbFactory.eINSTANCE.createApiInSequenceConfiguration())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.API_RESOURCE__OUT_SEQUENCE_CONFIGURATION, EsbFactory.eINSTANCE.createApiOutSequenceConfiguration())); newChildDescriptors.add (createChildParameter (EsbPackage.Literals.API_RESOURCE__FAULT_SEQUENCE_CONFIGURATION, EsbFactory.eINSTANCE.createApiFaultSequenceConfiguration())); } }
true
true
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { ApiResource apiResource = (ApiResource) object; if (itemPropertyDescriptors != null) { itemPropertyDescriptors.clear(); } super.getPropertyDescriptors(object); addUrlStylePropertyDescriptor(object); if(apiResource.getUrlStyle().equals(ApiResourceUrlStyle.URI_TEMPLATE)){ addUriTemplatePropertyDescriptor(object); } else if (apiResource.getUrlStyle().equals(ApiResourceUrlStyle.URI_TEMPLATE)){ addUrlMappingPropertyDescriptor(object); } addAllowGetPropertyDescriptor(object); addAllowPostPropertyDescriptor(object); addAllowPutPropertyDescriptor(object); addAllowDeletePropertyDescriptor(object); addAllowOptionsPropertyDescriptor(object); return itemPropertyDescriptors; }
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { ApiResource apiResource = (ApiResource) object; if (itemPropertyDescriptors != null) { itemPropertyDescriptors.clear(); } super.getPropertyDescriptors(object); addUrlStylePropertyDescriptor(object); if(apiResource.getUrlStyle().equals(ApiResourceUrlStyle.URI_TEMPLATE)){ addUriTemplatePropertyDescriptor(object); } else if (apiResource.getUrlStyle().equals(ApiResourceUrlStyle.URL_MAPPING)){ addUrlMappingPropertyDescriptor(object); } addAllowGetPropertyDescriptor(object); addAllowPostPropertyDescriptor(object); addAllowPutPropertyDescriptor(object); addAllowDeletePropertyDescriptor(object); addAllowOptionsPropertyDescriptor(object); return itemPropertyDescriptors; }
diff --git a/DSABinarySearchTree.java b/DSABinarySearchTree.java index 0b0aff8..bbb9f56 100644 --- a/DSABinarySearchTree.java +++ b/DSABinarySearchTree.java @@ -1,132 +1,132 @@ import java.util.*; public class DSABinarySearchTree< K extends Comparable<K>, V extends Comparable<V> > { private class TreeNode< K extends Comparable<K>, V extends Comparable<V> > { private K key; private V value; private TreeNode<K,V> left; private TreeNode<K,V> right; public TreeNode(K key, V value) { this.key = key; this.value = value; left = right = null; } } private TreeNode<K,V> root; public V find(K key) { TreeNode<K,V> cur = root; while (cur != null && !key.equals(cur.key)) { if (key.compareTo(cur.key) < 0) cur = cur.left; else cur = cur.right; } if (cur == null) throw new NoSuchElementException(); return cur.value; } public void insert(K key, V value) { TreeNode<K,V> cur = root, parent = null, child; while (cur != null) { int comp = key.compareTo(cur.key); parent = cur; if (comp == 0) throw new IllegalArgumentException(); else if (comp < 0) cur = cur.left; else cur = cur.right; } child = new TreeNode<K,V>(key, value); if (parent == null) root = child; - else if (key.compareTo(cur.key) < 0) + else if (key.compareTo(parent.key) < 0) parent.left = child; else parent.right = child; } public void delete(K key) { TreeNode<K,V> cur = root, parent = null; while (cur != null && !key.equals(cur.key)) { parent = cur; if (key.compareTo(cur.key) < 0) cur = cur.left; else cur = cur.right; } if (cur == null) throw new NoSuchElementException(); else if (cur.left == null || cur.right == null) deleteChineseNode(cur, parent); else deleteKurdishNode(cur, parent); } public void deleteChineseNode( TreeNode<K,V> cur, TreeNode<K,V> parent ) { TreeNode<K,V> promoted; if (cur.left == null) promoted = cur.left; else promoted = cur.right; if (parent == null) root = promoted; else if (parent.left == cur) parent.left = promoted; else parent.right = promoted; } public void deleteKurdishNode( TreeNode<K,V> cur, TreeNode<K,V> parent ) { TreeNode<K,V> successor, succParent; successor = cur.right; succParent = parent; while (successor.left != null) { succParent = successor; successor = successor.left; } deleteChineseNode(successor, parent); cur.key = successor.key; cur.value = successor.value; } public int height() { return height(root, 0); } public int height(TreeNode<K,V> start, int count) { int leftHeight, rightHeight; if (start == null) { return count; } else { leftHeight = height(start.left, count + 1); rightHeight = height(start.right, count + 1); if (leftHeight > rightHeight) return leftHeight; else return rightHeight; } } public static void main(String[] args) { DSABinarySearchTree<String, String> t = new DSABinarySearchTree<String, String>(); t.insert("[email protected]", "Delan Azabani"); t.insert("[email protected]", "Kye Russell"); t.insert("[email protected]", "Richard Stallman"); System.out.println(t.find("[email protected]")); System.out.println(t.find("[email protected]")); System.out.println(t.find("[email protected]")); try { System.out.println(t.find("[email protected]")); } catch (NoSuchElementException e) { System.out.println("[email protected] not found"); } } }
true
true
public void insert(K key, V value) { TreeNode<K,V> cur = root, parent = null, child; while (cur != null) { int comp = key.compareTo(cur.key); parent = cur; if (comp == 0) throw new IllegalArgumentException(); else if (comp < 0) cur = cur.left; else cur = cur.right; } child = new TreeNode<K,V>(key, value); if (parent == null) root = child; else if (key.compareTo(cur.key) < 0) parent.left = child; else parent.right = child; }
public void insert(K key, V value) { TreeNode<K,V> cur = root, parent = null, child; while (cur != null) { int comp = key.compareTo(cur.key); parent = cur; if (comp == 0) throw new IllegalArgumentException(); else if (comp < 0) cur = cur.left; else cur = cur.right; } child = new TreeNode<K,V>(key, value); if (parent == null) root = child; else if (key.compareTo(parent.key) < 0) parent.left = child; else parent.right = child; }
diff --git a/src/java/net/sf/picard/sam/MergeSamFiles.java b/src/java/net/sf/picard/sam/MergeSamFiles.java index cf5ee1c6..ac877152 100644 --- a/src/java/net/sf/picard/sam/MergeSamFiles.java +++ b/src/java/net/sf/picard/sam/MergeSamFiles.java @@ -1,225 +1,226 @@ /* * The MIT License * * Copyright (c) 2009 The Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.sf.picard.sam; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.Usage; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.io.IoUtil; import net.sf.picard.util.Log; import net.sf.picard.PicardException; import net.sf.samtools.*; /** * Reads a SAM or BAM file and combines the output to one file * * @author Tim Fennell */ public class MergeSamFiles extends CommandLineProgram { private static final Log log = Log.getInstance(MergeSamFiles.class); // Usage and parameters @Usage public String USAGE = "Merges multiple SAM/BAM files into one file.\n"; @Option(shortName="I", doc="SAM or BAM input file", minElements=1) public List<File> INPUT = new ArrayList<File>(); @Option(shortName="O", doc="SAM or BAM file to write merged result to") public File OUTPUT; @Option(shortName=StandardOptionDefinitions.SORT_ORDER_SHORT_NAME, doc="Sort order of output file", optional=true) public SAMFileHeader.SortOrder SORT_ORDER = SAMFileHeader.SortOrder.coordinate; @Option(doc="If true, assume that the input files are in the same sort order as the requested output sort order, even if their headers say otherwise.", shortName = StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME) public boolean ASSUME_SORTED = false; @Option(shortName="MSD", doc="Merge the seqeunce dictionaries", optional=true) public boolean MERGE_SEQUENCE_DICTIONARIES = false; @Option(doc="Option to enable a simple two-thread producer consumer version of the merge algorithm that " + "uses one thread to read and merge the records from the input files and another thread to encode, " + "compress and write to disk the output file. The threaded version uses about 20% more CPU and decreases " + "runtime by ~20% when writing out a compressed BAM file.") public boolean USE_THREADING = false; @Option(doc="Comment(s) to include in the merged output file's header.", optional=true, shortName="CO") public List<String> COMMENT = new ArrayList<String>(); private static final int PROGRESS_INTERVAL = 1000000; /** Required main method implementation. */ public static void main(final String[] argv) { System.exit(new MergeSamFiles().instanceMain(argv)); } /** Combines multiple SAM/BAM files into one. */ @Override protected int doWork() { boolean matchedSortOrders = true; // Open the files for reading and writing final List<SAMFileReader> readers = new ArrayList<SAMFileReader>(); final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); { SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory for (final File inFile : INPUT) { IoUtil.assertFileIsReadable(inFile); final SAMFileReader in = new SAMFileReader(inFile); readers.add(in); headers.add(in.getFileHeader()); // A slightly hackish attempt to keep memory consumption down when merging multiple files with // large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then // replace the duplicate copies with a single dictionary to reduce the memory footprint. if (dict == null) { dict = in.getFileHeader().getSequenceDictionary(); } else if (dict.equals(in.getFileHeader().getSequenceDictionary())) { in.getFileHeader().setSequenceDictionary(dict); } matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER; } } // If all the input sort orders match the output sort order then just merge them and // write on the fly, otherwise setup to merge and sort before writing out the final file IoUtil.assertFileIsWritable(OUTPUT); final boolean presorted; final SAMFileHeader.SortOrder headerMergerSortOrder; final boolean mergingSamRecordIteratorAssumeSorted; if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) { log.info("Input files are in same order as output so sorting to temp directory is not needed."); headerMergerSortOrder = SORT_ORDER; mergingSamRecordIteratorAssumeSorted = ASSUME_SORTED; presorted = true; } else { log.info("Sorting input files using temp directory " + TMP_DIR); headerMergerSortOrder = SAMFileHeader.SortOrder.unsorted; mergingSamRecordIteratorAssumeSorted = false; presorted = false; } final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(headerMergerSortOrder, headers, MERGE_SEQUENCE_DICTIONARIES); final MergingSamRecordIterator iterator = new MergingSamRecordIterator(headerMerger, readers, mergingSamRecordIteratorAssumeSorted); final SAMFileHeader header = headerMerger.getMergedHeader(); for (String comment : COMMENT) { header.addComment(comment); } + header.setSortOrder(SORT_ORDER); final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, presorted, OUTPUT); // Lastly loop through and write out the records if (USE_THREADING) { final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000); final AtomicBoolean producerSuccceeded = new AtomicBoolean(false); final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false); Runnable producer = new Runnable() { public void run() { try { while (iterator.hasNext()) { queue.put(iterator.next()); } producerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted reading SAMRecord to merge.", ie); } } }; Runnable consumer = new Runnable() { public void run() { try { long i = 0; SAMRecord rec = null; while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) { out.addAlignment(rec); if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed."); } consumerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted writing SAMRecord to output file.", ie); } } }; Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); try { consumerThread.join(); producerThread.join(); } catch (InterruptedException ie) { throw new PicardException("Interrupted while waiting for threads to finished writing.", ie); } if (!producerSuccceeded.get()) { throw new PicardException("Error reading or merging inputs."); } if (!consumerSuccceeded.get()) { throw new PicardException("Error writing output"); } } else { for (long numRecords = 1; iterator.hasNext(); ++numRecords) { final SAMRecord record = iterator.next(); out.addAlignment(record); if (numRecords % PROGRESS_INTERVAL == 0) { log.info(numRecords + " records read."); } } } log.info("Finished reading inputs."); out.close(); return 0; } @Override protected String[] customCommandLineValidation() { if (CREATE_INDEX && SORT_ORDER != SAMFileHeader.SortOrder.coordinate) { return new String[]{"Can't CREATE_INDEX unless SORT_ORDER is coordinate"}; } return null; } }
true
true
protected int doWork() { boolean matchedSortOrders = true; // Open the files for reading and writing final List<SAMFileReader> readers = new ArrayList<SAMFileReader>(); final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); { SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory for (final File inFile : INPUT) { IoUtil.assertFileIsReadable(inFile); final SAMFileReader in = new SAMFileReader(inFile); readers.add(in); headers.add(in.getFileHeader()); // A slightly hackish attempt to keep memory consumption down when merging multiple files with // large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then // replace the duplicate copies with a single dictionary to reduce the memory footprint. if (dict == null) { dict = in.getFileHeader().getSequenceDictionary(); } else if (dict.equals(in.getFileHeader().getSequenceDictionary())) { in.getFileHeader().setSequenceDictionary(dict); } matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER; } } // If all the input sort orders match the output sort order then just merge them and // write on the fly, otherwise setup to merge and sort before writing out the final file IoUtil.assertFileIsWritable(OUTPUT); final boolean presorted; final SAMFileHeader.SortOrder headerMergerSortOrder; final boolean mergingSamRecordIteratorAssumeSorted; if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) { log.info("Input files are in same order as output so sorting to temp directory is not needed."); headerMergerSortOrder = SORT_ORDER; mergingSamRecordIteratorAssumeSorted = ASSUME_SORTED; presorted = true; } else { log.info("Sorting input files using temp directory " + TMP_DIR); headerMergerSortOrder = SAMFileHeader.SortOrder.unsorted; mergingSamRecordIteratorAssumeSorted = false; presorted = false; } final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(headerMergerSortOrder, headers, MERGE_SEQUENCE_DICTIONARIES); final MergingSamRecordIterator iterator = new MergingSamRecordIterator(headerMerger, readers, mergingSamRecordIteratorAssumeSorted); final SAMFileHeader header = headerMerger.getMergedHeader(); for (String comment : COMMENT) { header.addComment(comment); } final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, presorted, OUTPUT); // Lastly loop through and write out the records if (USE_THREADING) { final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000); final AtomicBoolean producerSuccceeded = new AtomicBoolean(false); final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false); Runnable producer = new Runnable() { public void run() { try { while (iterator.hasNext()) { queue.put(iterator.next()); } producerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted reading SAMRecord to merge.", ie); } } }; Runnable consumer = new Runnable() { public void run() { try { long i = 0; SAMRecord rec = null; while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) { out.addAlignment(rec); if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed."); } consumerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted writing SAMRecord to output file.", ie); } } }; Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); try { consumerThread.join(); producerThread.join(); } catch (InterruptedException ie) { throw new PicardException("Interrupted while waiting for threads to finished writing.", ie); } if (!producerSuccceeded.get()) { throw new PicardException("Error reading or merging inputs."); } if (!consumerSuccceeded.get()) { throw new PicardException("Error writing output"); } } else { for (long numRecords = 1; iterator.hasNext(); ++numRecords) { final SAMRecord record = iterator.next(); out.addAlignment(record); if (numRecords % PROGRESS_INTERVAL == 0) { log.info(numRecords + " records read."); } } } log.info("Finished reading inputs."); out.close(); return 0; }
protected int doWork() { boolean matchedSortOrders = true; // Open the files for reading and writing final List<SAMFileReader> readers = new ArrayList<SAMFileReader>(); final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(); { SAMSequenceDictionary dict = null; // Used to try and reduce redundant SDs in memory for (final File inFile : INPUT) { IoUtil.assertFileIsReadable(inFile); final SAMFileReader in = new SAMFileReader(inFile); readers.add(in); headers.add(in.getFileHeader()); // A slightly hackish attempt to keep memory consumption down when merging multiple files with // large sequence dictionaries (10,000s of sequences). If the dictionaries are identical, then // replace the duplicate copies with a single dictionary to reduce the memory footprint. if (dict == null) { dict = in.getFileHeader().getSequenceDictionary(); } else if (dict.equals(in.getFileHeader().getSequenceDictionary())) { in.getFileHeader().setSequenceDictionary(dict); } matchedSortOrders = matchedSortOrders && in.getFileHeader().getSortOrder() == SORT_ORDER; } } // If all the input sort orders match the output sort order then just merge them and // write on the fly, otherwise setup to merge and sort before writing out the final file IoUtil.assertFileIsWritable(OUTPUT); final boolean presorted; final SAMFileHeader.SortOrder headerMergerSortOrder; final boolean mergingSamRecordIteratorAssumeSorted; if (matchedSortOrders || SORT_ORDER == SAMFileHeader.SortOrder.unsorted || ASSUME_SORTED) { log.info("Input files are in same order as output so sorting to temp directory is not needed."); headerMergerSortOrder = SORT_ORDER; mergingSamRecordIteratorAssumeSorted = ASSUME_SORTED; presorted = true; } else { log.info("Sorting input files using temp directory " + TMP_DIR); headerMergerSortOrder = SAMFileHeader.SortOrder.unsorted; mergingSamRecordIteratorAssumeSorted = false; presorted = false; } final SamFileHeaderMerger headerMerger = new SamFileHeaderMerger(headerMergerSortOrder, headers, MERGE_SEQUENCE_DICTIONARIES); final MergingSamRecordIterator iterator = new MergingSamRecordIterator(headerMerger, readers, mergingSamRecordIteratorAssumeSorted); final SAMFileHeader header = headerMerger.getMergedHeader(); for (String comment : COMMENT) { header.addComment(comment); } header.setSortOrder(SORT_ORDER); final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, presorted, OUTPUT); // Lastly loop through and write out the records if (USE_THREADING) { final BlockingQueue<SAMRecord> queue = new ArrayBlockingQueue<SAMRecord>(10000); final AtomicBoolean producerSuccceeded = new AtomicBoolean(false); final AtomicBoolean consumerSuccceeded = new AtomicBoolean(false); Runnable producer = new Runnable() { public void run() { try { while (iterator.hasNext()) { queue.put(iterator.next()); } producerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted reading SAMRecord to merge.", ie); } } }; Runnable consumer = new Runnable() { public void run() { try { long i = 0; SAMRecord rec = null; while ((rec = queue.poll(15, TimeUnit.SECONDS)) != null) { out.addAlignment(rec); if (++i % PROGRESS_INTERVAL == 0) log.info(i + " records processed."); } consumerSuccceeded.set(true); } catch (InterruptedException ie) { throw new PicardException("Interrupted writing SAMRecord to output file.", ie); } } }; Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); try { consumerThread.join(); producerThread.join(); } catch (InterruptedException ie) { throw new PicardException("Interrupted while waiting for threads to finished writing.", ie); } if (!producerSuccceeded.get()) { throw new PicardException("Error reading or merging inputs."); } if (!consumerSuccceeded.get()) { throw new PicardException("Error writing output"); } } else { for (long numRecords = 1; iterator.hasNext(); ++numRecords) { final SAMRecord record = iterator.next(); out.addAlignment(record); if (numRecords % PROGRESS_INTERVAL == 0) { log.info(numRecords + " records read."); } } } log.info("Finished reading inputs."); out.close(); return 0; }
diff --git a/tests/org.dresdenocl.debug.test/src/org/dresdenocl/debug/test/AbstractDebuggerTest.java b/tests/org.dresdenocl.debug.test/src/org/dresdenocl/debug/test/AbstractDebuggerTest.java index 8d132b78f..50ab43913 100644 --- a/tests/org.dresdenocl.debug.test/src/org/dresdenocl/debug/test/AbstractDebuggerTest.java +++ b/tests/org.dresdenocl.debug.test/src/org/dresdenocl/debug/test/AbstractDebuggerTest.java @@ -1,548 +1,549 @@ package org.dresdenocl.debug.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.Assert; import org.dresdenocl.debug.OclDebugger; import org.dresdenocl.facade.Ocl2ForEclipseFacade; import org.dresdenocl.model.IModel; import org.dresdenocl.model.ModelAccessException; import org.dresdenocl.modelbus.ModelBusPlugin; import org.dresdenocl.modelinstance.IModelInstance; import org.dresdenocl.modelinstancetype.types.IModelInstanceObject; import org.dresdenocl.parser.ParseException; import org.dresdenocl.pivotmodel.Constraint; import org.dresdenocl.pivotmodel.Type; import org.dresdenocl.testsuite._abstract.AbstractDresdenOclTest; import org.junit.After; import org.junit.Before; public abstract class AbstractDebuggerTest extends AbstractDresdenOclTest { /** Declares possible events to be happened during debugging. */ protected enum DebugEvent { CONSTRAINT_INTERPRETED, STARTED, SUSPENDED, RESUMED, TERMINATED } /** Declared possible debug steps to be executed by the debugger. */ protected enum DebugStep { RESUME, TERMINATE, STEP_INTO, STEP_OVER, STEP_RETURN } protected static final String MODEL_PATH = "bin/resource/package01/TestModel.class"; protected static final String MODEL_INSTANCE_PATH = "bin/resource/package01/TestModelInstance.class"; protected static final String RESOURCE01_PATH = "resources/resource01.ocl"; /** The last lines received as an event from the {@link OclDebugger}. */ protected static volatile List<String> lastReceivedLines = new LinkedList<String>(); protected static IModel modelUnderTest; protected static IModelInstance modelInstanceUnderTest; /** Socket the {@link OclDebugger} is sending events to. */ protected static Socket socket; /** * Thread used to listen for events on the {@link OclDebugger}'s * {@link Socket}. */ protected static SocketListener socketListener; protected static OclDebugger debugger; public static void setUp() throws Exception { AbstractDresdenOclTest.setUp(); } @Before public void before() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // assertEquals(null, ModelBusPlugin.getModelRegistry().getActiveModel()); } @After public void after() { debugStepAndWaitFor(DebugStep.TERMINATE, DebugEvent.TERMINATED, debugger); try { debugger.shutdown(); } catch (Exception e) { // drop it } assertTrue(ModelBusPlugin.getModelInstanceRegistry().removeModelInstance( modelInstanceUnderTest)); assertTrue(ModelBusPlugin.getModelRegistry().removeModel(modelUnderTest)); modelUnderTest = null; modelInstanceUnderTest = null; socketListener.terminate = true; debugger = null; lastReceivedLines = new LinkedList<String>(); if (null != socket) { try { socket.close(); } catch (IOException e) { /* Not important. */ } } // no else. } protected static IModel getModel(String modelPath) throws ModelAccessException { IModel result; File modelFile; try { modelFile = AbstractDebuggerTest.getFile(modelPath, DebugTestPlugin.PLUGIN_ID); } catch (IOException e) { throw new ModelAccessException(e.getMessage(), e); } assertNotNull(modelFile); result = Ocl2ForEclipseFacade.getModel(modelFile, Ocl2ForEclipseFacade.JAVA_META_MODEL); return result; } protected static IModelInstance getModelInstance(String modelInstancePath) throws ModelAccessException { IModelInstance result; File modelInstanceFile; try { modelInstanceFile = AbstractDebuggerTest.getFile(modelInstancePath, DebugTestPlugin.PLUGIN_ID); } catch (IOException e) { throw new ModelAccessException(e.getMessage(), e); } assertNotNull(modelInstanceFile); result = Ocl2ForEclipseFacade.getModelInstance(modelInstanceFile, modelUnderTest, Ocl2ForEclipseFacade.JAVA_MODEL_INSTANCE_TYPE); return result; } protected static Set<IModelInstanceObject> getModelInstanceObjects( String modelInstancePath, String... modelObjects) throws ModelAccessException { modelInstanceUnderTest = getModelInstance(modelInstancePath); assertNotNull(modelInstanceUnderTest); ModelBusPlugin.getModelInstanceRegistry().addModelInstance( modelInstanceUnderTest); ModelBusPlugin.getModelInstanceRegistry().setActiveModelInstance( modelUnderTest, modelInstanceUnderTest); // check the parameter assertTrue(modelObjects != null && modelObjects.length >= 1); // get the types Type objectType = modelUnderTest.findType(Arrays.asList(modelObjects)); assertNotNull("cannot find type", objectType); // find the objects Set<IModelInstanceObject> result = modelInstanceUnderTest.getAllInstances(objectType); assertNotNull("could not get all instances", result); return result; } protected static List<Constraint> getConstraints(String modelPath, String resourcePath) throws ModelAccessException, ParseException { modelUnderTest = getModel(modelPath); assertNotNull("could not get model", modelUnderTest); ModelBusPlugin.getModelRegistry().addModel(modelUnderTest); ModelBusPlugin.getModelRegistry().setActiveModel(modelUnderTest); List<Constraint> result; File resourceFile; try { resourceFile = AbstractDebuggerTest.getFile(resourcePath, DebugTestPlugin.PLUGIN_ID); } catch (IOException e) { throw new ModelAccessException(e.getMessage(), e); } assertNotNull("resource file is null", resourceFile); assertTrue("Cannot read the resource file", resourceFile.canRead()); result = Ocl2ForEclipseFacade.parseConstraints(resourceFile, modelUnderTest, true); assertNotNull("parse result is null", result); assertTrue("parse result is empty", result.size() >= 1); return result; } protected 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; } /** * Helper method asserting that the {@link OclDebugger} is at the right line. * * @param currentLine * The line to be asserted. * @param debugger * The {@link OclDebugger}. */ protected void assertCurrentLine(int currentLine, OclDebugger debugger) { assertEquals("The OclDebugger should bet at line " + currentLine + ".", currentLine, debugger.getCurrentLine()); } /** * Helper method asserting that the last entry of the call stack has the right * name. * * @param name * The name to be asserted. * @param debugger * The {@link OclDebugger}. */ protected void assertStackName(String name, OclDebugger debugger) { assertNotNull("The call stack should not be empty.", debugger.getStack()); assertFalse("The call stack should not be empty.", debugger.getStack().length == 0); String[] debuggerStack = debugger.getStack(); String callStackName = debuggerStack[debuggerStack.length - 1]; assertEquals( "The name of the last entry on the call stack should start with '" + name + "'", name, callStackName.substring(0, callStackName.indexOf(","))); } /** * Helper method asserting the size of the call stack. * * @param stackSize * The size of the stack. * @param debugger * The {@link OclDebugger}. */ protected void assertStackSize(int stackSize, OclDebugger debugger) { assertEquals("The Stack should have the size " + stackSize + ".", stackSize, debugger.getStack().length); } /** * Helper method asserting that a variable with a given name is visible in the * current stack frame. * * @param name * The name of the variable expected to be visible. * @param debugger * The {@link OclDebugger} to assert. */ protected void assertVariableExist(String name, OclDebugger debugger) { assertTrue("The variable '" + name + "' should be visible for the current stack.", getVariablesFromStackFrame(debugger).keySet().contains(name)); } /** * Helper method asserting the count of variables visible in the current stack * frame. * * @param count * The expected count of variables. * @param debugger * The {@link OclDebugger} to assert. */ protected void assertVariableNumber(int count, OclDebugger debugger) { assertEquals( "The expected number of variables for the current stack frame was wrong.", count, getVariablesFromStackFrame(debugger).size()); } /** * Helper method executing a given {@link DebugStep} and waiting for a given * {@link DebugEvent} afterwards. Fails, if the {@link DebugEvent} will not * happen within 10 seconds. * * @param step * The {@link DebugStep} to be executed. * @param event * The {@link DebugEvent} to be wait for. * @param debugger * The {@link OclDebugger}. */ protected void debugStepAndWaitFor(DebugStep step, DebugEvent event, OclDebugger debugger) { debugStepAndWaitFor(step, event, debugger, 10000); } /** * Helper method executing a given {@link DebugStep} and waiting for a given * {@link DebugEvent} afterwards. Fails, if the {@link DebugEvent} will not * happen within the specified timeout. * * @param step * The {@link DebugStep} to be executed. * @param event * The {@link DebugEvent} to be wait for. * @param debugger * The {@link OclDebugger}. * @param timeout * The timeout. */ protected void debugStepAndWaitFor(DebugStep step, DebugEvent event, OclDebugger debugger, long timeout) { lastReceivedLines.clear(); switch (step) { case RESUME: debugger.resume(); break; case TERMINATE: debugger.terminate(); break; case STEP_INTO: debugger.stepInto(); break; case STEP_OVER: debugger.stepOver(); break; case STEP_RETURN: debugger.stepReturn(); break; default: Assert.fail("Unknown debugstep: " + step.name()); } /* * try { Thread.sleep(100); } catch (InterruptedException e) { // Not * important. } */ waitForEvent(event, timeout); } /** * Helper method creating an {@link OclDebugger} for a given OCL resource. * * Besides, a {@link SocketListener} will be created and started that puts the * last received event into the lastReceivedLine field. * * @param oclResource * Path leading to the OCL file used for this {@link OclDebugger} * relative to the root directory of this test plugin. * @return The created {@link OclDebugger} * @throws Exception */ protected OclDebugger generateDebugger(String oclResource) throws Exception { synchronized (System.out) { System.out.println("== generateDebugger =="); + System.out.println(oclResource); } final String[] modelObjects = { "TestClass" }; final List<Constraint> constraints; final Set<IModelInstanceObject> imio; final int eventPort = findFreePort(); constraints = getConstraints(MODEL_PATH, oclResource); imio = getModelInstanceObjects(MODEL_INSTANCE_PATH, modelObjects); assertNotNull("There is no active model set.", ModelBusPlugin .getModelRegistry().getActiveModel()); assertNotNull( "There is no active model instance for the model under test.", ModelBusPlugin.getModelInstanceRegistry().getActiveModelInstance( modelUnderTest)); debugger = new OclDebugger(modelInstanceUnderTest); debugger.setDebugMode(true); new Thread(new Runnable() { @Override public void run() { debugger.setEventPort(eventPort); debugger.interpretConstraint(constraints.get(0), imio.iterator().next()); } }).start(); // Thread.sleep(1000); socket = new Socket("localhost", eventPort); socketListener = new SocketListener(); socketListener.start(); return debugger; } /** * Helper method returning all variables for the last stack frame as a Map. * * @param debugger * The {@link OclDebugger} for which the variables shall be returned. * @return The variables as a {@link Map} (keys are names as {@link String} * s). */ protected Map<String, Object> getVariablesFromStackFrame(OclDebugger debugger) { int frameId = debugger.getStack().length; if (frameId > 0) { frameId = frameId - 1; return debugger .getFrameVariables(debugger.getStack()[frameId].split(",")[1]); } else return Collections.emptyMap(); } /** * Helper method that waits till a given event will be sent by the * {@link OclDebugger} with a timeout of 10 seconds. * * @param event * The {@link DebugEvent} to be waited for. */ protected void waitForEvent(DebugEvent event) { waitForEvent(event, 10000); } /** * Helper method that waits till a given event will be sent by the * {@link OclDebugger}. * * @param event * The {@link DebugEvent} to be waited for. * @param timeout * The maximum amount of time to wait for the {@link DebugEvent} . * Fails otherwise. */ protected void waitForEvent(DebugEvent event, long timeout) { long currentMillis = System.currentTimeMillis(); while (!lastReceivedLines.contains(event.name() + ":")) { try { Thread.sleep(100); if (currentMillis + timeout < System.currentTimeMillis()) Assert.fail("Expected DebugEvent " + event.name() + " did not happen within specified timeout."); // no else. } catch (InterruptedException e) { /* Not that important. */ } } } /** * Helper {@link Thread} listening to the {@link Socket} of the * {@link OclDebugger} for events. * * @author Claas Wilke */ private class SocketListener extends Thread { /** * If this {@link SocketListener} shall terminate, set this to * <code>true</code>. */ public boolean terminate = false; /** * Creates a new {@link SocketListener}. */ public SocketListener() { lastReceivedLines.clear(); } /* * (non-Javadoc) * @see java.lang.Thread#run() */ @Override public void run() { BufferedReader in; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String inputLine; while (!terminate && (inputLine = in.readLine()) != null) { lastReceivedLines.add(inputLine); } } catch (IOException e) { if (!terminate) Assert.fail("Could not read from socket of debugger: " + e.getMessage()); // no else. } } } }
true
true
protected OclDebugger generateDebugger(String oclResource) throws Exception { synchronized (System.out) { System.out.println("== generateDebugger =="); } final String[] modelObjects = { "TestClass" }; final List<Constraint> constraints; final Set<IModelInstanceObject> imio; final int eventPort = findFreePort(); constraints = getConstraints(MODEL_PATH, oclResource); imio = getModelInstanceObjects(MODEL_INSTANCE_PATH, modelObjects); assertNotNull("There is no active model set.", ModelBusPlugin .getModelRegistry().getActiveModel()); assertNotNull( "There is no active model instance for the model under test.", ModelBusPlugin.getModelInstanceRegistry().getActiveModelInstance( modelUnderTest)); debugger = new OclDebugger(modelInstanceUnderTest); debugger.setDebugMode(true); new Thread(new Runnable() { @Override public void run() { debugger.setEventPort(eventPort); debugger.interpretConstraint(constraints.get(0), imio.iterator().next()); } }).start(); // Thread.sleep(1000); socket = new Socket("localhost", eventPort); socketListener = new SocketListener(); socketListener.start(); return debugger; }
protected OclDebugger generateDebugger(String oclResource) throws Exception { synchronized (System.out) { System.out.println("== generateDebugger =="); System.out.println(oclResource); } final String[] modelObjects = { "TestClass" }; final List<Constraint> constraints; final Set<IModelInstanceObject> imio; final int eventPort = findFreePort(); constraints = getConstraints(MODEL_PATH, oclResource); imio = getModelInstanceObjects(MODEL_INSTANCE_PATH, modelObjects); assertNotNull("There is no active model set.", ModelBusPlugin .getModelRegistry().getActiveModel()); assertNotNull( "There is no active model instance for the model under test.", ModelBusPlugin.getModelInstanceRegistry().getActiveModelInstance( modelUnderTest)); debugger = new OclDebugger(modelInstanceUnderTest); debugger.setDebugMode(true); new Thread(new Runnable() { @Override public void run() { debugger.setEventPort(eventPort); debugger.interpretConstraint(constraints.get(0), imio.iterator().next()); } }).start(); // Thread.sleep(1000); socket = new Socket("localhost", eventPort); socketListener = new SocketListener(); socketListener.start(); return debugger; }
diff --git a/src/com/dmdirc/addons/ui_swing/dialogs/channelsetting/TopicLabel.java b/src/com/dmdirc/addons/ui_swing/dialogs/channelsetting/TopicLabel.java index 62ab24988..2aa819ca6 100644 --- a/src/com/dmdirc/addons/ui_swing/dialogs/channelsetting/TopicLabel.java +++ b/src/com/dmdirc/addons/ui_swing/dialogs/channelsetting/TopicLabel.java @@ -1,84 +1,91 @@ /* * * Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.addons.ui_swing.dialogs.channelsetting; import com.dmdirc.Topic; import com.dmdirc.addons.ui_swing.components.text.OldTextLabel; import java.util.Date; import javax.swing.JPanel; import javax.swing.JSeparator; import net.miginfocom.swing.MigLayout; /** * Topic Label for use in the topic history panel. */ public class TopicLabel extends JPanel { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** Topic this label represents. */ private final Topic topic; /** * Instantiates a new topic label based on the specified topic. * * @param topic Specified topic */ public TopicLabel(final Topic topic) { this.topic = topic; init(); } private void init() { setLayout(new MigLayout("fillx, ins 0, debug", "[]0[]", "[]0[]")); - OldTextLabel label = new OldTextLabel(topic.getTopic()); - add(label, "wmax 450, growy, pushy, wrap, gapleft 5, gapleft 5"); + OldTextLabel label; + if (!topic.getTopic().isEmpty()) { + label = new OldTextLabel(topic.getTopic()); + add(label, "wmax 450, growy, pushy, wrap, gapleft 5, gapleft 5"); + } - label = new OldTextLabel("Topic set by " + topic.getClient()); + if (topic.getTopic().isEmpty()) { + label = new OldTextLabel("Topic unset by " + topic.getClient()); + } else { + label = new OldTextLabel("Topic set by " + topic.getClient()); + } add(label, "wmax 450, growy, pushy, wrap, gapleft 5, pad 0"); label = new OldTextLabel("on " + new Date(topic.getTime() * 1000).toString()); add(label, "wmax 450, growy, pushy, wrap, gapleft 5, pad 0"); add(new JSeparator(), "newline, span, growx, pushx"); } /** * Returns the topic for this label. * * @return Topic */ public Topic getTopic() { return topic; } }
false
true
private void init() { setLayout(new MigLayout("fillx, ins 0, debug", "[]0[]", "[]0[]")); OldTextLabel label = new OldTextLabel(topic.getTopic()); add(label, "wmax 450, growy, pushy, wrap, gapleft 5, gapleft 5"); label = new OldTextLabel("Topic set by " + topic.getClient()); add(label, "wmax 450, growy, pushy, wrap, gapleft 5, pad 0"); label = new OldTextLabel("on " + new Date(topic.getTime() * 1000).toString()); add(label, "wmax 450, growy, pushy, wrap, gapleft 5, pad 0"); add(new JSeparator(), "newline, span, growx, pushx"); }
private void init() { setLayout(new MigLayout("fillx, ins 0, debug", "[]0[]", "[]0[]")); OldTextLabel label; if (!topic.getTopic().isEmpty()) { label = new OldTextLabel(topic.getTopic()); add(label, "wmax 450, growy, pushy, wrap, gapleft 5, gapleft 5"); } if (topic.getTopic().isEmpty()) { label = new OldTextLabel("Topic unset by " + topic.getClient()); } else { label = new OldTextLabel("Topic set by " + topic.getClient()); } add(label, "wmax 450, growy, pushy, wrap, gapleft 5, pad 0"); label = new OldTextLabel("on " + new Date(topic.getTime() * 1000).toString()); add(label, "wmax 450, growy, pushy, wrap, gapleft 5, pad 0"); add(new JSeparator(), "newline, span, growx, pushx"); }
diff --git a/src/gui/AboutDialog.java b/src/gui/AboutDialog.java index f1a69b9f..beed37f3 100644 --- a/src/gui/AboutDialog.java +++ b/src/gui/AboutDialog.java @@ -1,118 +1,118 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package gui; import java.awt.*; import java.awt.event.*; import java.net.URL; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import version.*; import utils.GuiUtils; import utils.Platform; //---------------------------------------------------------------------------- public class AboutDialog extends JOptionPane { public static void show(Component parent, String name, String version, String protocolVersion, String command) { AboutDialog aboutDialog = new AboutDialog(name, version, protocolVersion, command); JDialog dialog = aboutDialog.createDialog(parent, "About"); dialog.setVisible(true); dialog.dispose(); } private AboutDialog(String name, String version, String protocolVersion, String command) { JTabbedPane tabbedPane = new JTabbedPane(); ClassLoader classLoader = getClass().getClassLoader(); URL imageUrl = classLoader.getResource("images/project-support.png"); String projectUrl = "http://gogui.sourceforge.net"; String supportUrl = "http://sourceforge.net/donate/index.php?group_id=59117"; JPanel goguiPanel = createPanel("<p align=\"center\"><b>GoGui " + Version.get() + "</b></p>" + "<p align=\"center\">" + "Graphical interface to Go programs<br>" + "&copy; 2003-2004, Markus Enzenberger" + "</p>" + "<p align=\"center\">" + "<tt><a href=\"" + projectUrl + "\">" + projectUrl + "</a></tt>" + "</p>" + "<p align=\"center\">" + "<a href=\"" + supportUrl + "\">" + "<img src=\"" + imageUrl + "\" border=\"0\"></a>" + "</p>"); tabbedPane.add("GoGui", goguiPanel); tabbedPane.setMnemonicAt(0, KeyEvent.VK_G); boolean isProgramAvailable = (name != null && ! name.equals("")); JPanel programPanel; if (isProgramAvailable) { String fullName = name; - if (version != null || ! version.equals("")) + if (version != null && ! version.equals("")) fullName = fullName + " " + version; int width = GuiUtils.getDefaultMonoFontSize() * 25; programPanel = createPanel("<p align=\"center\"><b>" + fullName + "</b></p>" + "<p align=\"center\" width=\"" + width + "\">" + "Command: <tt>" + command + "</tt></p>" + "<p align=\"center\">" + "GTP protocol version " + protocolVersion + "</p>"); } else programPanel = new JPanel(); tabbedPane.add("Go Program", programPanel); tabbedPane.setMnemonicAt(1, KeyEvent.VK_P); if (! isProgramAvailable) tabbedPane.setEnabledAt(1, false); setMessage(tabbedPane); setOptionType(DEFAULT_OPTION); } private static JPanel createPanel(String text) { JPanel panel = new JPanel(new GridLayout(1, 1)); JEditorPane editorPane = new JEditorPane(); editorPane.setBorder(GuiUtils.createEmptyBorder()); editorPane.setEditable(false); panel.add(editorPane); JLabel dummyLabel = new JLabel(); editorPane.setBackground(dummyLabel.getBackground()); EditorKit editorKit = JEditorPane.createEditorKitForContentType("text/html"); editorPane.setEditorKit(editorKit); editorPane.setText(text); editorPane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent event) { HyperlinkEvent.EventType type = event.getEventType(); if (type == HyperlinkEvent.EventType.ACTIVATED) { URL url = event.getURL(); if (! Platform.openInExternalBrowser(url)) SimpleDialogs.showError(null, "Could not open URL" + " in external browser"); } } }); return panel; } } //----------------------------------------------------------------------------
true
true
private AboutDialog(String name, String version, String protocolVersion, String command) { JTabbedPane tabbedPane = new JTabbedPane(); ClassLoader classLoader = getClass().getClassLoader(); URL imageUrl = classLoader.getResource("images/project-support.png"); String projectUrl = "http://gogui.sourceforge.net"; String supportUrl = "http://sourceforge.net/donate/index.php?group_id=59117"; JPanel goguiPanel = createPanel("<p align=\"center\"><b>GoGui " + Version.get() + "</b></p>" + "<p align=\"center\">" + "Graphical interface to Go programs<br>" + "&copy; 2003-2004, Markus Enzenberger" + "</p>" + "<p align=\"center\">" + "<tt><a href=\"" + projectUrl + "\">" + projectUrl + "</a></tt>" + "</p>" + "<p align=\"center\">" + "<a href=\"" + supportUrl + "\">" + "<img src=\"" + imageUrl + "\" border=\"0\"></a>" + "</p>"); tabbedPane.add("GoGui", goguiPanel); tabbedPane.setMnemonicAt(0, KeyEvent.VK_G); boolean isProgramAvailable = (name != null && ! name.equals("")); JPanel programPanel; if (isProgramAvailable) { String fullName = name; if (version != null || ! version.equals("")) fullName = fullName + " " + version; int width = GuiUtils.getDefaultMonoFontSize() * 25; programPanel = createPanel("<p align=\"center\"><b>" + fullName + "</b></p>" + "<p align=\"center\" width=\"" + width + "\">" + "Command: <tt>" + command + "</tt></p>" + "<p align=\"center\">" + "GTP protocol version " + protocolVersion + "</p>"); } else programPanel = new JPanel(); tabbedPane.add("Go Program", programPanel); tabbedPane.setMnemonicAt(1, KeyEvent.VK_P); if (! isProgramAvailable) tabbedPane.setEnabledAt(1, false); setMessage(tabbedPane); setOptionType(DEFAULT_OPTION); }
private AboutDialog(String name, String version, String protocolVersion, String command) { JTabbedPane tabbedPane = new JTabbedPane(); ClassLoader classLoader = getClass().getClassLoader(); URL imageUrl = classLoader.getResource("images/project-support.png"); String projectUrl = "http://gogui.sourceforge.net"; String supportUrl = "http://sourceforge.net/donate/index.php?group_id=59117"; JPanel goguiPanel = createPanel("<p align=\"center\"><b>GoGui " + Version.get() + "</b></p>" + "<p align=\"center\">" + "Graphical interface to Go programs<br>" + "&copy; 2003-2004, Markus Enzenberger" + "</p>" + "<p align=\"center\">" + "<tt><a href=\"" + projectUrl + "\">" + projectUrl + "</a></tt>" + "</p>" + "<p align=\"center\">" + "<a href=\"" + supportUrl + "\">" + "<img src=\"" + imageUrl + "\" border=\"0\"></a>" + "</p>"); tabbedPane.add("GoGui", goguiPanel); tabbedPane.setMnemonicAt(0, KeyEvent.VK_G); boolean isProgramAvailable = (name != null && ! name.equals("")); JPanel programPanel; if (isProgramAvailable) { String fullName = name; if (version != null && ! version.equals("")) fullName = fullName + " " + version; int width = GuiUtils.getDefaultMonoFontSize() * 25; programPanel = createPanel("<p align=\"center\"><b>" + fullName + "</b></p>" + "<p align=\"center\" width=\"" + width + "\">" + "Command: <tt>" + command + "</tt></p>" + "<p align=\"center\">" + "GTP protocol version " + protocolVersion + "</p>"); } else programPanel = new JPanel(); tabbedPane.add("Go Program", programPanel); tabbedPane.setMnemonicAt(1, KeyEvent.VK_P); if (! isProgramAvailable) tabbedPane.setEnabledAt(1, false); setMessage(tabbedPane); setOptionType(DEFAULT_OPTION); }
diff --git a/tests/org.eclipse.jst.jsp.tests.encoding/src/org/eclipse/jst/jsp/tests/encoding/jsp/JSPHeadTokenizerTester.java b/tests/org.eclipse.jst.jsp.tests.encoding/src/org/eclipse/jst/jsp/tests/encoding/jsp/JSPHeadTokenizerTester.java index 5af37e416..99278f870 100644 --- a/tests/org.eclipse.jst.jsp.tests.encoding/src/org/eclipse/jst/jsp/tests/encoding/jsp/JSPHeadTokenizerTester.java +++ b/tests/org.eclipse.jst.jsp.tests.encoding/src/org/eclipse/jst/jsp/tests/encoding/jsp/JSPHeadTokenizerTester.java @@ -1,374 +1,375 @@ /******************************************************************************* * Copyright (c) 2004, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jst.jsp.tests.encoding.jsp; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.StringTokenizer; import java.util.regex.Pattern; import junit.framework.TestCase; import org.eclipse.core.resources.IFile; import org.eclipse.jst.jsp.core.internal.contenttype.HeadParserToken; import org.eclipse.jst.jsp.core.internal.contenttype.JSPHeadTokenizer; import org.eclipse.jst.jsp.core.internal.contenttype.JSPHeadTokenizerConstants; import org.eclipse.jst.jsp.tests.encoding.JSPEncodingTestsPlugin; import org.eclipse.wst.sse.core.utils.StringUtils; import org.eclipse.wst.xml.core.internal.contenttype.EncodingParserConstants; import org.eclipse.wst.xml.core.internal.contenttype.XMLHeadTokenizerConstants; import org.eclipse.wst.xml.tests.encoding.ZippedTest; public class JSPHeadTokenizerTester extends TestCase { boolean DEBUG = false; private String fCharset; private String fContentType; private String fContentTypeValue; private final String fileDir = "jsp/"; private final String fileHome = "testfiles/"; private final String fileLocation = fileHome + fileDir; private String fPageEncodingValue = null; private String fXMLDecEncodingName; private String fLanguage; private void doTestFile(String filename, String expectedName) throws Exception { doTestFile(filename, expectedName, null, null); } private void doTestFile(String filename, String expectedName, String finalTokenType, String expectedContentType) throws Exception { try { doTestFile(JSPEncodingTestsPlugin.getTestReader(filename), expectedName, finalTokenType, expectedContentType); } catch (IOException e) { System.out.println("Error opening file \"" + filename +"\""); } } private void doTestFile(Reader fileReader, String expectedName, String finalTokenType, String expectedContentType) throws Exception { JSPHeadTokenizer tokenizer = null; tokenizer = new JSPHeadTokenizer(fileReader); HeadParserToken token = parseHeader(tokenizer); String resultValue = getAppropriateEncoding(); fileReader.close(); if (finalTokenType != null) { assertTrue("did not end as expected. found: " + token.getType(), finalTokenType.equals(token.getType())); } if (expectedName == null) { assertTrue("expected no encoding, but found: " + resultValue, resultValue == null); } else { assertTrue("expected " + expectedName + " but found " + resultValue, expectedName.equals(resultValue)); } String foundContentType = getContentType(); if (expectedContentType == null) { assertTrue("expected no contentType, but found: " + foundContentType, foundContentType == null); } else { assertTrue("expected " + expectedContentType + " but found " + foundContentType, expectedContentType.equals(foundContentType)); } } // public void testMalformedNoEncoding() { // String filename = fileLocation + "MalformedNoEncoding.jsp"; // doTestFile(filename); // } // public void testMalformedNoEncodingXSL() { // String filename = fileLocation + "MalformedNoEncodingXSL.jsp"; // doTestFile(filename); // } // public void testNoEncoding() { // String filename = fileLocation + "NoEncoding.jsp"; // doTestFile(filename); // } public void testNormalNonDefault() throws Exception { String filename = fileLocation + "NormalNonDefault.jsp"; doTestFile(filename, "ISO-8859-8"); } // public void testNormalPageCaseNonDefault() { // String filename = fileLocation + "NormalPageCaseNonDefault.jsp"; // doTestFile(filename); // } // public void testdefect223365() { // String filename = fileLocation + "SelColBeanRow12ResultsForm.jsp"; // doTestFile(filename); // } /** * returns encoding according to priority: 1. XML Declaration 2. page * directive pageEncoding name 3. page directive contentType charset name */ private String getAppropriateEncoding() { String result = null; if (fXMLDecEncodingName != null) result = fXMLDecEncodingName; else if (fPageEncodingValue != null) result = fPageEncodingValue; else if (fCharset != null) result = fCharset; return result; } private String getContentType() { return fContentType; } private boolean isLegalString(String tokenType) { boolean result = false; if (tokenType != null) { result = tokenType.equals(EncodingParserConstants.StringValue) || tokenType.equals(EncodingParserConstants.UnDelimitedStringValue) || tokenType.equals(EncodingParserConstants.InvalidTerminatedStringValue) || tokenType.equals(EncodingParserConstants.InvalidTermintatedUnDelimitedStringValue); } return result; } /** * This method should be exactly the same as what is in * JSPResourceEncodingDetector * * @param contentType */ private void parseContentTypeValue(String contentType) { /* * Based partially on * org.eclipse.jst.jsp.core.internal.document.PageDirectiveAdapterImpl * .getMimeTypeFromContentTypeValue(String) , divides the full value * into segments according to ';', assumes the first specifies the * content type itself if it has no '=', and that the remainder are * parameters which may specify a charset */ String cleanContentTypeValue = StringUtils.stripNonLetterDigits(contentType); /* Break the mime header into the main value and its parameters, separated by ';' */ StringTokenizer tokenizer = new StringTokenizer(cleanContentTypeValue, ";"); //$NON-NLS-1$ int tLen = tokenizer.countTokens(); if (tLen == 0) return; String[] tokens = new String[tLen]; int j = 0; while (tokenizer.hasMoreTokens()) { tokens[j] = tokenizer.nextToken(); j++; } int firstParameter = 0; if (tokens[0].indexOf('=') == -1) { /* * no equal sign in the first segment, so assume it indicates a * content type properly */ fContentType = tokens[0].trim(); firstParameter = 1; } /* * now handle parameters as name=value pairs, looking for "charset" * specifically */ Pattern equalPattern = Pattern.compile("\\s*=\\s*"); //$NON-NLS-1$ for (int i = firstParameter; i < tokens.length; i++) { String[] pair = equalPattern.split(tokens[i]); if (pair.length < 2) continue; if (pair[0].trim().equals("charset")) { //$NON-NLS-1$ fCharset = pair[1].trim(); } } } /** * Give's priority to encoding value, if found else, looks for contentType * value; */ private HeadParserToken parseHeader(JSPHeadTokenizer tokenizer) throws Exception { fPageEncodingValue = null; fCharset = null; fContentType = null; + fContentTypeValue = null; HeadParserToken token = null; HeadParserToken finalToken = null; do { token = tokenizer.getNextToken(); String tokenType = token.getType(); if(canHandleAsUnicodeStream(tokenType)) { } else if (tokenType == XMLHeadTokenizerConstants.XMLDelEncoding) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fXMLDecEncodingName = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageEncoding) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fPageEncodingValue = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageContentType) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fContentTypeValue = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageLanguage) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fLanguage = valueToken.getText(); } } } } while (tokenizer.hasMoreTokens()); if (fContentTypeValue != null) { parseContentTypeValue(fContentTypeValue); } finalToken = token; return finalToken; } private boolean canHandleAsUnicodeStream(String tokenType) { boolean canHandleAsUnicode = false; if (tokenType == EncodingParserConstants.UTF83ByteBOM) { canHandleAsUnicode = true; this.fCharset = "UTF-8"; //$NON-NLS-1$ } else if (tokenType == EncodingParserConstants.UTF16BE || tokenType == EncodingParserConstants.UTF16LE) { canHandleAsUnicode = true; this.fCharset = "UTF-16"; //$NON-NLS-1$ } return canHandleAsUnicode; } public void testBestCase() throws Exception { String filename = fileLocation + "nomalDirectiveCase.jsp"; doTestFile(filename, "ISO-8859-2", null, "text/html"); } public void testMinimalPageDirective() throws Exception { String filename = fileLocation + "minimalPageDirective.jsp"; doTestFile(filename, null, null, "text/html"); } public void testIllFormed() throws Exception { String filename = fileLocation + "testIllFormed.jsp"; doTestFile(filename, null); } public void testIllFormed2() throws Exception { String filename = fileLocation + "testIllFormed2.jsp"; doTestFile(filename, "UTF-8"); } public void testIllformedNormalNonDefault() throws Exception { String filename = fileLocation + "IllformedNormalNonDefault.jsp"; doTestFile(filename, "ISO-8859-8", null, "text/html"); } public void testEmptyFile() throws Exception { String filename = fileLocation + "EmptyFile.jsp"; doTestFile(filename, null); } public void testNomalDirectiveCaseUsingXMLSyntax() throws Exception { String filename = fileLocation + "nomalDirectiveCaseUsingXMLSyntax.jsp"; doTestFile(filename, "ISO-8859-2", null, "text/html"); } public void testNoPageDirective() throws Exception { String filename = fileLocation + "testNoPageDirective.jsp"; doTestFile(filename, null); } public void testNormalPageDirectiveWithXMLDecl() throws Exception { String filename = fileLocation + "nomalDirectiveCasewithXMLDecl.jsp"; doTestFile(filename, "ISO-8859-1", null, "text/html"); } public void testNoPageDirectiveAtFirst() throws Exception { String filename = fileLocation + "testNoPageDirectiveAtFirst.jsp"; doTestFile(filename, "ISO-8859-2", null, "text/html"); } public void testNoPageDirectiveInLargeFile() throws Exception { String filename = fileLocation + "testNoPageDirectiveInLargeFile.jsp"; doTestFile(filename, null, EncodingParserConstants.MAX_CHARS_REACHED, null); } public void testNormalCaseWithNeither() throws Exception { String filename = fileLocation + "nomalDirectiveCaseNoEncoding.jsp"; doTestFile(filename, null); } public void testNormalCharset() throws Exception { String filename = fileLocation + "nomalDirectiveCaseUsingCharset.jsp"; doTestFile(filename, "ISO-8859-3", null, "text/html"); } public void testUTF16le() throws Exception { String filename = fileLocation + "utf16le.jsp"; doTestFile(filename, "UTF-16LE", null, "text/html"); } public void testUTF16be() throws Exception { String filename = fileLocation + "utf16be.jsp"; doTestFile(filename, "UTF-16BE", null, "text/html"); } /* sun.io.MalformedInputException at sun.io.ByteToCharUTF8.convert(ByteToCharUTF8.java:262) at sun.nio.cs.StreamDecoder$ConverterSD.convertInto(StreamDecoder.java:314) at sun.nio.cs.StreamDecoder$ConverterSD.implRead(StreamDecoder.java:364) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:250) at java.io.InputStreamReader.read(InputStreamReader.java:212) at org.eclipse.jst.jsp.core.internal.contenttype.JSPHeadTokenizer.zzRefill(JSPHeadTokenizer.java:359) at org.eclipse.jst.jsp.core.internal.contenttype.JSPHeadTokenizer.primGetNextToken(JSPHeadTokenizer.java:598) at org.eclipse.jst.jsp.core.internal.contenttype.JSPHeadTokenizer.getNextToken(JSPHeadTokenizer.java:254) at org.eclipse.jst.jsp.tests.encoding.jsp.JSPHeadTokenizerTester.parseHeader(JSPHeadTokenizerTester.java:182) at org.eclipse.jst.jsp.tests.encoding.jsp.JSPHeadTokenizerTester.doTestFile(JSPHeadTokenizerTester.java:58) at org.eclipse.jst.jsp.tests.encoding.jsp.JSPHeadTokenizerTester.testUTF16BOM(JSPHeadTokenizerTester.java:324) */ public void testUTF16BOM() throws Exception { String filename = fileLocation + "utf16BOM.jsp"; ZippedTest test = new ZippedTest(); test.setUp(); IFile file = test.getFile(filename); assertNotNull(file); Reader fileReader = new FileReader(file.getLocationURI().getPath()); doTestFile(fileReader, "UTF-16", null, null); test.shutDown(); } public void testUTF16leXmlStyle() throws Exception { String filename = fileLocation + "utf16le_xmlStyle.jsp"; doTestFile(filename, "UTF-16LE", null, null); } public String getLanguage() { return fLanguage; } }
true
true
private HeadParserToken parseHeader(JSPHeadTokenizer tokenizer) throws Exception { fPageEncodingValue = null; fCharset = null; fContentType = null; HeadParserToken token = null; HeadParserToken finalToken = null; do { token = tokenizer.getNextToken(); String tokenType = token.getType(); if(canHandleAsUnicodeStream(tokenType)) { } else if (tokenType == XMLHeadTokenizerConstants.XMLDelEncoding) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fXMLDecEncodingName = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageEncoding) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fPageEncodingValue = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageContentType) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fContentTypeValue = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageLanguage) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fLanguage = valueToken.getText(); } } } } while (tokenizer.hasMoreTokens()); if (fContentTypeValue != null) { parseContentTypeValue(fContentTypeValue); } finalToken = token; return finalToken; }
private HeadParserToken parseHeader(JSPHeadTokenizer tokenizer) throws Exception { fPageEncodingValue = null; fCharset = null; fContentType = null; fContentTypeValue = null; HeadParserToken token = null; HeadParserToken finalToken = null; do { token = tokenizer.getNextToken(); String tokenType = token.getType(); if(canHandleAsUnicodeStream(tokenType)) { } else if (tokenType == XMLHeadTokenizerConstants.XMLDelEncoding) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fXMLDecEncodingName = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageEncoding) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fPageEncodingValue = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageContentType) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fContentTypeValue = valueToken.getText(); } } } else if (tokenType == JSPHeadTokenizerConstants.PageLanguage) { if (tokenizer.hasMoreTokens()) { HeadParserToken valueToken = tokenizer.getNextToken(); String valueTokenType = valueToken.getType(); if (isLegalString(valueTokenType)) { fLanguage = valueToken.getText(); } } } } while (tokenizer.hasMoreTokens()); if (fContentTypeValue != null) { parseContentTypeValue(fContentTypeValue); } finalToken = token; return finalToken; }
diff --git a/src/java/Servlets/myServlet.java b/src/java/Servlets/myServlet.java index 49511a4..61b7640 100755 --- a/src/java/Servlets/myServlet.java +++ b/src/java/Servlets/myServlet.java @@ -1,281 +1,281 @@ package Servlets; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import Objects.DBManager; import Objects.Product; import Objects.ProductInCart; import captchas.CaptchasDotNet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author Jason */ public class myServlet extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { if (request.getParameter("page").equals("login")) { try { String name = null; String role = null; // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); Statement statement = connection.createStatement(); // Search for the user ResultSet resultSet = statement.executeQuery("SELECT * FROM users;"); while (resultSet.next()) { if (resultSet.getString("username").equals(request.getParameter("username")) && resultSet.getString("password").equals(request.getParameter("password"))) { name = resultSet.getString("name"); role = resultSet.getString("role"); break; } } // Close connection to database statement.close(); connection.close(); if (name == null) { response.sendRedirect("loginFailed.jsp"); } else { HttpSession session = request.getSession(); session.setAttribute("name", name); if (role.equals("administrator")) { response.sendRedirect("admin.jsp"); } else { session.setAttribute("name", name); session.setAttribute("cart", new ArrayList<ProductInCart>()); - response.sendRedirect("shelf.jsp"); + response.sendRedirect("mainmenu.jsp"); } } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter( "page").equals("signup")) { try { // Construct the captchas object // Use same settings as in query.jsp CaptchasDotNet captchas = new captchas.CaptchasDotNet(request.getSession(true), "demo", "secret"); // Read the form values String captcha = request.getParameter("captcha"); // Check captcha switch (captchas.check(captcha)) { case 's': // Fail response.sendRedirect("loginFailed.jsp"); break; case 'm': // Fail response.sendRedirect("loginFailed.jsp"); break; case 'w': // Fail response.sendRedirect("loginFailed.jsp"); break; default: // Success // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO users(role, username, password, name, email) VALUES ( ?, ?, ?, ?, ? );"); // Add new user preparedStatement.setString(1, "user"); preparedStatement.setString(2, request.getParameter("username")); preparedStatement.setString(3, request.getParameter("password")); preparedStatement.setString(4, request.getParameter("name")); preparedStatement.setString(5, request.getParameter("email")); preparedStatement.executeUpdate(); // Close connection to database preparedStatement.close(); connection.close(); // Redirect to index.jsp response.sendRedirect("index.jsp"); } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter("page").equals("admin")) { try { if (request.getParameter("command").equals("delete")) { // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); Statement statement = connection.createStatement(); // Delete the data statement.execute("DELETE FROM users WHERE username = '" + request.getParameter("username") + "';"); // Redirect to admin.jsp response.sendRedirect("admin.jsp"); } else { request.getSession(false).setAttribute("username", request.getParameter("username")); response.sendRedirect("editUser.jsp"); } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter("page").equals("editUser")) { try { // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE users SET password=?, name=?, email=? WHERE username=?;"); // Update the data preparedStatement.setString(1, request.getParameter("password")); preparedStatement.setString(2, request.getParameter("name")); preparedStatement.setString(3, request.getParameter("email")); preparedStatement.setString(4, request.getSession(false).getAttribute("username").toString()); preparedStatement.executeUpdate(); // Redirect to admin.jsp response.sendRedirect("admin.jsp"); } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter( "page").equals("buy")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); Product product = new DBManager().getProduct(request.getParameter("productID")); Boolean exists = false; for (ProductInCart p : cart) { if (p.getProductID().equals(product.getProductID())) { p.setAmount(p.getAmount() + Integer.parseInt(request.getParameter("amount"))); exists = true; } } if (!exists) { ProductInCart newProduct = new ProductInCart(product.getProductID(), product.getName(), product.getDescription(), product.getStock(), product.getPrice(), product.getPictureURL(), Integer.parseInt(request.getParameter("amount"))); cart.add(newProduct); } response.sendRedirect("shelf.jsp"); } else if (request.getParameter( "page").equals("delete")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); for (int i = 0; i < cart.size(); i++) { if (cart.get(i).getProductID().equals(request.getParameter("productID"))) { cart.remove(i); break; } } response.sendRedirect("checkout.jsp"); } else if (request.getParameter( "page").equals("editamount")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); for (int i = 0; i < cart.size(); i++) { if (cart.get(i).getProductID().equals(request.getParameter("productID"))) { Integer newamount = Integer.parseInt(request.getParameter("newamount")); if (newamount == 0) { cart.remove(i); } else { cart.get(i).setAmount(Integer.parseInt(request.getParameter("newamount"))); } break; } } response.sendRedirect("checkout.jsp"); } } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
true
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { if (request.getParameter("page").equals("login")) { try { String name = null; String role = null; // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); Statement statement = connection.createStatement(); // Search for the user ResultSet resultSet = statement.executeQuery("SELECT * FROM users;"); while (resultSet.next()) { if (resultSet.getString("username").equals(request.getParameter("username")) && resultSet.getString("password").equals(request.getParameter("password"))) { name = resultSet.getString("name"); role = resultSet.getString("role"); break; } } // Close connection to database statement.close(); connection.close(); if (name == null) { response.sendRedirect("loginFailed.jsp"); } else { HttpSession session = request.getSession(); session.setAttribute("name", name); if (role.equals("administrator")) { response.sendRedirect("admin.jsp"); } else { session.setAttribute("name", name); session.setAttribute("cart", new ArrayList<ProductInCart>()); response.sendRedirect("shelf.jsp"); } } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter( "page").equals("signup")) { try { // Construct the captchas object // Use same settings as in query.jsp CaptchasDotNet captchas = new captchas.CaptchasDotNet(request.getSession(true), "demo", "secret"); // Read the form values String captcha = request.getParameter("captcha"); // Check captcha switch (captchas.check(captcha)) { case 's': // Fail response.sendRedirect("loginFailed.jsp"); break; case 'm': // Fail response.sendRedirect("loginFailed.jsp"); break; case 'w': // Fail response.sendRedirect("loginFailed.jsp"); break; default: // Success // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO users(role, username, password, name, email) VALUES ( ?, ?, ?, ?, ? );"); // Add new user preparedStatement.setString(1, "user"); preparedStatement.setString(2, request.getParameter("username")); preparedStatement.setString(3, request.getParameter("password")); preparedStatement.setString(4, request.getParameter("name")); preparedStatement.setString(5, request.getParameter("email")); preparedStatement.executeUpdate(); // Close connection to database preparedStatement.close(); connection.close(); // Redirect to index.jsp response.sendRedirect("index.jsp"); } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter("page").equals("admin")) { try { if (request.getParameter("command").equals("delete")) { // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); Statement statement = connection.createStatement(); // Delete the data statement.execute("DELETE FROM users WHERE username = '" + request.getParameter("username") + "';"); // Redirect to admin.jsp response.sendRedirect("admin.jsp"); } else { request.getSession(false).setAttribute("username", request.getParameter("username")); response.sendRedirect("editUser.jsp"); } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter("page").equals("editUser")) { try { // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE users SET password=?, name=?, email=? WHERE username=?;"); // Update the data preparedStatement.setString(1, request.getParameter("password")); preparedStatement.setString(2, request.getParameter("name")); preparedStatement.setString(3, request.getParameter("email")); preparedStatement.setString(4, request.getSession(false).getAttribute("username").toString()); preparedStatement.executeUpdate(); // Redirect to admin.jsp response.sendRedirect("admin.jsp"); } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter( "page").equals("buy")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); Product product = new DBManager().getProduct(request.getParameter("productID")); Boolean exists = false; for (ProductInCart p : cart) { if (p.getProductID().equals(product.getProductID())) { p.setAmount(p.getAmount() + Integer.parseInt(request.getParameter("amount"))); exists = true; } } if (!exists) { ProductInCart newProduct = new ProductInCart(product.getProductID(), product.getName(), product.getDescription(), product.getStock(), product.getPrice(), product.getPictureURL(), Integer.parseInt(request.getParameter("amount"))); cart.add(newProduct); } response.sendRedirect("shelf.jsp"); } else if (request.getParameter( "page").equals("delete")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); for (int i = 0; i < cart.size(); i++) { if (cart.get(i).getProductID().equals(request.getParameter("productID"))) { cart.remove(i); break; } } response.sendRedirect("checkout.jsp"); } else if (request.getParameter( "page").equals("editamount")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); for (int i = 0; i < cart.size(); i++) { if (cart.get(i).getProductID().equals(request.getParameter("productID"))) { Integer newamount = Integer.parseInt(request.getParameter("newamount")); if (newamount == 0) { cart.remove(i); } else { cart.get(i).setAmount(Integer.parseInt(request.getParameter("newamount"))); } break; } } response.sendRedirect("checkout.jsp"); } } finally { out.close(); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { if (request.getParameter("page").equals("login")) { try { String name = null; String role = null; // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); Statement statement = connection.createStatement(); // Search for the user ResultSet resultSet = statement.executeQuery("SELECT * FROM users;"); while (resultSet.next()) { if (resultSet.getString("username").equals(request.getParameter("username")) && resultSet.getString("password").equals(request.getParameter("password"))) { name = resultSet.getString("name"); role = resultSet.getString("role"); break; } } // Close connection to database statement.close(); connection.close(); if (name == null) { response.sendRedirect("loginFailed.jsp"); } else { HttpSession session = request.getSession(); session.setAttribute("name", name); if (role.equals("administrator")) { response.sendRedirect("admin.jsp"); } else { session.setAttribute("name", name); session.setAttribute("cart", new ArrayList<ProductInCart>()); response.sendRedirect("mainmenu.jsp"); } } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter( "page").equals("signup")) { try { // Construct the captchas object // Use same settings as in query.jsp CaptchasDotNet captchas = new captchas.CaptchasDotNet(request.getSession(true), "demo", "secret"); // Read the form values String captcha = request.getParameter("captcha"); // Check captcha switch (captchas.check(captcha)) { case 's': // Fail response.sendRedirect("loginFailed.jsp"); break; case 'm': // Fail response.sendRedirect("loginFailed.jsp"); break; case 'w': // Fail response.sendRedirect("loginFailed.jsp"); break; default: // Success // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO users(role, username, password, name, email) VALUES ( ?, ?, ?, ?, ? );"); // Add new user preparedStatement.setString(1, "user"); preparedStatement.setString(2, request.getParameter("username")); preparedStatement.setString(3, request.getParameter("password")); preparedStatement.setString(4, request.getParameter("name")); preparedStatement.setString(5, request.getParameter("email")); preparedStatement.executeUpdate(); // Close connection to database preparedStatement.close(); connection.close(); // Redirect to index.jsp response.sendRedirect("index.jsp"); } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter("page").equals("admin")) { try { if (request.getParameter("command").equals("delete")) { // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); Statement statement = connection.createStatement(); // Delete the data statement.execute("DELETE FROM users WHERE username = '" + request.getParameter("username") + "';"); // Redirect to admin.jsp response.sendRedirect("admin.jsp"); } else { request.getSession(false).setAttribute("username", request.getParameter("username")); response.sendRedirect("editUser.jsp"); } } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter("page").equals("editUser")) { try { // Load the driver Class.forName("com.mysql.jdbc.Driver").newInstance(); // Connect to MySQL Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/ITStore", "root", ""); PreparedStatement preparedStatement = connection.prepareStatement("UPDATE users SET password=?, name=?, email=? WHERE username=?;"); // Update the data preparedStatement.setString(1, request.getParameter("password")); preparedStatement.setString(2, request.getParameter("name")); preparedStatement.setString(3, request.getParameter("email")); preparedStatement.setString(4, request.getSession(false).getAttribute("username").toString()); preparedStatement.executeUpdate(); // Redirect to admin.jsp response.sendRedirect("admin.jsp"); } catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) { out.println(ex.toString()); } } else if (request.getParameter( "page").equals("buy")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); Product product = new DBManager().getProduct(request.getParameter("productID")); Boolean exists = false; for (ProductInCart p : cart) { if (p.getProductID().equals(product.getProductID())) { p.setAmount(p.getAmount() + Integer.parseInt(request.getParameter("amount"))); exists = true; } } if (!exists) { ProductInCart newProduct = new ProductInCart(product.getProductID(), product.getName(), product.getDescription(), product.getStock(), product.getPrice(), product.getPictureURL(), Integer.parseInt(request.getParameter("amount"))); cart.add(newProduct); } response.sendRedirect("shelf.jsp"); } else if (request.getParameter( "page").equals("delete")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); for (int i = 0; i < cart.size(); i++) { if (cart.get(i).getProductID().equals(request.getParameter("productID"))) { cart.remove(i); break; } } response.sendRedirect("checkout.jsp"); } else if (request.getParameter( "page").equals("editamount")) { ArrayList<ProductInCart> cart = (ArrayList<ProductInCart>) request.getSession(false).getAttribute("cart"); for (int i = 0; i < cart.size(); i++) { if (cart.get(i).getProductID().equals(request.getParameter("productID"))) { Integer newamount = Integer.parseInt(request.getParameter("newamount")); if (newamount == 0) { cart.remove(i); } else { cart.get(i).setAmount(Integer.parseInt(request.getParameter("newamount"))); } break; } } response.sendRedirect("checkout.jsp"); } } finally { out.close(); } }
diff --git a/trunk/CruxSite/src/main/java/org/cruxframework/cruxsite/client/MainController.java b/trunk/CruxSite/src/main/java/org/cruxframework/cruxsite/client/MainController.java index 9bd5265b2..e6303aad9 100644 --- a/trunk/CruxSite/src/main/java/org/cruxframework/cruxsite/client/MainController.java +++ b/trunk/CruxSite/src/main/java/org/cruxframework/cruxsite/client/MainController.java @@ -1,161 +1,162 @@ package org.cruxframework.cruxsite.client; import java.util.logging.Level; import java.util.logging.Logger; import org.cruxframework.crux.core.client.controller.Controller; import org.cruxframework.crux.core.client.controller.Expose; import org.cruxframework.crux.core.client.ioc.Inject; import org.cruxframework.crux.core.client.screen.Screen; import org.cruxframework.crux.core.client.screen.views.View; import org.cruxframework.crux.widgets.client.disposal.topmenudisposal.TopMenuDisposal; import org.cruxframework.crux.widgets.client.event.SelectEvent; import org.cruxframework.crux.widgets.client.rss.feed.Error; import org.cruxframework.crux.widgets.client.rss.feed.Feed; import org.cruxframework.crux.widgets.client.rss.feed.FeedApi; import org.cruxframework.crux.widgets.client.rss.feed.FeedCallback; import org.cruxframework.crux.widgets.client.rss.feed.Loader; import org.cruxframework.cruxsite.client.accessor.IndexAccessor; import com.google.gwt.logging.client.LogConfiguration; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Label; @Controller("mainController") public class MainController { @Inject private IndexAccessor screen; private static Logger logger = Logger.getLogger(MainController.class.getName()); @Expose public void onLoad() { Loader.init("ABQIAAAArGIZjhmsan61DtT58_d6cRQNU4gAv_Jc96TUa1T-tg6v_fuASxRtwAMNaJHgnp12SaDI9Cs17oKAzw", new Loader.LoaderCallback() { public void onError(Throwable t) { if (LogConfiguration.loggingIsEnabled()) { Window.alert("Erro carregando a API de feed."); logger.log(Level.SEVERE, "Error loading Google Feed API..."); } } public void onLoad() { - FeedApi feedLastBlogEntries = FeedApi.create("http://feeds.feedburner.com/cruxframework/blog"); - feedLastBlogEntries.includeHistoricalEntries(); + FeedApi feedLastBlogEntries = FeedApi.create("http://feeds.feedburner.com/cruxframework"); + //this will only get feeds from cache. + //feedLastBlogEntries.includeHistoricalEntries(); feedLastBlogEntries.setNumEntries(3); feedLastBlogEntries.load(new FeedCallback() { @Override public void onLoad(Feed feed) { screen.lastBlogEntries().setFeed(feed); //screen.lastBlogEntries(). } @Override public void onError(Error error) { // TODO Auto-generated method stub } }); } }); } @Expose public void showViewInfo(SelectEvent evt) { showView("info", evt); } @Expose public void showViewFast(SelectEvent evt) { showView("desempenho", evt); } @Expose public void showViewJava(SelectEvent evt) { showView("escrevaJava", evt); } @Expose public void showViewCrossDev(SelectEvent evt) { showView("multiplataforma", evt); } @Expose public void showViewOpenSource(SelectEvent evt) { showView("opensource", evt); } @Expose public void showViewAbout(SelectEvent evt) { showView("sobreocrux", evt); } @Expose public void showViewExamples(SelectEvent evt) { showView("exemplos", evt); } @Expose public void showAppHelloCross(SelectEvent evt) { showSampleApp(evt, "CrossDeviceHelloWorld"); } @Expose public void showAppSite(SelectEvent evt) { showSampleApp(evt, "CruxSite"); } @Expose public void showAppShowcase(SelectEvent evt) { showSampleApp(evt, "CrossDeviceShowcase"); } /** * @param evt * @param nomeAplicacao */ private void showSampleApp(SelectEvent evt, String nomeAplicacao) { showView("aplicacaoExemplo", evt); Label appName = (Label) View.getView("aplicacaoExemplo").getWidget("sampleAppName"); appName.setText(nomeAplicacao); } /** * @param viewName * @param evt **/ private void showView(String viewName, SelectEvent evt) { if(evt != null) { evt.setCanceled(true); } TopMenuDisposal disposal = (TopMenuDisposal) Screen.get("menuDisposal"); disposal.showView(viewName, true); } public void setScreen(IndexAccessor screen) { this.screen = screen; } }
true
true
public void onLoad() { Loader.init("ABQIAAAArGIZjhmsan61DtT58_d6cRQNU4gAv_Jc96TUa1T-tg6v_fuASxRtwAMNaJHgnp12SaDI9Cs17oKAzw", new Loader.LoaderCallback() { public void onError(Throwable t) { if (LogConfiguration.loggingIsEnabled()) { Window.alert("Erro carregando a API de feed."); logger.log(Level.SEVERE, "Error loading Google Feed API..."); } } public void onLoad() { FeedApi feedLastBlogEntries = FeedApi.create("http://feeds.feedburner.com/cruxframework/blog"); feedLastBlogEntries.includeHistoricalEntries(); feedLastBlogEntries.setNumEntries(3); feedLastBlogEntries.load(new FeedCallback() { @Override public void onLoad(Feed feed) { screen.lastBlogEntries().setFeed(feed); //screen.lastBlogEntries(). } @Override public void onError(Error error) { // TODO Auto-generated method stub } }); } }); }
public void onLoad() { Loader.init("ABQIAAAArGIZjhmsan61DtT58_d6cRQNU4gAv_Jc96TUa1T-tg6v_fuASxRtwAMNaJHgnp12SaDI9Cs17oKAzw", new Loader.LoaderCallback() { public void onError(Throwable t) { if (LogConfiguration.loggingIsEnabled()) { Window.alert("Erro carregando a API de feed."); logger.log(Level.SEVERE, "Error loading Google Feed API..."); } } public void onLoad() { FeedApi feedLastBlogEntries = FeedApi.create("http://feeds.feedburner.com/cruxframework"); //this will only get feeds from cache. //feedLastBlogEntries.includeHistoricalEntries(); feedLastBlogEntries.setNumEntries(3); feedLastBlogEntries.load(new FeedCallback() { @Override public void onLoad(Feed feed) { screen.lastBlogEntries().setFeed(feed); //screen.lastBlogEntries(). } @Override public void onError(Error error) { // TODO Auto-generated method stub } }); } }); }
diff --git a/atlassian-plugins-core/src/test/java/com/atlassian/plugin/util/TestClassUtils.java b/atlassian-plugins-core/src/test/java/com/atlassian/plugin/util/TestClassUtils.java index 7ccd1265..260a052c 100644 --- a/atlassian-plugins-core/src/test/java/com/atlassian/plugin/util/TestClassUtils.java +++ b/atlassian-plugins-core/src/test/java/com/atlassian/plugin/util/TestClassUtils.java @@ -1,186 +1,186 @@ package com.atlassian.plugin.util; import junit.framework.TestCase; import java.io.IOException; import java.io.Serializable; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import static com.google.common.collect.Sets.newHashSet; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.mockito.Mockito.mock; /** * */ public class TestClassUtils extends TestCase { public void testFindAllTypes() { assertEquals(newHashSet( List.class, AbstractList.class, Cloneable.class, RandomAccess.class, AbstractCollection.class, Iterable.class, Collection.class, ArrayList.class, Object.class, Serializable.class ), ClassUtils.findAllTypes(ArrayList.class)); } public void testGetTypeArguments() { assertEquals(asList(String.class), ClassUtils.getTypeArguments(BaseClass.class, Child.class)); assertEquals(asList(String.class), ClassUtils.getTypeArguments(BaseClass.class, Baby.class)); assertEquals(singletonList(null), ClassUtils.getTypeArguments(BaseClass.class, ForgotType.class)); } public void testGetTypeArgumentsDifferentClassloader() throws Exception { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { URL log4jUrl = getClass().getClassLoader().getResource("log4j.properties"); - URL root = new URL(log4jUrl.toExternalForm() + "/../"); + URL root = new URL(new URL(log4jUrl.toExternalForm()), "."); URLClassLoader urlCl = new URLClassLoader(new URL[] {root}, new FilteredClassLoader(MySuperClass.class)); ClosableClassLoader wrapCl = new ClosableClassLoader(getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(null); Class<?> module = ClassUtils.getTypeArguments((Class<Object>) urlCl.loadClass(MySuperClass.class.getName()), (Class<? extends MySuperClass>) urlCl.loadClass(MySubClass.class.getName())).get(0); assertEquals(MyModule.class.getName(), module.getName()); ClassLoader urlCl2 = new URLClassLoader(new URL[] {root}, new FilteredClassLoader(MySuperClass.class)); assertTrue(wrapCl.loadClass(MySuperClass.class.getName()) == urlCl2.loadClass(MySuperClass.class.getName())); assertTrue(wrapCl.loadClass(MySubClass.class.getName()) != urlCl2.loadClass(MySubClass.class.getName())); assertTrue(wrapCl.loadClass(MySubClass.class.getName()).getSuperclass() == urlCl2.loadClass(MySubClass.class.getName()).getSuperclass()); wrapCl.setClosed(true); //Thread.currentThread().setContextClassLoader(urlCl2); Class<?> module2 = ClassUtils.getTypeArguments((Class<Object>) urlCl2.loadClass(MySuperClass.class.getName()), (Class<? extends MySuperClass>) urlCl2.loadClass(MySubClass.class.getName())).get(0); assertEquals(MyModule.class.getName(), module2.getName()); assertTrue(module != module2); assertTrue(module != MyModule.class); assertTrue(module2 != MyModule.class); } finally { Thread.currentThread().setContextClassLoader(cl); } } public void testGetTypeArgumentsChildNotSubclass() { Class fakeChild = BaseClass.class; try { assertEquals(singletonList(null), ClassUtils.getTypeArguments(Baby.class, (Class<? extends Baby>) fakeChild)); fail("Should have failed"); } catch (IllegalArgumentException ex) { // this is good } } private static class BaseClass<T> {} private static class Child extends BaseClass<String>{} private static class ForgotType extends BaseClass{} private static class Mom<T> extends BaseClass<T>{} private static class Baby extends Mom<String>{} private static class ClosableClassLoader extends ClassLoader { private final ClassLoader delegate; private volatile boolean closed; public ClosableClassLoader(ClassLoader delegate) { super(null); this.delegate = delegate; } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { checkClosed(); return delegate.loadClass(name); } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { checkClosed(); return delegate.loadClass(name); } private void checkClosed() { if (closed) { throw new IllegalStateException("Closed"); } } @Override public URL getResource(String name) { checkClosed(); return delegate.getResource(name); } @Override public Enumeration<URL> getResources(String name) throws IOException { checkClosed(); return delegate.getResources(name); } public void setClosed(boolean closed) { this.closed = closed; } } private static class FilteredClassLoader extends ClassLoader { private final Collection<Class> classes; public FilteredClassLoader(Class... classes) { super(null); this.classes = asList(classes); } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { for (Class cls : classes) { if (cls.getName().equals(name)) { return cls; } } if (name.startsWith("java.")) { return ClassLoader.getSystemClassLoader().loadClass(name); } throw new ClassNotFoundException(name); } } }
true
true
public void testGetTypeArgumentsDifferentClassloader() throws Exception { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { URL log4jUrl = getClass().getClassLoader().getResource("log4j.properties"); URL root = new URL(log4jUrl.toExternalForm() + "/../"); URLClassLoader urlCl = new URLClassLoader(new URL[] {root}, new FilteredClassLoader(MySuperClass.class)); ClosableClassLoader wrapCl = new ClosableClassLoader(getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(null); Class<?> module = ClassUtils.getTypeArguments((Class<Object>) urlCl.loadClass(MySuperClass.class.getName()), (Class<? extends MySuperClass>) urlCl.loadClass(MySubClass.class.getName())).get(0); assertEquals(MyModule.class.getName(), module.getName()); ClassLoader urlCl2 = new URLClassLoader(new URL[] {root}, new FilteredClassLoader(MySuperClass.class)); assertTrue(wrapCl.loadClass(MySuperClass.class.getName()) == urlCl2.loadClass(MySuperClass.class.getName())); assertTrue(wrapCl.loadClass(MySubClass.class.getName()) != urlCl2.loadClass(MySubClass.class.getName())); assertTrue(wrapCl.loadClass(MySubClass.class.getName()).getSuperclass() == urlCl2.loadClass(MySubClass.class.getName()).getSuperclass()); wrapCl.setClosed(true); //Thread.currentThread().setContextClassLoader(urlCl2); Class<?> module2 = ClassUtils.getTypeArguments((Class<Object>) urlCl2.loadClass(MySuperClass.class.getName()), (Class<? extends MySuperClass>) urlCl2.loadClass(MySubClass.class.getName())).get(0); assertEquals(MyModule.class.getName(), module2.getName()); assertTrue(module != module2); assertTrue(module != MyModule.class); assertTrue(module2 != MyModule.class); } finally { Thread.currentThread().setContextClassLoader(cl); } }
public void testGetTypeArgumentsDifferentClassloader() throws Exception { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { URL log4jUrl = getClass().getClassLoader().getResource("log4j.properties"); URL root = new URL(new URL(log4jUrl.toExternalForm()), "."); URLClassLoader urlCl = new URLClassLoader(new URL[] {root}, new FilteredClassLoader(MySuperClass.class)); ClosableClassLoader wrapCl = new ClosableClassLoader(getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(null); Class<?> module = ClassUtils.getTypeArguments((Class<Object>) urlCl.loadClass(MySuperClass.class.getName()), (Class<? extends MySuperClass>) urlCl.loadClass(MySubClass.class.getName())).get(0); assertEquals(MyModule.class.getName(), module.getName()); ClassLoader urlCl2 = new URLClassLoader(new URL[] {root}, new FilteredClassLoader(MySuperClass.class)); assertTrue(wrapCl.loadClass(MySuperClass.class.getName()) == urlCl2.loadClass(MySuperClass.class.getName())); assertTrue(wrapCl.loadClass(MySubClass.class.getName()) != urlCl2.loadClass(MySubClass.class.getName())); assertTrue(wrapCl.loadClass(MySubClass.class.getName()).getSuperclass() == urlCl2.loadClass(MySubClass.class.getName()).getSuperclass()); wrapCl.setClosed(true); //Thread.currentThread().setContextClassLoader(urlCl2); Class<?> module2 = ClassUtils.getTypeArguments((Class<Object>) urlCl2.loadClass(MySuperClass.class.getName()), (Class<? extends MySuperClass>) urlCl2.loadClass(MySubClass.class.getName())).get(0); assertEquals(MyModule.class.getName(), module2.getName()); assertTrue(module != module2); assertTrue(module != MyModule.class); assertTrue(module2 != MyModule.class); } finally { Thread.currentThread().setContextClassLoader(cl); } }
diff --git a/components/bio-formats/src/loci/formats/in/RHKReader.java b/components/bio-formats/src/loci/formats/in/RHKReader.java index 80e0ab216..164b427a9 100644 --- a/components/bio-formats/src/loci/formats/in/RHKReader.java +++ b/components/bio-formats/src/loci/formats/in/RHKReader.java @@ -1,206 +1,210 @@ // // RHKReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.IOException; import loci.common.DataTools; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import ome.xml.model.primitives.PositiveFloat; /** * RHKReader is the file format reader for RHK Technologies files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/RHKReader.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/RHKReader.java;hb=HEAD">Gitweb</a></dd></dl> */ public class RHKReader extends FormatReader { // -- Constants -- private static final int HEADER_SIZE = 512; // -- Fields -- private boolean invertX = false, invertY = false; private long pixelOffset = 0; // -- Constructor -- /** Constructs a new RHK reader. */ public RHKReader() { super("RHK Technologies", new String[] {"sm2", "sm3"}); domains = new String[] {FormatTools.SPM_DOMAIN}; } // -- IFormatReader API methods -- /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); in.seek(pixelOffset); readPlane(in, x, y, w, h, buf); int bpp = FormatTools.getBytesPerPixel(getPixelType()); if (invertY) { byte[] rowBuf = new byte[w * bpp]; for (int row=0; row<h/2; row++) { int top = row * rowBuf.length; int bottom = (h - row - 1) * rowBuf.length; System.arraycopy(buf, top, rowBuf, 0, rowBuf.length); System.arraycopy(buf, bottom, buf, top, rowBuf.length); System.arraycopy(rowBuf, 0, buf, bottom, rowBuf.length); } } if (invertX) { byte[] pixel = new byte[bpp]; for (int row=0; row<h; row++) { for (int col=0; col<w/2; col++) { int left = row * w * bpp + col * bpp; int right = row * w * bpp + (w - col - 1) * bpp; System.arraycopy(buf, left, pixel, 0, bpp); System.arraycopy(buf, right, buf, left, bpp); System.arraycopy(pixel, 0, buf, right, bpp); } } } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { invertX = false; invertY = false; pixelOffset = 0; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); core[0].littleEndian = true; in.order(isLittleEndian()); boolean xpm = in.readShort() == 0xaa; int dataType = -1; if (xpm) { in.seek(40); int imageType = in.readInt(); int pageType = in.readInt(); dataType = in.readInt(); int lineType = in.readInt(); in.skipBytes(8); core[0].sizeX = in.readInt(); core[0].sizeY = in.readInt(); in.skipBytes(16); pixelOffset = in.readInt(); } else { in.seek(32); String[] typeData = in.readString(32).trim().split(" "); int imageType = Integer.parseInt(typeData[0]); dataType = Integer.parseInt(typeData[1]); int lineType = Integer.parseInt(typeData[2]); core[0].sizeX = Integer.parseInt(typeData[3]); core[0].sizeY = Integer.parseInt(typeData[4]); int pageType = Integer.parseInt(typeData[6]); pixelOffset = HEADER_SIZE; } switch (dataType) { case 0: core[0].pixelType = FormatTools.FLOAT; break; case 1: core[0].pixelType = FormatTools.INT16; break; case 2: core[0].pixelType = FormatTools.INT32; break; case 3: core[0].pixelType = FormatTools.UINT8; break; default: throw new FormatException("Unsupported data type: " + dataType); } double xScale = 0d, yScale = 0d; if (xpm) { in.skipBytes(8); xScale = in.readFloat() * 1000000; yScale = in.readFloat() * 1000000; } else { String[] xAxis = in.readString(32).trim().split(" "); String[] yAxis = in.readString(32).trim().split(" "); xScale = Double.parseDouble(xAxis[1]) * 1000000; yScale = Double.parseDouble(yAxis[1]) * 1000000; invertX = xScale < 0; invertY = yScale > 0; } in.seek(352); String description = in.readString(32).trim(); addGlobalMeta("Description", description); core[0].rgb = false; core[0].sizeZ = 1; core[0].sizeC = 1; core[0].sizeT = 1; core[0].imageCount = 1; core[0].dimensionOrder = "XYZCT"; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); MetadataTools.setDefaultCreationDate(store, currentId, 0); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { - store.setPixelsPhysicalSizeX(new PositiveFloat(xScale), 0); - store.setPixelsPhysicalSizeY(new PositiveFloat(yScale), 0); + if (xScale > 0) { + store.setPixelsPhysicalSizeX(new PositiveFloat(xScale), 0); + } + if (yScale > 0) { + store.setPixelsPhysicalSizeY(new PositiveFloat(yScale), 0); + } store.setImageDescription(description, 0); } } }
true
true
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); core[0].littleEndian = true; in.order(isLittleEndian()); boolean xpm = in.readShort() == 0xaa; int dataType = -1; if (xpm) { in.seek(40); int imageType = in.readInt(); int pageType = in.readInt(); dataType = in.readInt(); int lineType = in.readInt(); in.skipBytes(8); core[0].sizeX = in.readInt(); core[0].sizeY = in.readInt(); in.skipBytes(16); pixelOffset = in.readInt(); } else { in.seek(32); String[] typeData = in.readString(32).trim().split(" "); int imageType = Integer.parseInt(typeData[0]); dataType = Integer.parseInt(typeData[1]); int lineType = Integer.parseInt(typeData[2]); core[0].sizeX = Integer.parseInt(typeData[3]); core[0].sizeY = Integer.parseInt(typeData[4]); int pageType = Integer.parseInt(typeData[6]); pixelOffset = HEADER_SIZE; } switch (dataType) { case 0: core[0].pixelType = FormatTools.FLOAT; break; case 1: core[0].pixelType = FormatTools.INT16; break; case 2: core[0].pixelType = FormatTools.INT32; break; case 3: core[0].pixelType = FormatTools.UINT8; break; default: throw new FormatException("Unsupported data type: " + dataType); } double xScale = 0d, yScale = 0d; if (xpm) { in.skipBytes(8); xScale = in.readFloat() * 1000000; yScale = in.readFloat() * 1000000; } else { String[] xAxis = in.readString(32).trim().split(" "); String[] yAxis = in.readString(32).trim().split(" "); xScale = Double.parseDouble(xAxis[1]) * 1000000; yScale = Double.parseDouble(yAxis[1]) * 1000000; invertX = xScale < 0; invertY = yScale > 0; } in.seek(352); String description = in.readString(32).trim(); addGlobalMeta("Description", description); core[0].rgb = false; core[0].sizeZ = 1; core[0].sizeC = 1; core[0].sizeT = 1; core[0].imageCount = 1; core[0].dimensionOrder = "XYZCT"; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); MetadataTools.setDefaultCreationDate(store, currentId, 0); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { store.setPixelsPhysicalSizeX(new PositiveFloat(xScale), 0); store.setPixelsPhysicalSizeY(new PositiveFloat(yScale), 0); store.setImageDescription(description, 0); } }
protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); core[0].littleEndian = true; in.order(isLittleEndian()); boolean xpm = in.readShort() == 0xaa; int dataType = -1; if (xpm) { in.seek(40); int imageType = in.readInt(); int pageType = in.readInt(); dataType = in.readInt(); int lineType = in.readInt(); in.skipBytes(8); core[0].sizeX = in.readInt(); core[0].sizeY = in.readInt(); in.skipBytes(16); pixelOffset = in.readInt(); } else { in.seek(32); String[] typeData = in.readString(32).trim().split(" "); int imageType = Integer.parseInt(typeData[0]); dataType = Integer.parseInt(typeData[1]); int lineType = Integer.parseInt(typeData[2]); core[0].sizeX = Integer.parseInt(typeData[3]); core[0].sizeY = Integer.parseInt(typeData[4]); int pageType = Integer.parseInt(typeData[6]); pixelOffset = HEADER_SIZE; } switch (dataType) { case 0: core[0].pixelType = FormatTools.FLOAT; break; case 1: core[0].pixelType = FormatTools.INT16; break; case 2: core[0].pixelType = FormatTools.INT32; break; case 3: core[0].pixelType = FormatTools.UINT8; break; default: throw new FormatException("Unsupported data type: " + dataType); } double xScale = 0d, yScale = 0d; if (xpm) { in.skipBytes(8); xScale = in.readFloat() * 1000000; yScale = in.readFloat() * 1000000; } else { String[] xAxis = in.readString(32).trim().split(" "); String[] yAxis = in.readString(32).trim().split(" "); xScale = Double.parseDouble(xAxis[1]) * 1000000; yScale = Double.parseDouble(yAxis[1]) * 1000000; invertX = xScale < 0; invertY = yScale > 0; } in.seek(352); String description = in.readString(32).trim(); addGlobalMeta("Description", description); core[0].rgb = false; core[0].sizeZ = 1; core[0].sizeC = 1; core[0].sizeT = 1; core[0].imageCount = 1; core[0].dimensionOrder = "XYZCT"; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this); MetadataTools.setDefaultCreationDate(store, currentId, 0); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (xScale > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(xScale), 0); } if (yScale > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(yScale), 0); } store.setImageDescription(description, 0); } }
diff --git a/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ContentController.java b/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ContentController.java index cb65bdd7..c5e56838 100644 --- a/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ContentController.java +++ b/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ContentController.java @@ -1,2580 +1,2580 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple * Place, Suite 330 / Boston, MA 02111-1307 / USA. * * =============================================================================== */ package org.infoglue.cms.controllers.kernel.impl.simple; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.exolab.castor.jdo.Database; import org.exolab.castor.jdo.OQLQuery; import org.exolab.castor.jdo.ObjectNotFoundException; import org.exolab.castor.jdo.QueryResults; import org.infoglue.cms.applications.contenttool.wizards.actions.CreateContentWizardInfoBean; import org.infoglue.cms.entities.content.Content; import org.infoglue.cms.entities.content.ContentVO; import org.infoglue.cms.entities.content.ContentVersion; import org.infoglue.cms.entities.content.ContentVersionVO; import org.infoglue.cms.entities.content.impl.simple.ContentImpl; import org.infoglue.cms.entities.content.impl.simple.MediumContentImpl; import org.infoglue.cms.entities.content.impl.simple.SmallContentImpl; import org.infoglue.cms.entities.content.impl.simple.SmallestContentVersionImpl; import org.infoglue.cms.entities.kernel.BaseEntityVO; import org.infoglue.cms.entities.management.ContentTypeDefinition; import org.infoglue.cms.entities.management.ContentTypeDefinitionVO; import org.infoglue.cms.entities.management.LanguageVO; import org.infoglue.cms.entities.management.Repository; import org.infoglue.cms.entities.management.RepositoryLanguage; import org.infoglue.cms.entities.management.RepositoryVO; import org.infoglue.cms.entities.management.ServiceDefinition; import org.infoglue.cms.entities.management.ServiceDefinitionVO; import org.infoglue.cms.entities.management.impl.simple.ContentTypeDefinitionImpl; import org.infoglue.cms.entities.management.impl.simple.RepositoryImpl; import org.infoglue.cms.entities.structure.Qualifyer; import org.infoglue.cms.entities.structure.ServiceBinding; import org.infoglue.cms.entities.structure.SiteNode; import org.infoglue.cms.entities.structure.SiteNodeVO; import org.infoglue.cms.entities.structure.SiteNodeVersion; import org.infoglue.cms.entities.structure.impl.simple.SiteNodeImpl; import org.infoglue.cms.exception.Bug; import org.infoglue.cms.exception.ConstraintException; import org.infoglue.cms.exception.SystemException; import org.infoglue.cms.security.InfoGluePrincipal; import org.infoglue.cms.services.BaseService; import org.infoglue.cms.util.ConstraintExceptionBuffer; import org.infoglue.deliver.applications.databeans.DeliveryContext; import org.infoglue.deliver.util.CacheController; import org.infoglue.deliver.util.Timer; import com.opensymphony.module.propertyset.PropertySet; import com.opensymphony.module.propertyset.PropertySetManager; /** * @author Mattias Bogeblad */ public class ContentController extends BaseController { private final static Logger logger = Logger.getLogger(ContentController.class.getName()); //private static ContentController controller = null; /** * Factory method */ public static ContentController getContentController() { /* if(controller == null) controller = new ContentController(); return controller; */ return new ContentController(); } public ContentVO getContentVOWithId(Integer contentId) throws SystemException, Bug { return (ContentVO) getVOWithId(SmallContentImpl.class, contentId); } public ContentVO getContentVOWithId(Integer contentId, Database db) throws SystemException, Bug { return (ContentVO) getVOWithId(SmallContentImpl.class, contentId, db); } public ContentVO getSmallContentVOWithId(Integer contentId, Database db) throws SystemException, Bug { return (ContentVO) getVOWithId(SmallContentImpl.class, contentId, db); } public Content getContentWithId(Integer contentId, Database db) throws SystemException, Bug { return (Content) getObjectWithId(ContentImpl.class, contentId, db); } public Content getReadOnlyContentWithId(Integer contentId, Database db) throws SystemException, Bug { return (Content) getObjectWithIdAsReadOnly(ContentImpl.class, contentId, db); } public Content getReadOnlyMediumContentWithId(Integer contentId, Database db) throws SystemException, Bug { return (Content) getObjectWithIdAsReadOnly(MediumContentImpl.class, contentId, db); } public List getContentVOList() throws SystemException, Bug { return getAllVOObjects(ContentImpl.class, "contentId"); } public List<ContentVO> getContentVOListMarkedForDeletion(Integer repositoryId) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); List<ContentVO> contentVOListMarkedForDeletion = new ArrayList<ContentVO>(); try { beginTransaction(db); String sql = "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.isDeleted = $1 AND is_defined(c.repository.name) ORDER BY c.contentId"; if(repositoryId != null && repositoryId != -1) sql = "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.isDeleted = $1 AND is_defined(c.repository.name) AND c.repository = $2 ORDER BY c.contentId"; OQLQuery oql = db.getOQLQuery(sql); oql.bind(true); if(repositoryId != null && repositoryId != -1) oql.bind(repositoryId); QueryResults results = oql.execute(Database.READONLY); while(results.hasMore()) { Content content = (Content)results.next(); contentVOListMarkedForDeletion.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch ( Exception e) { throw new SystemException("An error occurred when we tried to fetch a list of deleted pages. Reason:" + e.getMessage(), e); } return contentVOListMarkedForDeletion; } /** * Returns a repository list marked for deletion. */ public Set<ContentVO> getContentVOListLastModifiedByPincipal(InfoGluePrincipal principal, String[] excludedContentTypes) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); Set<ContentVO> contentVOList = new HashSet<ContentVO>(); try { beginTransaction(db); OQLQuery oql = db.getOQLQuery("SELECT cv FROM org.infoglue.cms.entities.content.impl.simple.SmallestContentVersionImpl cv WHERE cv.versionModifier = $1 ORDER BY cv.modifiedDateTime DESC LIMIT $2"); oql.bind(principal.getName()); oql.bind(50); QueryResults results = oql.execute(Database.READONLY); while(results.hasMore()) { SmallestContentVersionImpl contentVersion = (SmallestContentVersionImpl)results.next(); ContentVO contentVO = getContentVOWithId(contentVersion.getValueObject().getContentId(), db); boolean isValid = true; for(int i=0; i<excludedContentTypes.length; i++) { String contentTypeDefinitionNameToExclude = excludedContentTypes[i]; ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName(contentTypeDefinitionNameToExclude, db); if(contentVO.getContentTypeDefinitionId().equals(ctdVO.getId())) { isValid = false; break; } } if(isValid) contentVOList.add(contentVO); } results.close(); oql.close(); commitTransaction(db); } catch ( Exception e) { e.printStackTrace(); throw new SystemException("An error occurred when we tried to fetch a list contents last modified by the user. Reason:" + e.getMessage(), e); } return contentVOList; } /** * This method finishes what the create content wizard initiated and resulted in. */ public ContentVO create(CreateContentWizardInfoBean createContentWizardInfoBean) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = create(db, createContentWizardInfoBean.getParentContentId(), createContentWizardInfoBean.getContentTypeDefinitionId(), createContentWizardInfoBean.getRepositoryId(), createContentWizardInfoBean.getContent().getValueObject()); Iterator it = createContentWizardInfoBean.getContentVersions().keySet().iterator(); while (it.hasNext()) { Integer languageId = (Integer)it.next(); logger.info("languageId:" + languageId); ContentVersionVO contentVersionVO = (ContentVersionVO)createContentWizardInfoBean.getContentVersions().get(languageId); contentVersionVO = ContentVersionController.getContentVersionController().create(content.getContentId(), languageId, contentVersionVO, null, db).getValueObject(); } //Bind if needed? ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public ContentVO create(Integer parentContentId, Integer contentTypeDefinitionId, Integer repositoryId, ContentVO contentVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = create(db, parentContentId, contentTypeDefinitionId, repositoryId, contentVO); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public /*synchronized*/ Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Integer repositoryId, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); if(repositoryId == null) repositoryId = parentContent.getRepository().getRepositoryId(); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); Repository repository = RepositoryController.getController().getRepositoryWithId(repositoryId, db); /* synchronized (controller) { //db.lock(parentContent); */ content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } //} //repository.getContents().add(content); } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Repository repository, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { delete(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. * @throws Exception * @throws Bug */ public void delete(Integer contentId, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws Bug, Exception { ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(infogluePrincipal, contentId); delete(contentVO, infogluePrincipal, forceDelete); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { delete(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { delete(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { /* synchronized (controller) { //db.lock(controller); */ Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { deleteRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /* } */ } else { deleteRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void deleteRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { - if(!skipRelationCheck) + if(!skipRelationCheck && !content.getIsDeleted()) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); deleteRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } content.setChildren(new ArrayList()); boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); if(!skipServiceBindings) ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); if(parentIterator != null) parentIterator.remove(); db.remove(content); Map args = new HashMap(); args.put("globalKey", "infoglue"); PropertySet ps = PropertySetManager.getInstance("jdbc", args); ps.remove( "content_" + content.getContentId() + "_allowedContentTypeNames"); ps.remove( "content_" + content.getContentId() + "_defaultContentTypeName"); ps.remove( "content_" + content.getContentId() + "_initialLanguageId"); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method returns true if the content does not have any published contentversions or * are restricted in any other way. */ private static boolean getIsDeletable(Content content, InfoGluePrincipal infogluePrincipal, Database db) throws SystemException { boolean isDeletable = true; if(content.getIsProtected().equals(ContentVO.YES)) { boolean hasAccess = AccessRightController.getController().getIsPrincipalAuthorized(db, infogluePrincipal, "Content.Delete", "" + content.getId()); if(!hasAccess) return false; } Collection contentVersions = content.getContentVersions(); Iterator versionIterator = contentVersions.iterator(); while (versionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)versionIterator.next(); if(contentVersion.getStateId().intValue() == ContentVersionVO.PUBLISHED_STATE.intValue() && contentVersion.getIsActive().booleanValue() == true) { logger.info("The content had a published version so we cannot delete it.."); isDeletable = false; break; } } return isDeletable; } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { markForDeletion(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { markForDeletion(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { markForDeletion(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { markForDeletionRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } } else { markForDeletionRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void markForDeletionRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305", "<br/><br/>" + content.getName() + " (" + content.getId() + ")"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); markForDeletionRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { //ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); //if(!skipServiceBindings) // ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); //if(parentIterator != null) // parentIterator.remove(); content.setIsDeleted(true); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method restored a content. */ public void restoreContent(Integer contentId, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { Content content = getContentWithId(contentId, db); content.setIsDeleted(false); while(content.getParentContent() != null && content.getParentContent().getIsDeleted()) { content = content.getParentContent(); content.setIsDeleted(false); } commitTransaction(db); } catch(Exception e) { rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public ContentVO update(ContentVO contentVO) throws ConstraintException, SystemException { return update(contentVO, null); } public ContentVO update(ContentVO contentVO, Integer contentTypeDefinitionId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); Content content = null; beginTransaction(db); try { content = (Content)getObjectWithId(ContentImpl.class, contentVO.getId(), db); content.setVO(contentVO); if(contentTypeDefinitionId != null) { ContentTypeDefinition contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } public List<LanguageVO> getAvailableLanguagVOListForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException, Exception { //List<LanguageVO> availableLanguageVOList = new ArrayList<LanguageVO>(); Content content = getContentWithId(contentId, db); List<LanguageVO> availableLanguageVOList = LanguageController.getController().getLanguageVOList(content.getRepositoryId(), db); /* if(content != null) { Repository repository = content.getRepository(); if(repository != null) { List availableRepositoryLanguageList = RepositoryLanguageController.getController().getRepositoryLanguageListWithRepositoryId(repository.getId(), db); Iterator i = availableRepositoryLanguageList.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); availableLanguageVOList.add(repositoryLanguage.getLanguage().getValueObject()); } } } */ return availableLanguageVOList; } /* public List getAvailableLanguagesForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException { List availableLanguageVOList = new ArrayList(); Content content = getContentWithId(contentId, db); if(content != null) { Repository repository = content.getRepository(); if(repository != null) { Collection availableLanguages = repository.getRepositoryLanguages(); Iterator i = availableLanguages.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); int position = 0; Iterator availableLanguageVOListIterator = availableLanguageVOList.iterator(); while(availableLanguageVOListIterator.hasNext()) { LanguageVO availableLanguageVO = (LanguageVO)availableLanguageVOListIterator.next(); if(repositoryLanguage.getLanguage().getValueObject().getId().intValue() < availableLanguageVO.getId().intValue()) break; position++; } availableLanguageVOList.add(position, repositoryLanguage.getLanguage().getValueObject()); } } } return availableLanguageVOList; } */ /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); ContentVO parentContentVO = null; beginTransaction(db); try { Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return parentContentVO; } /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId, Database db) throws SystemException, Bug { ContentVO parentContentVO = null; Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); logger.info("CONTENT:" + content.getName()); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); return parentContentVO; } public static void addChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().add(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public static void removeChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().remove(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { moveContent(contentVO, newParentContentId, db); commitTransaction(db); } catch(ConstraintException ce) { logger.error("An error occurred so we should not complete the transaction:" + ce.getMessage()); rollbackTransaction(db); throw new SystemException(ce.getMessage()); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId, Database db) throws ConstraintException, SystemException { ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; Content newParentContent = null; Content oldParentContent = null; //Validation that checks the entire object contentVO.validate(); if(newParentContentId == null) { logger.warn("You must specify the new parent-content......"); throw new ConstraintException("Content.parentContentId", "3303"); } if(contentVO.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot have the content as it's own parent......"); throw new ConstraintException("Content.parentContentId", "3301"); } content = getContentWithId(contentVO.getContentId(), db); oldParentContent = content.getParentContent(); newParentContent = getContentWithId(newParentContentId, db); if(oldParentContent.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot specify the same folder as it originally was located in......"); throw new ConstraintException("Content.parentContentId", "3304"); } Content tempContent = newParentContent.getParentContent(); while(tempContent != null) { if(tempContent.getId().intValue() == content.getId().intValue()) { logger.warn("You cannot move the content to a child under it......"); throw new ConstraintException("Content.parentContentId", "3302"); } tempContent = tempContent.getParentContent(); } oldParentContent.getChildren().remove(content); content.setParentContent((ContentImpl)newParentContent); changeRepositoryRecursive(content, newParentContent.getRepository()); //content.setRepository(newParentContent.getRepository()); newParentContent.getChildren().add(content); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); } /** * Recursively sets the contents repositoryId. * @param content * @param newRepository */ private void changeRepositoryRecursive(Content content, Repository newRepository) { if(content.getRepository().getId().intValue() != newRepository.getId().intValue()) { content.setRepository((RepositoryImpl)newRepository); Iterator childContentsIterator = content.getChildren().iterator(); while(childContentsIterator.hasNext()) { Content childContent = (Content)childContentsIterator.next(); changeRepositoryRecursive(childContent, newRepository); } } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName) throws SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { List result = getContentVOWithContentTypeDefinition(contentTypeDefinitionName, db); commitTransaction(db); return result; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName, Database db) throws SystemException { HashMap arguments = new HashMap(); arguments.put("method", "selectListOnContentTypeName"); List argumentList = new ArrayList(); String[] names = contentTypeDefinitionName.split(","); for(int i = 0; i < names.length; i++) { HashMap argument = new HashMap(); argument.put("contentTypeDefinitionName", names[i]); argumentList.add(argument); } arguments.put("arguments", argumentList); try { return getContentVOList(arguments, db); } catch(SystemException e) { throw e; } catch(Exception e) { throw new SystemException(e.getMessage()); } } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap) throws SystemException, Bug { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getContentVOWithId(contentId)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments); } return contents; } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap, Database db) throws SystemException, Exception { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getSmallContentVOWithId(contentId, db)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments, db); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); List contents = new ArrayList(); beginTransaction(db); try { Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND c.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments, Database db) throws SystemException, Exception { List contents = new ArrayList(); Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND c.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } return contents; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName) throws ConstraintException, SystemException { if(repositoryId == null || repositoryId.intValue() < 1) return null; Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { logger.info("Fetching the root content for the repository " + repositoryId); //OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE is_undefined(c.parentContentId) AND c.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = getRootContent(db, repositoryId, userName, createIfNonExisting); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Database db, Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException, Exception { Content content = null; logger.info("Fetching the root content for the repository " + repositoryId); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { if(createIfNonExisting) { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } } results.close(); oql.close(); return content; } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content createRootContent(Database db, Repository repository, String userName) throws ConstraintException, SystemException, Exception { Content content = null; ContentVO rootContentVO = new ContentVO(); rootContentVO.setCreatorName(userName); rootContentVO.setName(repository.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repository, rootContentVO); return content; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Integer repositoryId, Database db) throws ConstraintException, SystemException, Exception { Content content = null; OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(); this.logger.info("Fetching entity in read/write mode" + repositoryId); if (results.hasMore()) { content = (Content)results.next(); } results.close(); oql.close(); return content; } /** * This method returns a list of the children a content has. */ /* public List getContentChildrenVOList(Integer parentContentId) throws ConstraintException, SystemException { String key = "" + parentContentId; logger.info("key:" + key); List cachedChildContentVOList = (List)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = null; beginTransaction(db); try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } */ /** * This method returns a list of the children a content has. */ public List<ContentVO> getContentChildrenVOList(Integer parentContentId, String[] allowedContentTypeIds, Boolean showDeletedItems) throws ConstraintException, SystemException { String allowedContentTypeIdsString = ""; if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) allowedContentTypeIdsString += "_" + allowedContentTypeIds[i]; } String key = "" + parentContentId + allowedContentTypeIdsString + "_" + showDeletedItems; if(logger.isInfoEnabled()) logger.info("key:" + key); List<ContentVO> cachedChildContentVOList = (List<ContentVO>)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { if(logger.isInfoEnabled()) logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = new ArrayList(); beginTransaction(db); Timer t = new Timer(); /* try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); System.out.println("childrenVOList under:" + content.getName() + ":" + childrenVOList.size()); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } */ try { String contentTypeINClause = ""; if(allowedContentTypeIds != null && allowedContentTypeIds.length > 0) { contentTypeINClause = " AND (content.isBranch = true OR content.contentTypeDefinitionId IN LIST ("; for(int i=0; i < allowedContentTypeIds.length; i++) { if(i > 0) contentTypeINClause += ","; contentTypeINClause += "$" + (i+3); } contentTypeINClause += "))"; } String showDeletedItemsClause = " AND content.isDeleted = $2"; String SQL = "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 " + showDeletedItemsClause + contentTypeINClause + " ORDER BY content.contentId"; //System.out.println("SQL:" + SQL); OQLQuery oql = db.getOQLQuery(SQL); //OQLQuery oql = db.getOQLQuery( "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 ORDER BY content.contentId"); oql.bind(parentContentId); oql.bind(showDeletedItems); if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) { System.out.println("allowedContentTypeIds[i]:" + allowedContentTypeIds[i]); oql.bind(allowedContentTypeIds[i]); } } QueryResults results = oql.execute(Database.ReadOnly); while (results.hasMore()) { Content content = (Content)results.next(); childrenVOList.add(content.getValueObject()); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } /** * This method returns the contentTypeDefinitionVO which is associated with this content. */ public ContentTypeDefinitionVO getContentTypeDefinition(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); ContentTypeDefinitionVO contentTypeDefinitionVO = null; beginTransaction(db); try { ContentVO smallContentVO = getSmallContentVOWithId(contentId, db); if(smallContentVO != null && smallContentVO.getContentTypeDefinitionId() != null) contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(smallContentVO.getContentTypeDefinitionId(), db); /* Content content = getReadOnlyMediumContentWithId(contentId, db); if(content != null && content.getContentTypeDefinition() != null) contentTypeDefinitionVO = content.getContentTypeDefinition().getValueObject(); */ //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentTypeDefinitionVO; } /** * This method reurns a list of available languages for this content. */ public List getRepositoryLanguages(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List languages = null; beginTransaction(db); try { languages = LanguageController.getController().getLanguageVOList(contentId, db); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return languages; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { result = getBoundContents(db, serviceBindingId); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return result; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } public static List getInTransactionBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getController().getReadOnlyServiceBindingWithId(serviceBindingId, db); //ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments, db); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } /** * This method just sorts the list of qualifyers on sortOrder. */ private static List sortQualifyers(Collection qualifyers) { List sortedQualifyers = new ArrayList(); try { Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); int index = 0; Iterator sortedListIterator = sortedQualifyers.iterator(); while(sortedListIterator.hasNext()) { Qualifyer sortedQualifyer = (Qualifyer)sortedListIterator.next(); if(sortedQualifyer.getSortOrder().intValue() > qualifyer.getSortOrder().intValue()) { break; } index++; } sortedQualifyers.add(index, qualifyer); } } catch(Exception e) { logger.warn("The sorting of qualifyers failed:" + e.getMessage(), e); } return sortedQualifyers; } /** * This method returns the contents belonging to a certain repository. */ public List getRepositoryContents(Integer repositoryId, Database db) throws SystemException, Exception { List contents = new ArrayList(); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.repositoryId = $1 ORDER BY c.contentId"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content); } results.close(); oql.close(); return contents; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator) throws SystemException, Exception { ContentVO contentVO = null; Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { contentVO = getContentVOWithPath(repositoryId, path, forceFolders, creator, db); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVO; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { ContentVO content = getRootContent(repositoryId, db).getValueObject(); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; if(!name.equals("")) { final ContentVO childContent = getChildVOWithName(content.getContentId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent.getValueObject(); } } } return content; } public Content getContentWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { Content content = getRootContent(repositoryId, db); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; final Content childContent = getChildWithName(content.getId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { logger.info(" CREATE " + name); ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent; } } return content; } /** * */ private ContentVO getChildVOWithName(Integer parentContentId, String name, Database db) throws Exception { ContentVO contentVO = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.parentContentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(Database.ReadOnly); if(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contentVO = content.getValueObject(); } results.close(); oql.close(); return contentVO; } /** * */ private Content getChildWithName(Integer parentContentId, String name, Database db) throws Exception { Content content = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.parentContent.contentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(); if(results.hasMore()) { content = (ContentImpl)results.next(); } results.close(); oql.close(); return content; } /** * */ /* private Content getChildWithName(Content content, String name, Database db) { for(Iterator i=content.getChildren().iterator(); i.hasNext(); ) { final Content childContent = (Content) i.next(); if(childContent.getName().equals(name)) return childContent; } return null; } */ /** * Recursive methods to get all contentVersions of a given state under the specified parent content. */ public List getContentVOWithParentRecursive(Integer contentId) throws ConstraintException, SystemException { return getContentVOWithParentRecursive(contentId, new ArrayList()); } private List getContentVOWithParentRecursive(Integer contentId, List resultList) throws ConstraintException, SystemException { // Get the versions of this content. resultList.add(getContentVOWithId(contentId)); // Get the children of this content and do the recursion List childContentList = ContentController.getContentController().getContentChildrenVOList(contentId, null, false); Iterator cit = childContentList.iterator(); while (cit.hasNext()) { ContentVO contentVO = (ContentVO) cit.next(); getContentVOWithParentRecursive(contentVO.getId(), resultList); } return resultList; } public String getContentAttribute(Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId); attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, Integer stateId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, stateId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), stateId, db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } /** * This is a method that gives the user back an newly initialized ValueObject for this entity that the controller * is handling. */ public BaseEntityVO getNewVO() { return new ContentVO(); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId) throws ConstraintException, SystemException, Bug, Exception { return getContentPath(contentId, false, false); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId, boolean includeRootContent, boolean includeRepositoryName) throws ConstraintException, SystemException, Bug, Exception { StringBuffer sb = new StringBuffer(); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); sb.insert(0, contentVO.getName()); while (contentVO.getParentContentId() != null) { contentVO = ContentController.getContentController().getContentVOWithId(contentVO.getParentContentId()); if (includeRootContent || contentVO.getParentContentId() != null) { sb.insert(0, contentVO.getName() + "/"); } } if (includeRepositoryName) { RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(contentVO.getRepositoryId()); if(repositoryVO != null) sb.insert(0, repositoryVO.getName() + " - /"); } return sb.toString(); } public List<ContentVO> getUpcomingExpiringContents(int numberOfWeeks) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfWeeks); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } public List<ContentVO> getUpcomingExpiringContents(int numberOfDays, InfoGluePrincipal principal, String[] excludedContentTypes) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3 AND c.contentVersions.versionModifier = $4"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfDays); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); oql.bind(principal.getName()); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); boolean isValid = true; for(int i=0; i<excludedContentTypes.length; i++) { String contentTypeDefinitionNameToExclude = excludedContentTypes[i]; ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName(contentTypeDefinitionNameToExclude, db); if(content.getContentTypeDefinitionId().equals(ctdVO.getId())) { isValid = false; break; } } if(isValid) contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } /** * This method checks if there are published versions available for the contentVersion. */ public boolean hasPublishedVersion(Integer contentId) { boolean hasPublishedVersion = false; try { ContentVersion contentVersion = ContentVersionController.getContentVersionController().getLatestPublishedContentVersion(contentId); if(contentVersion != null) { hasPublishedVersion = true; } } catch(Exception e){} return hasPublishedVersion; } public List<ContentVO> getRelatedContents(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallback) throws Exception { String qualifyerXML = getContentAttribute(db, contentId, languageId, attributeName, useLanguageFallback); return getRelatedContentsFromXML(qualifyerXML); } public List<SiteNodeVO> getRelatedSiteNodes(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallback) throws Exception { String qualifyerXML = getContentAttribute(db, contentId, languageId, attributeName, useLanguageFallback); return getRelatedSiteNodesFromXML(qualifyerXML); } /** * This method gets the related contents from an XML. */ private String idElementStart = "<id>"; private String idElementEnd = "</id>"; private String idAttribute1Start = "id=\""; private String idAttribute1End = "\""; private String idAttribute2Start = "id='"; private String idAttribute2End = "'"; private List<ContentVO> getRelatedContentsFromXML(String qualifyerXML) { if(logger.isInfoEnabled()) logger.info("qualifyerXML:" + qualifyerXML); Timer t = new Timer(); List<ContentVO> relatedContentVOList = new ArrayList<ContentVO>(); try { if(qualifyerXML != null && !qualifyerXML.equals("")) { String startExpression = idElementStart; String endExpression = idElementEnd; int idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute1Start; idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute2Start; endExpression = idAttribute2End; idIndex = qualifyerXML.indexOf(startExpression); } else { endExpression = idAttribute1End; } } while(idIndex > -1) { int endIndex = qualifyerXML.indexOf(endExpression, idIndex + 4); String id = qualifyerXML.substring(idIndex + 4, endIndex); try { Integer contentId = new Integer(id); relatedContentVOList.add(getContentVOWithId(contentId)); } catch(Exception e) { logger.info("An error occurred when looking up one of the related contents FromXML:" + e.getMessage(), e); } idIndex = qualifyerXML.indexOf(startExpression, idIndex + 5); } } } catch(Exception e) { logger.error("An error occurred trying to get related contents from qualifyerXML " + qualifyerXML + ":" + e.getMessage(), e); } return relatedContentVOList; } /** * This method gets the related pages from an XML. */ private List<SiteNodeVO> getRelatedSiteNodesFromXML(String qualifyerXML) { if(logger.isInfoEnabled()) logger.info("qualifyerXML:" + qualifyerXML); Timer t = new Timer(); List<SiteNodeVO> relatedPages = new ArrayList<SiteNodeVO>(); try { if(qualifyerXML != null && !qualifyerXML.equals("")) { String startExpression = idElementStart; String endExpression = idElementEnd; int idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute1Start; idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute2Start; endExpression = idAttribute2End; idIndex = qualifyerXML.indexOf(startExpression); } else { endExpression = idAttribute1End; } } while(idIndex > -1) { int endIndex = qualifyerXML.indexOf(endExpression, idIndex + 4); String id = qualifyerXML.substring(idIndex + 4, endIndex); try { SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(new Integer(id)); relatedPages.add(siteNodeVO); } catch(Exception e) { logger.info("An error occurred when looking up one of the related Pages FromXML:" + e.getMessage(), e); } idIndex = qualifyerXML.indexOf(startExpression, idIndex + 5); } } } catch(Exception e) { logger.error("An error occurred trying to get related contents from qualifyerXML " + qualifyerXML + ":" + e.getMessage(), e); } return relatedPages; } }
true
true
public /*synchronized*/ Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Integer repositoryId, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); if(repositoryId == null) repositoryId = parentContent.getRepository().getRepositoryId(); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); Repository repository = RepositoryController.getController().getRepositoryWithId(repositoryId, db); /* synchronized (controller) { //db.lock(parentContent); */ content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } //} //repository.getContents().add(content); } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Repository repository, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { delete(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. * @throws Exception * @throws Bug */ public void delete(Integer contentId, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws Bug, Exception { ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(infogluePrincipal, contentId); delete(contentVO, infogluePrincipal, forceDelete); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { delete(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { delete(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { /* synchronized (controller) { //db.lock(controller); */ Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { deleteRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /* } */ } else { deleteRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void deleteRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); deleteRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } content.setChildren(new ArrayList()); boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); if(!skipServiceBindings) ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); if(parentIterator != null) parentIterator.remove(); db.remove(content); Map args = new HashMap(); args.put("globalKey", "infoglue"); PropertySet ps = PropertySetManager.getInstance("jdbc", args); ps.remove( "content_" + content.getContentId() + "_allowedContentTypeNames"); ps.remove( "content_" + content.getContentId() + "_defaultContentTypeName"); ps.remove( "content_" + content.getContentId() + "_initialLanguageId"); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method returns true if the content does not have any published contentversions or * are restricted in any other way. */ private static boolean getIsDeletable(Content content, InfoGluePrincipal infogluePrincipal, Database db) throws SystemException { boolean isDeletable = true; if(content.getIsProtected().equals(ContentVO.YES)) { boolean hasAccess = AccessRightController.getController().getIsPrincipalAuthorized(db, infogluePrincipal, "Content.Delete", "" + content.getId()); if(!hasAccess) return false; } Collection contentVersions = content.getContentVersions(); Iterator versionIterator = contentVersions.iterator(); while (versionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)versionIterator.next(); if(contentVersion.getStateId().intValue() == ContentVersionVO.PUBLISHED_STATE.intValue() && contentVersion.getIsActive().booleanValue() == true) { logger.info("The content had a published version so we cannot delete it.."); isDeletable = false; break; } } return isDeletable; } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { markForDeletion(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { markForDeletion(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { markForDeletion(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { markForDeletionRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } } else { markForDeletionRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void markForDeletionRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305", "<br/><br/>" + content.getName() + " (" + content.getId() + ")"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); markForDeletionRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { //ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); //if(!skipServiceBindings) // ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); //if(parentIterator != null) // parentIterator.remove(); content.setIsDeleted(true); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method restored a content. */ public void restoreContent(Integer contentId, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { Content content = getContentWithId(contentId, db); content.setIsDeleted(false); while(content.getParentContent() != null && content.getParentContent().getIsDeleted()) { content = content.getParentContent(); content.setIsDeleted(false); } commitTransaction(db); } catch(Exception e) { rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public ContentVO update(ContentVO contentVO) throws ConstraintException, SystemException { return update(contentVO, null); } public ContentVO update(ContentVO contentVO, Integer contentTypeDefinitionId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); Content content = null; beginTransaction(db); try { content = (Content)getObjectWithId(ContentImpl.class, contentVO.getId(), db); content.setVO(contentVO); if(contentTypeDefinitionId != null) { ContentTypeDefinition contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } public List<LanguageVO> getAvailableLanguagVOListForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException, Exception { //List<LanguageVO> availableLanguageVOList = new ArrayList<LanguageVO>(); Content content = getContentWithId(contentId, db); List<LanguageVO> availableLanguageVOList = LanguageController.getController().getLanguageVOList(content.getRepositoryId(), db); /* if(content != null) { Repository repository = content.getRepository(); if(repository != null) { List availableRepositoryLanguageList = RepositoryLanguageController.getController().getRepositoryLanguageListWithRepositoryId(repository.getId(), db); Iterator i = availableRepositoryLanguageList.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); availableLanguageVOList.add(repositoryLanguage.getLanguage().getValueObject()); } } } */ return availableLanguageVOList; } /* public List getAvailableLanguagesForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException { List availableLanguageVOList = new ArrayList(); Content content = getContentWithId(contentId, db); if(content != null) { Repository repository = content.getRepository(); if(repository != null) { Collection availableLanguages = repository.getRepositoryLanguages(); Iterator i = availableLanguages.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); int position = 0; Iterator availableLanguageVOListIterator = availableLanguageVOList.iterator(); while(availableLanguageVOListIterator.hasNext()) { LanguageVO availableLanguageVO = (LanguageVO)availableLanguageVOListIterator.next(); if(repositoryLanguage.getLanguage().getValueObject().getId().intValue() < availableLanguageVO.getId().intValue()) break; position++; } availableLanguageVOList.add(position, repositoryLanguage.getLanguage().getValueObject()); } } } return availableLanguageVOList; } */ /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); ContentVO parentContentVO = null; beginTransaction(db); try { Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return parentContentVO; } /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId, Database db) throws SystemException, Bug { ContentVO parentContentVO = null; Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); logger.info("CONTENT:" + content.getName()); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); return parentContentVO; } public static void addChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().add(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public static void removeChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().remove(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { moveContent(contentVO, newParentContentId, db); commitTransaction(db); } catch(ConstraintException ce) { logger.error("An error occurred so we should not complete the transaction:" + ce.getMessage()); rollbackTransaction(db); throw new SystemException(ce.getMessage()); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId, Database db) throws ConstraintException, SystemException { ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; Content newParentContent = null; Content oldParentContent = null; //Validation that checks the entire object contentVO.validate(); if(newParentContentId == null) { logger.warn("You must specify the new parent-content......"); throw new ConstraintException("Content.parentContentId", "3303"); } if(contentVO.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot have the content as it's own parent......"); throw new ConstraintException("Content.parentContentId", "3301"); } content = getContentWithId(contentVO.getContentId(), db); oldParentContent = content.getParentContent(); newParentContent = getContentWithId(newParentContentId, db); if(oldParentContent.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot specify the same folder as it originally was located in......"); throw new ConstraintException("Content.parentContentId", "3304"); } Content tempContent = newParentContent.getParentContent(); while(tempContent != null) { if(tempContent.getId().intValue() == content.getId().intValue()) { logger.warn("You cannot move the content to a child under it......"); throw new ConstraintException("Content.parentContentId", "3302"); } tempContent = tempContent.getParentContent(); } oldParentContent.getChildren().remove(content); content.setParentContent((ContentImpl)newParentContent); changeRepositoryRecursive(content, newParentContent.getRepository()); //content.setRepository(newParentContent.getRepository()); newParentContent.getChildren().add(content); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); } /** * Recursively sets the contents repositoryId. * @param content * @param newRepository */ private void changeRepositoryRecursive(Content content, Repository newRepository) { if(content.getRepository().getId().intValue() != newRepository.getId().intValue()) { content.setRepository((RepositoryImpl)newRepository); Iterator childContentsIterator = content.getChildren().iterator(); while(childContentsIterator.hasNext()) { Content childContent = (Content)childContentsIterator.next(); changeRepositoryRecursive(childContent, newRepository); } } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName) throws SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { List result = getContentVOWithContentTypeDefinition(contentTypeDefinitionName, db); commitTransaction(db); return result; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName, Database db) throws SystemException { HashMap arguments = new HashMap(); arguments.put("method", "selectListOnContentTypeName"); List argumentList = new ArrayList(); String[] names = contentTypeDefinitionName.split(","); for(int i = 0; i < names.length; i++) { HashMap argument = new HashMap(); argument.put("contentTypeDefinitionName", names[i]); argumentList.add(argument); } arguments.put("arguments", argumentList); try { return getContentVOList(arguments, db); } catch(SystemException e) { throw e; } catch(Exception e) { throw new SystemException(e.getMessage()); } } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap) throws SystemException, Bug { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getContentVOWithId(contentId)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments); } return contents; } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap, Database db) throws SystemException, Exception { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getSmallContentVOWithId(contentId, db)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments, db); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); List contents = new ArrayList(); beginTransaction(db); try { Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND c.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments, Database db) throws SystemException, Exception { List contents = new ArrayList(); Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND c.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } return contents; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName) throws ConstraintException, SystemException { if(repositoryId == null || repositoryId.intValue() < 1) return null; Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { logger.info("Fetching the root content for the repository " + repositoryId); //OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE is_undefined(c.parentContentId) AND c.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = getRootContent(db, repositoryId, userName, createIfNonExisting); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Database db, Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException, Exception { Content content = null; logger.info("Fetching the root content for the repository " + repositoryId); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { if(createIfNonExisting) { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } } results.close(); oql.close(); return content; } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content createRootContent(Database db, Repository repository, String userName) throws ConstraintException, SystemException, Exception { Content content = null; ContentVO rootContentVO = new ContentVO(); rootContentVO.setCreatorName(userName); rootContentVO.setName(repository.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repository, rootContentVO); return content; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Integer repositoryId, Database db) throws ConstraintException, SystemException, Exception { Content content = null; OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(); this.logger.info("Fetching entity in read/write mode" + repositoryId); if (results.hasMore()) { content = (Content)results.next(); } results.close(); oql.close(); return content; } /** * This method returns a list of the children a content has. */ /* public List getContentChildrenVOList(Integer parentContentId) throws ConstraintException, SystemException { String key = "" + parentContentId; logger.info("key:" + key); List cachedChildContentVOList = (List)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = null; beginTransaction(db); try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } */ /** * This method returns a list of the children a content has. */ public List<ContentVO> getContentChildrenVOList(Integer parentContentId, String[] allowedContentTypeIds, Boolean showDeletedItems) throws ConstraintException, SystemException { String allowedContentTypeIdsString = ""; if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) allowedContentTypeIdsString += "_" + allowedContentTypeIds[i]; } String key = "" + parentContentId + allowedContentTypeIdsString + "_" + showDeletedItems; if(logger.isInfoEnabled()) logger.info("key:" + key); List<ContentVO> cachedChildContentVOList = (List<ContentVO>)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { if(logger.isInfoEnabled()) logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = new ArrayList(); beginTransaction(db); Timer t = new Timer(); /* try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); System.out.println("childrenVOList under:" + content.getName() + ":" + childrenVOList.size()); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } */ try { String contentTypeINClause = ""; if(allowedContentTypeIds != null && allowedContentTypeIds.length > 0) { contentTypeINClause = " AND (content.isBranch = true OR content.contentTypeDefinitionId IN LIST ("; for(int i=0; i < allowedContentTypeIds.length; i++) { if(i > 0) contentTypeINClause += ","; contentTypeINClause += "$" + (i+3); } contentTypeINClause += "))"; } String showDeletedItemsClause = " AND content.isDeleted = $2"; String SQL = "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 " + showDeletedItemsClause + contentTypeINClause + " ORDER BY content.contentId"; //System.out.println("SQL:" + SQL); OQLQuery oql = db.getOQLQuery(SQL); //OQLQuery oql = db.getOQLQuery( "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 ORDER BY content.contentId"); oql.bind(parentContentId); oql.bind(showDeletedItems); if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) { System.out.println("allowedContentTypeIds[i]:" + allowedContentTypeIds[i]); oql.bind(allowedContentTypeIds[i]); } } QueryResults results = oql.execute(Database.ReadOnly); while (results.hasMore()) { Content content = (Content)results.next(); childrenVOList.add(content.getValueObject()); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } /** * This method returns the contentTypeDefinitionVO which is associated with this content. */ public ContentTypeDefinitionVO getContentTypeDefinition(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); ContentTypeDefinitionVO contentTypeDefinitionVO = null; beginTransaction(db); try { ContentVO smallContentVO = getSmallContentVOWithId(contentId, db); if(smallContentVO != null && smallContentVO.getContentTypeDefinitionId() != null) contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(smallContentVO.getContentTypeDefinitionId(), db); /* Content content = getReadOnlyMediumContentWithId(contentId, db); if(content != null && content.getContentTypeDefinition() != null) contentTypeDefinitionVO = content.getContentTypeDefinition().getValueObject(); */ //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentTypeDefinitionVO; } /** * This method reurns a list of available languages for this content. */ public List getRepositoryLanguages(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List languages = null; beginTransaction(db); try { languages = LanguageController.getController().getLanguageVOList(contentId, db); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return languages; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { result = getBoundContents(db, serviceBindingId); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return result; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } public static List getInTransactionBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getController().getReadOnlyServiceBindingWithId(serviceBindingId, db); //ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments, db); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } /** * This method just sorts the list of qualifyers on sortOrder. */ private static List sortQualifyers(Collection qualifyers) { List sortedQualifyers = new ArrayList(); try { Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); int index = 0; Iterator sortedListIterator = sortedQualifyers.iterator(); while(sortedListIterator.hasNext()) { Qualifyer sortedQualifyer = (Qualifyer)sortedListIterator.next(); if(sortedQualifyer.getSortOrder().intValue() > qualifyer.getSortOrder().intValue()) { break; } index++; } sortedQualifyers.add(index, qualifyer); } } catch(Exception e) { logger.warn("The sorting of qualifyers failed:" + e.getMessage(), e); } return sortedQualifyers; } /** * This method returns the contents belonging to a certain repository. */ public List getRepositoryContents(Integer repositoryId, Database db) throws SystemException, Exception { List contents = new ArrayList(); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.repositoryId = $1 ORDER BY c.contentId"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content); } results.close(); oql.close(); return contents; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator) throws SystemException, Exception { ContentVO contentVO = null; Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { contentVO = getContentVOWithPath(repositoryId, path, forceFolders, creator, db); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVO; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { ContentVO content = getRootContent(repositoryId, db).getValueObject(); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; if(!name.equals("")) { final ContentVO childContent = getChildVOWithName(content.getContentId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent.getValueObject(); } } } return content; } public Content getContentWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { Content content = getRootContent(repositoryId, db); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; final Content childContent = getChildWithName(content.getId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { logger.info(" CREATE " + name); ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent; } } return content; } /** * */ private ContentVO getChildVOWithName(Integer parentContentId, String name, Database db) throws Exception { ContentVO contentVO = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.parentContentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(Database.ReadOnly); if(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contentVO = content.getValueObject(); } results.close(); oql.close(); return contentVO; } /** * */ private Content getChildWithName(Integer parentContentId, String name, Database db) throws Exception { Content content = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.parentContent.contentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(); if(results.hasMore()) { content = (ContentImpl)results.next(); } results.close(); oql.close(); return content; } /** * */ /* private Content getChildWithName(Content content, String name, Database db) { for(Iterator i=content.getChildren().iterator(); i.hasNext(); ) { final Content childContent = (Content) i.next(); if(childContent.getName().equals(name)) return childContent; } return null; } */ /** * Recursive methods to get all contentVersions of a given state under the specified parent content. */ public List getContentVOWithParentRecursive(Integer contentId) throws ConstraintException, SystemException { return getContentVOWithParentRecursive(contentId, new ArrayList()); } private List getContentVOWithParentRecursive(Integer contentId, List resultList) throws ConstraintException, SystemException { // Get the versions of this content. resultList.add(getContentVOWithId(contentId)); // Get the children of this content and do the recursion List childContentList = ContentController.getContentController().getContentChildrenVOList(contentId, null, false); Iterator cit = childContentList.iterator(); while (cit.hasNext()) { ContentVO contentVO = (ContentVO) cit.next(); getContentVOWithParentRecursive(contentVO.getId(), resultList); } return resultList; } public String getContentAttribute(Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId); attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, Integer stateId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, stateId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), stateId, db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } /** * This is a method that gives the user back an newly initialized ValueObject for this entity that the controller * is handling. */ public BaseEntityVO getNewVO() { return new ContentVO(); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId) throws ConstraintException, SystemException, Bug, Exception { return getContentPath(contentId, false, false); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId, boolean includeRootContent, boolean includeRepositoryName) throws ConstraintException, SystemException, Bug, Exception { StringBuffer sb = new StringBuffer(); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); sb.insert(0, contentVO.getName()); while (contentVO.getParentContentId() != null) { contentVO = ContentController.getContentController().getContentVOWithId(contentVO.getParentContentId()); if (includeRootContent || contentVO.getParentContentId() != null) { sb.insert(0, contentVO.getName() + "/"); } } if (includeRepositoryName) { RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(contentVO.getRepositoryId()); if(repositoryVO != null) sb.insert(0, repositoryVO.getName() + " - /"); } return sb.toString(); } public List<ContentVO> getUpcomingExpiringContents(int numberOfWeeks) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfWeeks); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } public List<ContentVO> getUpcomingExpiringContents(int numberOfDays, InfoGluePrincipal principal, String[] excludedContentTypes) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3 AND c.contentVersions.versionModifier = $4"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfDays); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); oql.bind(principal.getName()); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); boolean isValid = true; for(int i=0; i<excludedContentTypes.length; i++) { String contentTypeDefinitionNameToExclude = excludedContentTypes[i]; ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName(contentTypeDefinitionNameToExclude, db); if(content.getContentTypeDefinitionId().equals(ctdVO.getId())) { isValid = false; break; } } if(isValid) contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } /** * This method checks if there are published versions available for the contentVersion. */ public boolean hasPublishedVersion(Integer contentId) { boolean hasPublishedVersion = false; try { ContentVersion contentVersion = ContentVersionController.getContentVersionController().getLatestPublishedContentVersion(contentId); if(contentVersion != null) { hasPublishedVersion = true; } } catch(Exception e){} return hasPublishedVersion; } public List<ContentVO> getRelatedContents(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallback) throws Exception { String qualifyerXML = getContentAttribute(db, contentId, languageId, attributeName, useLanguageFallback); return getRelatedContentsFromXML(qualifyerXML); } public List<SiteNodeVO> getRelatedSiteNodes(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallback) throws Exception { String qualifyerXML = getContentAttribute(db, contentId, languageId, attributeName, useLanguageFallback); return getRelatedSiteNodesFromXML(qualifyerXML); } /** * This method gets the related contents from an XML. */ private String idElementStart = "<id>"; private String idElementEnd = "</id>"; private String idAttribute1Start = "id=\""; private String idAttribute1End = "\""; private String idAttribute2Start = "id='"; private String idAttribute2End = "'"; private List<ContentVO> getRelatedContentsFromXML(String qualifyerXML) { if(logger.isInfoEnabled()) logger.info("qualifyerXML:" + qualifyerXML); Timer t = new Timer(); List<ContentVO> relatedContentVOList = new ArrayList<ContentVO>(); try { if(qualifyerXML != null && !qualifyerXML.equals("")) { String startExpression = idElementStart; String endExpression = idElementEnd; int idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute1Start; idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute2Start; endExpression = idAttribute2End; idIndex = qualifyerXML.indexOf(startExpression); } else { endExpression = idAttribute1End; } } while(idIndex > -1) { int endIndex = qualifyerXML.indexOf(endExpression, idIndex + 4); String id = qualifyerXML.substring(idIndex + 4, endIndex); try { Integer contentId = new Integer(id); relatedContentVOList.add(getContentVOWithId(contentId)); } catch(Exception e) { logger.info("An error occurred when looking up one of the related contents FromXML:" + e.getMessage(), e); } idIndex = qualifyerXML.indexOf(startExpression, idIndex + 5); } } } catch(Exception e) { logger.error("An error occurred trying to get related contents from qualifyerXML " + qualifyerXML + ":" + e.getMessage(), e); } return relatedContentVOList; } /** * This method gets the related pages from an XML. */ private List<SiteNodeVO> getRelatedSiteNodesFromXML(String qualifyerXML) { if(logger.isInfoEnabled()) logger.info("qualifyerXML:" + qualifyerXML); Timer t = new Timer(); List<SiteNodeVO> relatedPages = new ArrayList<SiteNodeVO>(); try { if(qualifyerXML != null && !qualifyerXML.equals("")) { String startExpression = idElementStart; String endExpression = idElementEnd; int idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute1Start; idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute2Start; endExpression = idAttribute2End; idIndex = qualifyerXML.indexOf(startExpression); } else { endExpression = idAttribute1End; } } while(idIndex > -1) { int endIndex = qualifyerXML.indexOf(endExpression, idIndex + 4); String id = qualifyerXML.substring(idIndex + 4, endIndex); try { SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(new Integer(id)); relatedPages.add(siteNodeVO); } catch(Exception e) { logger.info("An error occurred when looking up one of the related Pages FromXML:" + e.getMessage(), e); } idIndex = qualifyerXML.indexOf(startExpression, idIndex + 5); } } } catch(Exception e) { logger.error("An error occurred trying to get related contents from qualifyerXML " + qualifyerXML + ":" + e.getMessage(), e); } return relatedPages; } }
public /*synchronized*/ Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Integer repositoryId, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); if(repositoryId == null) repositoryId = parentContent.getRepository().getRepositoryId(); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); Repository repository = RepositoryController.getController().getRepositoryWithId(repositoryId, db); /* synchronized (controller) { //db.lock(parentContent); */ content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } //} //repository.getContents().add(content); } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Repository repository, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { delete(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. * @throws Exception * @throws Bug */ public void delete(Integer contentId, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws Bug, Exception { ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(infogluePrincipal, contentId); delete(contentVO, infogluePrincipal, forceDelete); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { delete(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { delete(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { /* synchronized (controller) { //db.lock(controller); */ Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { deleteRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /* } */ } else { deleteRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void deleteRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck && !content.getIsDeleted()) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); deleteRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } content.setChildren(new ArrayList()); boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); if(!skipServiceBindings) ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); if(parentIterator != null) parentIterator.remove(); db.remove(content); Map args = new HashMap(); args.put("globalKey", "infoglue"); PropertySet ps = PropertySetManager.getInstance("jdbc", args); ps.remove( "content_" + content.getContentId() + "_allowedContentTypeNames"); ps.remove( "content_" + content.getContentId() + "_defaultContentTypeName"); ps.remove( "content_" + content.getContentId() + "_initialLanguageId"); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method returns true if the content does not have any published contentversions or * are restricted in any other way. */ private static boolean getIsDeletable(Content content, InfoGluePrincipal infogluePrincipal, Database db) throws SystemException { boolean isDeletable = true; if(content.getIsProtected().equals(ContentVO.YES)) { boolean hasAccess = AccessRightController.getController().getIsPrincipalAuthorized(db, infogluePrincipal, "Content.Delete", "" + content.getId()); if(!hasAccess) return false; } Collection contentVersions = content.getContentVersions(); Iterator versionIterator = contentVersions.iterator(); while (versionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)versionIterator.next(); if(contentVersion.getStateId().intValue() == ContentVersionVO.PUBLISHED_STATE.intValue() && contentVersion.getIsActive().booleanValue() == true) { logger.info("The content had a published version so we cannot delete it.."); isDeletable = false; break; } } return isDeletable; } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { markForDeletion(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { markForDeletion(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { markForDeletion(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { markForDeletionRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } } else { markForDeletionRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void markForDeletionRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305", "<br/><br/>" + content.getName() + " (" + content.getId() + ")"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); markForDeletionRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { //ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); //if(!skipServiceBindings) // ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); //if(parentIterator != null) // parentIterator.remove(); content.setIsDeleted(true); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method restored a content. */ public void restoreContent(Integer contentId, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { Content content = getContentWithId(contentId, db); content.setIsDeleted(false); while(content.getParentContent() != null && content.getParentContent().getIsDeleted()) { content = content.getParentContent(); content.setIsDeleted(false); } commitTransaction(db); } catch(Exception e) { rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public ContentVO update(ContentVO contentVO) throws ConstraintException, SystemException { return update(contentVO, null); } public ContentVO update(ContentVO contentVO, Integer contentTypeDefinitionId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); Content content = null; beginTransaction(db); try { content = (Content)getObjectWithId(ContentImpl.class, contentVO.getId(), db); content.setVO(contentVO); if(contentTypeDefinitionId != null) { ContentTypeDefinition contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } public List<LanguageVO> getAvailableLanguagVOListForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException, Exception { //List<LanguageVO> availableLanguageVOList = new ArrayList<LanguageVO>(); Content content = getContentWithId(contentId, db); List<LanguageVO> availableLanguageVOList = LanguageController.getController().getLanguageVOList(content.getRepositoryId(), db); /* if(content != null) { Repository repository = content.getRepository(); if(repository != null) { List availableRepositoryLanguageList = RepositoryLanguageController.getController().getRepositoryLanguageListWithRepositoryId(repository.getId(), db); Iterator i = availableRepositoryLanguageList.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); availableLanguageVOList.add(repositoryLanguage.getLanguage().getValueObject()); } } } */ return availableLanguageVOList; } /* public List getAvailableLanguagesForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException { List availableLanguageVOList = new ArrayList(); Content content = getContentWithId(contentId, db); if(content != null) { Repository repository = content.getRepository(); if(repository != null) { Collection availableLanguages = repository.getRepositoryLanguages(); Iterator i = availableLanguages.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); int position = 0; Iterator availableLanguageVOListIterator = availableLanguageVOList.iterator(); while(availableLanguageVOListIterator.hasNext()) { LanguageVO availableLanguageVO = (LanguageVO)availableLanguageVOListIterator.next(); if(repositoryLanguage.getLanguage().getValueObject().getId().intValue() < availableLanguageVO.getId().intValue()) break; position++; } availableLanguageVOList.add(position, repositoryLanguage.getLanguage().getValueObject()); } } } return availableLanguageVOList; } */ /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); ContentVO parentContentVO = null; beginTransaction(db); try { Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return parentContentVO; } /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId, Database db) throws SystemException, Bug { ContentVO parentContentVO = null; Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); logger.info("CONTENT:" + content.getName()); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); return parentContentVO; } public static void addChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().add(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public static void removeChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().remove(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { moveContent(contentVO, newParentContentId, db); commitTransaction(db); } catch(ConstraintException ce) { logger.error("An error occurred so we should not complete the transaction:" + ce.getMessage()); rollbackTransaction(db); throw new SystemException(ce.getMessage()); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId, Database db) throws ConstraintException, SystemException { ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; Content newParentContent = null; Content oldParentContent = null; //Validation that checks the entire object contentVO.validate(); if(newParentContentId == null) { logger.warn("You must specify the new parent-content......"); throw new ConstraintException("Content.parentContentId", "3303"); } if(contentVO.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot have the content as it's own parent......"); throw new ConstraintException("Content.parentContentId", "3301"); } content = getContentWithId(contentVO.getContentId(), db); oldParentContent = content.getParentContent(); newParentContent = getContentWithId(newParentContentId, db); if(oldParentContent.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot specify the same folder as it originally was located in......"); throw new ConstraintException("Content.parentContentId", "3304"); } Content tempContent = newParentContent.getParentContent(); while(tempContent != null) { if(tempContent.getId().intValue() == content.getId().intValue()) { logger.warn("You cannot move the content to a child under it......"); throw new ConstraintException("Content.parentContentId", "3302"); } tempContent = tempContent.getParentContent(); } oldParentContent.getChildren().remove(content); content.setParentContent((ContentImpl)newParentContent); changeRepositoryRecursive(content, newParentContent.getRepository()); //content.setRepository(newParentContent.getRepository()); newParentContent.getChildren().add(content); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); } /** * Recursively sets the contents repositoryId. * @param content * @param newRepository */ private void changeRepositoryRecursive(Content content, Repository newRepository) { if(content.getRepository().getId().intValue() != newRepository.getId().intValue()) { content.setRepository((RepositoryImpl)newRepository); Iterator childContentsIterator = content.getChildren().iterator(); while(childContentsIterator.hasNext()) { Content childContent = (Content)childContentsIterator.next(); changeRepositoryRecursive(childContent, newRepository); } } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName) throws SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { List result = getContentVOWithContentTypeDefinition(contentTypeDefinitionName, db); commitTransaction(db); return result; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName, Database db) throws SystemException { HashMap arguments = new HashMap(); arguments.put("method", "selectListOnContentTypeName"); List argumentList = new ArrayList(); String[] names = contentTypeDefinitionName.split(","); for(int i = 0; i < names.length; i++) { HashMap argument = new HashMap(); argument.put("contentTypeDefinitionName", names[i]); argumentList.add(argument); } arguments.put("arguments", argumentList); try { return getContentVOList(arguments, db); } catch(SystemException e) { throw e; } catch(Exception e) { throw new SystemException(e.getMessage()); } } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap) throws SystemException, Bug { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getContentVOWithId(contentId)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments); } return contents; } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap, Database db) throws SystemException, Exception { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getSmallContentVOWithId(contentId, db)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments, db); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); List contents = new ArrayList(); beginTransaction(db); try { Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND c.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments, Database db) throws SystemException, Exception { List contents = new ArrayList(); Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND c.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } return contents; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName) throws ConstraintException, SystemException { if(repositoryId == null || repositoryId.intValue() < 1) return null; Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { logger.info("Fetching the root content for the repository " + repositoryId); //OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE is_undefined(c.parentContentId) AND c.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = getRootContent(db, repositoryId, userName, createIfNonExisting); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Database db, Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException, Exception { Content content = null; logger.info("Fetching the root content for the repository " + repositoryId); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { if(createIfNonExisting) { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } } results.close(); oql.close(); return content; } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content createRootContent(Database db, Repository repository, String userName) throws ConstraintException, SystemException, Exception { Content content = null; ContentVO rootContentVO = new ContentVO(); rootContentVO.setCreatorName(userName); rootContentVO.setName(repository.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repository, rootContentVO); return content; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Integer repositoryId, Database db) throws ConstraintException, SystemException, Exception { Content content = null; OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(); this.logger.info("Fetching entity in read/write mode" + repositoryId); if (results.hasMore()) { content = (Content)results.next(); } results.close(); oql.close(); return content; } /** * This method returns a list of the children a content has. */ /* public List getContentChildrenVOList(Integer parentContentId) throws ConstraintException, SystemException { String key = "" + parentContentId; logger.info("key:" + key); List cachedChildContentVOList = (List)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = null; beginTransaction(db); try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } */ /** * This method returns a list of the children a content has. */ public List<ContentVO> getContentChildrenVOList(Integer parentContentId, String[] allowedContentTypeIds, Boolean showDeletedItems) throws ConstraintException, SystemException { String allowedContentTypeIdsString = ""; if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) allowedContentTypeIdsString += "_" + allowedContentTypeIds[i]; } String key = "" + parentContentId + allowedContentTypeIdsString + "_" + showDeletedItems; if(logger.isInfoEnabled()) logger.info("key:" + key); List<ContentVO> cachedChildContentVOList = (List<ContentVO>)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { if(logger.isInfoEnabled()) logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = new ArrayList(); beginTransaction(db); Timer t = new Timer(); /* try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); System.out.println("childrenVOList under:" + content.getName() + ":" + childrenVOList.size()); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } */ try { String contentTypeINClause = ""; if(allowedContentTypeIds != null && allowedContentTypeIds.length > 0) { contentTypeINClause = " AND (content.isBranch = true OR content.contentTypeDefinitionId IN LIST ("; for(int i=0; i < allowedContentTypeIds.length; i++) { if(i > 0) contentTypeINClause += ","; contentTypeINClause += "$" + (i+3); } contentTypeINClause += "))"; } String showDeletedItemsClause = " AND content.isDeleted = $2"; String SQL = "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 " + showDeletedItemsClause + contentTypeINClause + " ORDER BY content.contentId"; //System.out.println("SQL:" + SQL); OQLQuery oql = db.getOQLQuery(SQL); //OQLQuery oql = db.getOQLQuery( "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 ORDER BY content.contentId"); oql.bind(parentContentId); oql.bind(showDeletedItems); if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) { System.out.println("allowedContentTypeIds[i]:" + allowedContentTypeIds[i]); oql.bind(allowedContentTypeIds[i]); } } QueryResults results = oql.execute(Database.ReadOnly); while (results.hasMore()) { Content content = (Content)results.next(); childrenVOList.add(content.getValueObject()); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } /** * This method returns the contentTypeDefinitionVO which is associated with this content. */ public ContentTypeDefinitionVO getContentTypeDefinition(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); ContentTypeDefinitionVO contentTypeDefinitionVO = null; beginTransaction(db); try { ContentVO smallContentVO = getSmallContentVOWithId(contentId, db); if(smallContentVO != null && smallContentVO.getContentTypeDefinitionId() != null) contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(smallContentVO.getContentTypeDefinitionId(), db); /* Content content = getReadOnlyMediumContentWithId(contentId, db); if(content != null && content.getContentTypeDefinition() != null) contentTypeDefinitionVO = content.getContentTypeDefinition().getValueObject(); */ //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentTypeDefinitionVO; } /** * This method reurns a list of available languages for this content. */ public List getRepositoryLanguages(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List languages = null; beginTransaction(db); try { languages = LanguageController.getController().getLanguageVOList(contentId, db); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return languages; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { result = getBoundContents(db, serviceBindingId); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return result; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } public static List getInTransactionBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getController().getReadOnlyServiceBindingWithId(serviceBindingId, db); //ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments, db); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } /** * This method just sorts the list of qualifyers on sortOrder. */ private static List sortQualifyers(Collection qualifyers) { List sortedQualifyers = new ArrayList(); try { Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); int index = 0; Iterator sortedListIterator = sortedQualifyers.iterator(); while(sortedListIterator.hasNext()) { Qualifyer sortedQualifyer = (Qualifyer)sortedListIterator.next(); if(sortedQualifyer.getSortOrder().intValue() > qualifyer.getSortOrder().intValue()) { break; } index++; } sortedQualifyers.add(index, qualifyer); } } catch(Exception e) { logger.warn("The sorting of qualifyers failed:" + e.getMessage(), e); } return sortedQualifyers; } /** * This method returns the contents belonging to a certain repository. */ public List getRepositoryContents(Integer repositoryId, Database db) throws SystemException, Exception { List contents = new ArrayList(); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.repositoryId = $1 ORDER BY c.contentId"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content); } results.close(); oql.close(); return contents; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator) throws SystemException, Exception { ContentVO contentVO = null; Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { contentVO = getContentVOWithPath(repositoryId, path, forceFolders, creator, db); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVO; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { ContentVO content = getRootContent(repositoryId, db).getValueObject(); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; if(!name.equals("")) { final ContentVO childContent = getChildVOWithName(content.getContentId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent.getValueObject(); } } } return content; } public Content getContentWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { Content content = getRootContent(repositoryId, db); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; final Content childContent = getChildWithName(content.getId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { logger.info(" CREATE " + name); ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent; } } return content; } /** * */ private ContentVO getChildVOWithName(Integer parentContentId, String name, Database db) throws Exception { ContentVO contentVO = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.parentContentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(Database.ReadOnly); if(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contentVO = content.getValueObject(); } results.close(); oql.close(); return contentVO; } /** * */ private Content getChildWithName(Integer parentContentId, String name, Database db) throws Exception { Content content = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.parentContent.contentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(); if(results.hasMore()) { content = (ContentImpl)results.next(); } results.close(); oql.close(); return content; } /** * */ /* private Content getChildWithName(Content content, String name, Database db) { for(Iterator i=content.getChildren().iterator(); i.hasNext(); ) { final Content childContent = (Content) i.next(); if(childContent.getName().equals(name)) return childContent; } return null; } */ /** * Recursive methods to get all contentVersions of a given state under the specified parent content. */ public List getContentVOWithParentRecursive(Integer contentId) throws ConstraintException, SystemException { return getContentVOWithParentRecursive(contentId, new ArrayList()); } private List getContentVOWithParentRecursive(Integer contentId, List resultList) throws ConstraintException, SystemException { // Get the versions of this content. resultList.add(getContentVOWithId(contentId)); // Get the children of this content and do the recursion List childContentList = ContentController.getContentController().getContentChildrenVOList(contentId, null, false); Iterator cit = childContentList.iterator(); while (cit.hasNext()) { ContentVO contentVO = (ContentVO) cit.next(); getContentVOWithParentRecursive(contentVO.getId(), resultList); } return resultList; } public String getContentAttribute(Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId); attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, Integer stateId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, stateId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), stateId, db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } /** * This is a method that gives the user back an newly initialized ValueObject for this entity that the controller * is handling. */ public BaseEntityVO getNewVO() { return new ContentVO(); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId) throws ConstraintException, SystemException, Bug, Exception { return getContentPath(contentId, false, false); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId, boolean includeRootContent, boolean includeRepositoryName) throws ConstraintException, SystemException, Bug, Exception { StringBuffer sb = new StringBuffer(); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); sb.insert(0, contentVO.getName()); while (contentVO.getParentContentId() != null) { contentVO = ContentController.getContentController().getContentVOWithId(contentVO.getParentContentId()); if (includeRootContent || contentVO.getParentContentId() != null) { sb.insert(0, contentVO.getName() + "/"); } } if (includeRepositoryName) { RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(contentVO.getRepositoryId()); if(repositoryVO != null) sb.insert(0, repositoryVO.getName() + " - /"); } return sb.toString(); } public List<ContentVO> getUpcomingExpiringContents(int numberOfWeeks) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfWeeks); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } public List<ContentVO> getUpcomingExpiringContents(int numberOfDays, InfoGluePrincipal principal, String[] excludedContentTypes) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3 AND c.contentVersions.versionModifier = $4"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfDays); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); oql.bind(principal.getName()); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); boolean isValid = true; for(int i=0; i<excludedContentTypes.length; i++) { String contentTypeDefinitionNameToExclude = excludedContentTypes[i]; ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName(contentTypeDefinitionNameToExclude, db); if(content.getContentTypeDefinitionId().equals(ctdVO.getId())) { isValid = false; break; } } if(isValid) contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } /** * This method checks if there are published versions available for the contentVersion. */ public boolean hasPublishedVersion(Integer contentId) { boolean hasPublishedVersion = false; try { ContentVersion contentVersion = ContentVersionController.getContentVersionController().getLatestPublishedContentVersion(contentId); if(contentVersion != null) { hasPublishedVersion = true; } } catch(Exception e){} return hasPublishedVersion; } public List<ContentVO> getRelatedContents(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallback) throws Exception { String qualifyerXML = getContentAttribute(db, contentId, languageId, attributeName, useLanguageFallback); return getRelatedContentsFromXML(qualifyerXML); } public List<SiteNodeVO> getRelatedSiteNodes(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallback) throws Exception { String qualifyerXML = getContentAttribute(db, contentId, languageId, attributeName, useLanguageFallback); return getRelatedSiteNodesFromXML(qualifyerXML); } /** * This method gets the related contents from an XML. */ private String idElementStart = "<id>"; private String idElementEnd = "</id>"; private String idAttribute1Start = "id=\""; private String idAttribute1End = "\""; private String idAttribute2Start = "id='"; private String idAttribute2End = "'"; private List<ContentVO> getRelatedContentsFromXML(String qualifyerXML) { if(logger.isInfoEnabled()) logger.info("qualifyerXML:" + qualifyerXML); Timer t = new Timer(); List<ContentVO> relatedContentVOList = new ArrayList<ContentVO>(); try { if(qualifyerXML != null && !qualifyerXML.equals("")) { String startExpression = idElementStart; String endExpression = idElementEnd; int idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute1Start; idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute2Start; endExpression = idAttribute2End; idIndex = qualifyerXML.indexOf(startExpression); } else { endExpression = idAttribute1End; } } while(idIndex > -1) { int endIndex = qualifyerXML.indexOf(endExpression, idIndex + 4); String id = qualifyerXML.substring(idIndex + 4, endIndex); try { Integer contentId = new Integer(id); relatedContentVOList.add(getContentVOWithId(contentId)); } catch(Exception e) { logger.info("An error occurred when looking up one of the related contents FromXML:" + e.getMessage(), e); } idIndex = qualifyerXML.indexOf(startExpression, idIndex + 5); } } } catch(Exception e) { logger.error("An error occurred trying to get related contents from qualifyerXML " + qualifyerXML + ":" + e.getMessage(), e); } return relatedContentVOList; } /** * This method gets the related pages from an XML. */ private List<SiteNodeVO> getRelatedSiteNodesFromXML(String qualifyerXML) { if(logger.isInfoEnabled()) logger.info("qualifyerXML:" + qualifyerXML); Timer t = new Timer(); List<SiteNodeVO> relatedPages = new ArrayList<SiteNodeVO>(); try { if(qualifyerXML != null && !qualifyerXML.equals("")) { String startExpression = idElementStart; String endExpression = idElementEnd; int idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute1Start; idIndex = qualifyerXML.indexOf(startExpression); if(idIndex == -1) { startExpression = idAttribute2Start; endExpression = idAttribute2End; idIndex = qualifyerXML.indexOf(startExpression); } else { endExpression = idAttribute1End; } } while(idIndex > -1) { int endIndex = qualifyerXML.indexOf(endExpression, idIndex + 4); String id = qualifyerXML.substring(idIndex + 4, endIndex); try { SiteNodeVO siteNodeVO = SiteNodeController.getController().getSiteNodeVOWithId(new Integer(id)); relatedPages.add(siteNodeVO); } catch(Exception e) { logger.info("An error occurred when looking up one of the related Pages FromXML:" + e.getMessage(), e); } idIndex = qualifyerXML.indexOf(startExpression, idIndex + 5); } } } catch(Exception e) { logger.error("An error occurred trying to get related contents from qualifyerXML " + qualifyerXML + ":" + e.getMessage(), e); } return relatedPages; } }
diff --git a/opal-gwt-client/src/test/java/org/obiba/opal/client/presenter/DataExportPresenterTest.java b/opal-gwt-client/src/test/java/org/obiba/opal/client/presenter/DataExportPresenterTest.java index fe642920a..cf2e84fe1 100644 --- a/opal-gwt-client/src/test/java/org/obiba/opal/client/presenter/DataExportPresenterTest.java +++ b/opal-gwt-client/src/test/java/org/obiba/opal/client/presenter/DataExportPresenterTest.java @@ -1,109 +1,110 @@ /******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.client.presenter; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import net.customware.gwt.presenter.client.EventBus; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.obiba.opal.web.gwt.app.client.presenter.DataExportPresenter; import org.obiba.opal.web.gwt.app.client.widgets.event.FileSelectionEvent; import org.obiba.opal.web.gwt.app.client.widgets.event.FileSelectionUpdateEvent; import org.obiba.opal.web.gwt.app.client.widgets.event.TableListUpdateEvent; import org.obiba.opal.web.gwt.app.client.widgets.event.TableSelectionEvent; import org.obiba.opal.web.gwt.app.client.widgets.presenter.FileSelectionPresenter; import org.obiba.opal.web.gwt.app.client.widgets.presenter.TableListPresenter; import org.obiba.opal.web.gwt.rest.client.ResourceCallback; import org.obiba.opal.web.gwt.rest.client.ResourceRequestBuilder; import org.obiba.opal.web.gwt.test.AbstractGwtTestSetup; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.GwtEvent.Type; public class DataExportPresenterTest extends AbstractGwtTestSetup { private EventBus eventBusMock; private DataExportPresenter.Display displayMock; private DataExportPresenter exportPresenter; private TableListPresenter.Display tableListDisplayMock; private TableListPresenter tableListPresenter; private FileSelectionPresenter.Display fileSelectionDisplayMock; private FileSelectionPresenter fileSelectionPresenter; @Before public void setUp() { displayMock = createMock(DataExportPresenter.Display.class); eventBusMock = createMock(EventBus.class); tableListDisplayMock = createMock(TableListPresenter.Display.class); tableListPresenter = new TableListPresenter(tableListDisplayMock, eventBusMock); fileSelectionDisplayMock = createMock(FileSelectionPresenter.Display.class); fileSelectionPresenter = new FileSelectionPresenter(fileSelectionDisplayMock, eventBusMock); exportPresenter = new DataExportPresenter(displayMock, eventBusMock, tableListPresenter, fileSelectionPresenter); } @Test public void testThatEventHandlersAreAddedToUIComponents() { HandlerRegistration handlerRegistrationMock = createMock(HandlerRegistration.class); // Make sure that handlers are added to the event bus expect(eventBusMock.addHandler((Type<TableSelectionEvent.Handler>) EasyMock.anyObject(), (TableSelectionEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<FileSelectionEvent.Handler>) EasyMock.anyObject(), (FileSelectionEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<TableListUpdateEvent.Handler>) EasyMock.anyObject(), (TableListUpdateEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<FileSelectionUpdateEvent.Handler>) EasyMock.anyObject(), (FileSelectionUpdateEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); // Make sure that a ClickHandler is added to the Submit button expect(displayMock.addSubmitClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); expect(displayMock.addJobLinkClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); expect(tableListDisplayMock.addRemoveClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(tableListDisplayMock.addAddClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(fileSelectionDisplayMock.addBrowseClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); displayMock.setTableWidgetDisplay(tableListDisplayMock); expect(displayMock.getFileFormat()).andReturn("csv"); displayMock.setFileWidgetDisplay(fileSelectionDisplayMock); expect(displayMock.addFileFormatChangeHandler((ChangeHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(displayMock.addDestinationFileClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(displayMock.addDestinationDatasourceClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); + expect(displayMock.addWithVariablesClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); // Expects that the presenter makes these calls to the server when it binds itself ResourceRequestBuilder mockRequestBuilder = mockBridge.addMock(ResourceRequestBuilder.class); expect(mockRequestBuilder.forResource("/datasources")).andReturn(mockRequestBuilder).once(); expect(mockRequestBuilder.get()).andReturn(mockRequestBuilder).anyTimes(); expect(mockRequestBuilder.withCallback((ResourceCallback) EasyMock.anyObject())).andReturn(mockRequestBuilder).anyTimes(); expect(mockRequestBuilder.forResource("/functional-units")).andReturn(mockRequestBuilder).once(); mockRequestBuilder.send(); EasyMock.expectLastCall().anyTimes(); replay(eventBusMock, tableListDisplayMock, fileSelectionDisplayMock, displayMock, mockRequestBuilder); exportPresenter.bind(); verify(eventBusMock, tableListDisplayMock, fileSelectionDisplayMock, displayMock, mockRequestBuilder); } }
true
true
public void testThatEventHandlersAreAddedToUIComponents() { HandlerRegistration handlerRegistrationMock = createMock(HandlerRegistration.class); // Make sure that handlers are added to the event bus expect(eventBusMock.addHandler((Type<TableSelectionEvent.Handler>) EasyMock.anyObject(), (TableSelectionEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<FileSelectionEvent.Handler>) EasyMock.anyObject(), (FileSelectionEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<TableListUpdateEvent.Handler>) EasyMock.anyObject(), (TableListUpdateEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<FileSelectionUpdateEvent.Handler>) EasyMock.anyObject(), (FileSelectionUpdateEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); // Make sure that a ClickHandler is added to the Submit button expect(displayMock.addSubmitClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); expect(displayMock.addJobLinkClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); expect(tableListDisplayMock.addRemoveClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(tableListDisplayMock.addAddClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(fileSelectionDisplayMock.addBrowseClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); displayMock.setTableWidgetDisplay(tableListDisplayMock); expect(displayMock.getFileFormat()).andReturn("csv"); displayMock.setFileWidgetDisplay(fileSelectionDisplayMock); expect(displayMock.addFileFormatChangeHandler((ChangeHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(displayMock.addDestinationFileClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(displayMock.addDestinationDatasourceClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); // Expects that the presenter makes these calls to the server when it binds itself ResourceRequestBuilder mockRequestBuilder = mockBridge.addMock(ResourceRequestBuilder.class); expect(mockRequestBuilder.forResource("/datasources")).andReturn(mockRequestBuilder).once(); expect(mockRequestBuilder.get()).andReturn(mockRequestBuilder).anyTimes(); expect(mockRequestBuilder.withCallback((ResourceCallback) EasyMock.anyObject())).andReturn(mockRequestBuilder).anyTimes(); expect(mockRequestBuilder.forResource("/functional-units")).andReturn(mockRequestBuilder).once(); mockRequestBuilder.send(); EasyMock.expectLastCall().anyTimes(); replay(eventBusMock, tableListDisplayMock, fileSelectionDisplayMock, displayMock, mockRequestBuilder); exportPresenter.bind(); verify(eventBusMock, tableListDisplayMock, fileSelectionDisplayMock, displayMock, mockRequestBuilder); }
public void testThatEventHandlersAreAddedToUIComponents() { HandlerRegistration handlerRegistrationMock = createMock(HandlerRegistration.class); // Make sure that handlers are added to the event bus expect(eventBusMock.addHandler((Type<TableSelectionEvent.Handler>) EasyMock.anyObject(), (TableSelectionEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<FileSelectionEvent.Handler>) EasyMock.anyObject(), (FileSelectionEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<TableListUpdateEvent.Handler>) EasyMock.anyObject(), (TableListUpdateEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); expect(eventBusMock.addHandler((Type<FileSelectionUpdateEvent.Handler>) EasyMock.anyObject(), (FileSelectionUpdateEvent.Handler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).once(); // Make sure that a ClickHandler is added to the Submit button expect(displayMock.addSubmitClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); expect(displayMock.addJobLinkClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); expect(tableListDisplayMock.addRemoveClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(tableListDisplayMock.addAddClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(fileSelectionDisplayMock.addBrowseClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock).atLeastOnce(); displayMock.setTableWidgetDisplay(tableListDisplayMock); expect(displayMock.getFileFormat()).andReturn("csv"); displayMock.setFileWidgetDisplay(fileSelectionDisplayMock); expect(displayMock.addFileFormatChangeHandler((ChangeHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(displayMock.addDestinationFileClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(displayMock.addDestinationDatasourceClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); expect(displayMock.addWithVariablesClickHandler((ClickHandler) EasyMock.anyObject())).andReturn(handlerRegistrationMock); // Expects that the presenter makes these calls to the server when it binds itself ResourceRequestBuilder mockRequestBuilder = mockBridge.addMock(ResourceRequestBuilder.class); expect(mockRequestBuilder.forResource("/datasources")).andReturn(mockRequestBuilder).once(); expect(mockRequestBuilder.get()).andReturn(mockRequestBuilder).anyTimes(); expect(mockRequestBuilder.withCallback((ResourceCallback) EasyMock.anyObject())).andReturn(mockRequestBuilder).anyTimes(); expect(mockRequestBuilder.forResource("/functional-units")).andReturn(mockRequestBuilder).once(); mockRequestBuilder.send(); EasyMock.expectLastCall().anyTimes(); replay(eventBusMock, tableListDisplayMock, fileSelectionDisplayMock, displayMock, mockRequestBuilder); exportPresenter.bind(); verify(eventBusMock, tableListDisplayMock, fileSelectionDisplayMock, displayMock, mockRequestBuilder); }
diff --git a/src/bspkrs/floatingruins/WorldGenFloatingIslandRuin.java b/src/bspkrs/floatingruins/WorldGenFloatingIslandRuin.java index 42583d3..45205e4 100644 --- a/src/bspkrs/floatingruins/WorldGenFloatingIslandRuin.java +++ b/src/bspkrs/floatingruins/WorldGenFloatingIslandRuin.java @@ -1,999 +1,999 @@ package bspkrs.floatingruins; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.entity.monster.EntitySlime; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntityMobSpawner; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.gen.feature.WorldGenerator; import bspkrs.util.CommonUtils; public class WorldGenFloatingIslandRuin extends WorldGenerator { private final int numberOfItems; private final String stringOfIds; private final String spawnerDefault; private final String spawnerDesert; private final String spawnerForest; private final String spawnerHills; private final String spawnerPlains; private final String spawnerSwampland; private final String spawnerTaiga; private final String spawnerOcean; private final String spawnerRiver; private final String spawnerJungle; private final String spawnerIceBiomes; private final String spawnerMushroom; private final String spawnerNearLava; private boolean isLavaNearby; private static ItemStack[] helms = { null, new ItemStack(Item.helmetChain.itemID, 1, 0), new ItemStack(Item.helmetChain.itemID, 1, 0), new ItemStack(Item.helmetChain.itemID, 1, 0), new ItemStack(Item.helmetChain.itemID, 1, 0), null, null, new ItemStack(Item.helmetDiamond.itemID, 1, 0), null, null, new ItemStack(Item.helmetGold.itemID, 1, 0), new ItemStack(Item.helmetGold.itemID, 1, 0), new ItemStack(Item.helmetGold.itemID, 1, 0), new ItemStack(Item.helmetGold.itemID, 1, 0), new ItemStack(Item.helmetGold.itemID, 1, 0), null, null, new ItemStack(Item.helmetLeather.itemID, 1, 0), new ItemStack(Item.helmetLeather.itemID, 1, 0), new ItemStack(Item.helmetLeather.itemID, 1, 0), new ItemStack(Item.helmetLeather.itemID, 1, 0), null, null, new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), null, null, new ItemStack(Item.helmetChain.itemID, 1, 0), new ItemStack(Item.helmetChain.itemID, 1, 0), new ItemStack(Item.helmetChain.itemID, 1, 0), new ItemStack(Item.helmetChain.itemID, 1, 0), new ItemStack(Item.helmetChain.itemID, 1, 0), null, null, new ItemStack(Item.helmetDiamond.itemID, 1, 0), null, null, new ItemStack(Item.helmetGold.itemID, 1, 0), new ItemStack(Item.helmetGold.itemID, 1, 0), new ItemStack(Item.helmetGold.itemID, 1, 0), new ItemStack(Item.helmetGold.itemID, 1, 0), new ItemStack(Item.helmetGold.itemID, 1, 0), null, null, new ItemStack(Item.helmetLeather.itemID, 1, 0), new ItemStack(Item.helmetLeather.itemID, 1, 0), new ItemStack(Item.helmetLeather.itemID, 1, 0), null, null, new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0), new ItemStack(Item.helmetIron.itemID, 1, 0) }; private static ItemStack[] plates = { null, new ItemStack(Item.plateChain.itemID, 1, 0), new ItemStack(Item.plateChain.itemID, 1, 0), new ItemStack(Item.plateChain.itemID, 1, 0), new ItemStack(Item.plateChain.itemID, 1, 0), null, null, new ItemStack(Item.plateDiamond.itemID, 1, 0), null, null, new ItemStack(Item.plateGold.itemID, 1, 0), new ItemStack(Item.plateGold.itemID, 1, 0), new ItemStack(Item.plateGold.itemID, 1, 0), new ItemStack(Item.plateGold.itemID, 1, 0), new ItemStack(Item.plateGold.itemID, 1, 0), null, null, new ItemStack(Item.plateLeather.itemID, 1, 0), new ItemStack(Item.plateLeather.itemID, 1, 0), new ItemStack(Item.plateLeather.itemID, 1, 0), null, null, new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), null, null, new ItemStack(Item.plateChain.itemID, 1, 0), new ItemStack(Item.plateChain.itemID, 1, 0), new ItemStack(Item.plateChain.itemID, 1, 0), new ItemStack(Item.plateChain.itemID, 1, 0), new ItemStack(Item.plateChain.itemID, 1, 0), new ItemStack(Item.plateChain.itemID, 1, 0), null, null, new ItemStack(Item.plateDiamond.itemID, 1, 0), null, null, new ItemStack(Item.plateGold.itemID, 1, 0), new ItemStack(Item.plateGold.itemID, 1, 0), new ItemStack(Item.plateGold.itemID, 1, 0), new ItemStack(Item.plateGold.itemID, 1, 0), new ItemStack(Item.plateGold.itemID, 1, 0), null, null, new ItemStack(Item.plateLeather.itemID, 1, 0), new ItemStack(Item.plateLeather.itemID, 1, 0), new ItemStack(Item.plateLeather.itemID, 1, 0), null, null, new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0), new ItemStack(Item.plateIron.itemID, 1, 0) }; private static ItemStack[] legs = { null, new ItemStack(Item.legsChain.itemID, 1, 0), new ItemStack(Item.legsChain.itemID, 1, 0), new ItemStack(Item.legsChain.itemID, 1, 0), new ItemStack(Item.legsChain.itemID, 1, 0), null, null, new ItemStack(Item.legsDiamond.itemID, 1, 0), null, null, new ItemStack(Item.legsGold.itemID, 1, 0), new ItemStack(Item.legsGold.itemID, 1, 0), new ItemStack(Item.legsGold.itemID, 1, 0), new ItemStack(Item.legsGold.itemID, 1, 0), new ItemStack(Item.legsGold.itemID, 1, 0), null, null, new ItemStack(Item.legsLeather.itemID, 1, 0), new ItemStack(Item.legsLeather.itemID, 1, 0), new ItemStack(Item.legsLeather.itemID, 1, 0), new ItemStack(Item.legsLeather.itemID, 1, 0), null, null, new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), null, null, new ItemStack(Item.legsChain.itemID, 1, 0), new ItemStack(Item.legsChain.itemID, 1, 0), new ItemStack(Item.legsChain.itemID, 1, 0), new ItemStack(Item.legsChain.itemID, 1, 0), new ItemStack(Item.legsChain.itemID, 1, 0), null, null, new ItemStack(Item.legsDiamond.itemID, 1, 0), null, null, new ItemStack(Item.legsGold.itemID, 1, 0), new ItemStack(Item.legsGold.itemID, 1, 0), new ItemStack(Item.legsGold.itemID, 1, 0), new ItemStack(Item.legsGold.itemID, 1, 0), new ItemStack(Item.legsGold.itemID, 1, 0), null, null, new ItemStack(Item.legsLeather.itemID, 1, 0), new ItemStack(Item.legsLeather.itemID, 1, 0), new ItemStack(Item.legsLeather.itemID, 1, 0), null, null, new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0), new ItemStack(Item.legsIron.itemID, 1, 0) }; private static ItemStack[] boots = { null, new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), null, null, new ItemStack(Item.bootsDiamond.itemID, 1, 0), null, null, new ItemStack(Item.bootsGold.itemID, 1, 0), new ItemStack(Item.bootsGold.itemID, 1, 0), new ItemStack(Item.bootsGold.itemID, 1, 0), new ItemStack(Item.bootsGold.itemID, 1, 0), new ItemStack(Item.bootsGold.itemID, 1, 0), null, null, new ItemStack(Item.bootsLeather.itemID, 1, 0), new ItemStack(Item.bootsLeather.itemID, 1, 0), new ItemStack(Item.bootsLeather.itemID, 1, 0), new ItemStack(Item.bootsLeather.itemID, 1, 0), null, null, new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), null, null, new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), new ItemStack(Item.bootsChain.itemID, 1, 0), null, null, new ItemStack(Item.bootsDiamond.itemID, 1, 0), null, null, new ItemStack(Item.bootsGold.itemID, 1, 0), new ItemStack(Item.bootsGold.itemID, 1, 0), new ItemStack(Item.bootsGold.itemID, 1, 0), new ItemStack(Item.bootsGold.itemID, 1, 0), new ItemStack(Item.bootsGold.itemID, 1, 0), null, null, new ItemStack(Item.bootsLeather.itemID, 1, 0), new ItemStack(Item.bootsLeather.itemID, 1, 0), new ItemStack(Item.bootsLeather.itemID, 1, 0), new ItemStack(Item.bootsLeather.itemID, 1, 0), null, null, new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0), new ItemStack(Item.bootsIron.itemID, 1, 0) }; private static ItemStack[] skel_weap = { new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.swordDiamond.itemID, 1, 0), new ItemStack(Item.swordDiamond.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.bow.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0) }; private static ItemStack[] zombie_weap = { new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordDiamond.itemID, 1, 0), new ItemStack(Item.swordDiamond.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordWood.itemID, 1, 0), new ItemStack(Item.swordWood.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordStone.itemID, 1, 0), new ItemStack(Item.swordDiamond.itemID, 1, 0), new ItemStack(Item.swordDiamond.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordGold.itemID, 1, 0), new ItemStack(Item.swordWood.itemID, 1, 0), new ItemStack(Item.swordWood.itemID, 1, 0), new ItemStack(Item.swordWood.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0), new ItemStack(Item.swordIron.itemID, 1, 0) }; public WorldGenFloatingIslandRuin(boolean isLavaNearby) { numberOfItems = FloatingRuins.numberOfItems; stringOfIds = FloatingRuins.stringOfIds; spawnerDefault = FloatingRuins.spawnerDefault; spawnerDesert = FloatingRuins.spawnerDesert; spawnerForest = FloatingRuins.spawnerForest; spawnerHills = FloatingRuins.spawnerHills; spawnerPlains = FloatingRuins.spawnerPlains; spawnerSwampland = FloatingRuins.spawnerSwampland; spawnerTaiga = FloatingRuins.spawnerTaiga; spawnerOcean = FloatingRuins.spawnerOcean; spawnerRiver = FloatingRuins.spawnerOcean; spawnerJungle = FloatingRuins.spawnerJungle; spawnerIceBiomes = FloatingRuins.spawnerIceBiomes; spawnerMushroom = FloatingRuins.spawnerMushroom; spawnerNearLava = FloatingRuins.spawnerNearLava; this.isLavaNearby = isLavaNearby; } @Override public boolean generate(World world, Random random, int x, int y, int z) { setDungeon(world, random, x, y, z); return true; } private void setDungeon(World world, Random random, int x, int y, int z) { BiomeGenBase biomegenbase = world.getWorldChunkManager().getBiomeGenAt(x, z); int dungeonBlock = getDungeonBlock(biomegenbase); if (dungeonBlock == Block.blockSnow.blockID) setIgloo(world, x, y, z, 5, dungeonBlock); else if (dungeonBlock == Block.sandStone.blockID) setPyramid(world, x, y, z, 6, dungeonBlock); else if (dungeonBlock == Block.mushroomCapRed.blockID) CommonUtils.setHugeMushroom(world, random, x, y, z, dungeonBlock); else setBox(world, random, x, y, z, 4, 4, getDungeonBlock(biomegenbase)); setChest(world, random, x, y, z); setSpawner(world, biomegenbase, x, y + 2, z); } private void setChest(World world, Random random, int x, int y, int z) { world.setBlock(x, y, z, Block.chest.blockID, 0, 3); TileEntityChest tileentitychest = (TileEntityChest) world.getBlockTileEntity(x, y, z); addItems(tileentitychest, random); int blockingBlockID = (FloatingRuins.harderDungeons ? Block.bedrock.blockID : Block.obsidian.blockID); world.setBlock(x + 1, y, z, blockingBlockID, 0, 3); world.setBlock(x - 1, y, z, blockingBlockID, 0, 3); world.setBlock(x, y, z + 1, blockingBlockID, 0, 3); world.setBlock(x, y, z - 1, blockingBlockID, 0, 3); world.setBlock(x, y - 1, z, blockingBlockID, 0, 3); if (FloatingRuins.harderDungeons) world.setBlock(x, y + 1, z, Block.obsidian.blockID, 0, 3); else world.setBlock(x, y + 1, z, Block.cobblestone.blockID, 0, 3); } private void setSpawner(World world, BiomeGenBase biomegenbase, int x, int y, int z) { world.setBlock(x, y, z, Block.mobSpawner.blockID, 0, 3); world.setBlock(x + 1, y, z, Block.obsidian.blockID, 0, 3); world.setBlock(x - 1, y, z, Block.obsidian.blockID, 0, 3); world.setBlock(x, y, z + 1, Block.obsidian.blockID, 0, 3); world.setBlock(x, y, z - 1, Block.obsidian.blockID, 0, 3); if (FloatingRuins.harderDungeons) { world.setBlock(x, y - 1, z, Block.obsidian.blockID, 0, 3); world.setBlock(x, y + 1, z, Block.obsidian.blockID, 0, 3); } TileEntityMobSpawner tileEntityMobSpawner = (TileEntityMobSpawner) world.getBlockTileEntity(x, y, z); if (tileEntityMobSpawner != null) { String[] mobIDList; if (FloatingRuins.allowMultiMobSpawners) mobIDList = getSpawnerMobList(world, biomegenbase); else { mobIDList = new String[1]; mobIDList[0] = getSpawnerType(world, biomegenbase, x, z); } if (mobIDList.length == 1 && mobIDList[0].trim().equalsIgnoreCase("Default")) mobIDList = FloatingRuins.spawnerDefault.split(","); // get rid of extra whitespace from list to avoid NPEs for (int i = 0; i < mobIDList.length; i++) mobIDList[i] = mobIDList[i].trim(); NBTTagCompound spawnerNBT = new NBTTagCompound(); tileEntityMobSpawner.writeToNBT(spawnerNBT); NBTTagCompound properties; NBTTagList spawnPotentials = new NBTTagList(); for (int i = 0; i < mobIDList.length; i++) { properties = new NBTTagCompound(); NBTTagCompound potentialSpawn = new NBTTagCompound(); potentialSpawn.setInteger("Weight", world.rand.nextInt(4) + 1); String debug = " +" + mobIDList[i] + " wt(" + potentialSpawn.getInteger("Weight") + ") "; if (mobIDList[i].equals("WitherSkeleton")) { NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = zombie_weap[world.rand.nextInt(zombie_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); for (int j = 0; j < 4; j++) { item = new NBTTagCompound(); equipment.appendTag(item); } properties.setTag("Equipment", equipment); properties.setByte("SkeletonType", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", "Skeleton"); spawnerNBT.setString("EntityId", "Skeleton"); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Wolf")) { properties.setByte("Angry", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } - else if (mobIDList[i].equals("ChargedCreeper") || (mobIDList[i].equals("Creeper") && biomegenbase.canSpawnLightningBolt())) + else if (mobIDList[i].equals("ChargedCreeper")) { properties.setByte("powered", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", "Creeper"); spawnerNBT.setString("EntityId", "Creeper"); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("PigZombie")) { properties.setShort("Anger", (short) (400 + world.rand.nextInt(400))); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Zombie")) { boolean flag = world.rand.nextBoolean(); properties.setByte("isVillager", (byte) (flag ? 1 : 0)); if (flag) { properties.setInteger("ConversionTime", -1); debug += "+V "; } flag = world.rand.nextBoolean(); if (flag) { NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = zombie_weap[world.rand.nextInt(zombie_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = boots[world.rand.nextInt(boots.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = legs[world.rand.nextInt(legs.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = plates[world.rand.nextInt(plates.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = helms[world.rand.nextInt(helms.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); properties.setTag("Equipment", equipment); } potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Skeleton")) { boolean flag = world.rand.nextBoolean(); NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = skel_weap[world.rand.nextInt(skel_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); if (flag) { item = new NBTTagCompound(); equip = boots[world.rand.nextInt(boots.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = legs[world.rand.nextInt(legs.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = plates[world.rand.nextInt(plates.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = helms[world.rand.nextInt(helms.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); } else { for (int j = 0; j < 4; j++) { item = new NBTTagCompound(); equipment.appendTag(item); } } properties.setTag("Equipment", equipment); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else { potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } spawnPotentials.appendTag(potentialSpawn); FloatingRuins.debug(debug); } spawnerNBT.setTag("SpawnPotentials", spawnPotentials); if (FloatingRuins.harderDungeons) { spawnerNBT.setShort("MinSpawnDelay", (short) 80); spawnerNBT.setShort("MaxSpawnDelay", (short) 200); spawnerNBT.setShort("SpawnCount", (short) 6); spawnerNBT.setShort("MaxNearbyEntities", (short) 16); spawnerNBT.setShort("SpawnRange", (short) 7); } tileEntityMobSpawner.readFromNBT(spawnerNBT); } } private int getDungeonBlock(BiomeGenBase biomegenbase) { if (biomegenbase.equals(BiomeGenBase.desert) || biomegenbase.equals(BiomeGenBase.desertHills)) return Block.sandStone.blockID; if (biomegenbase.equals(BiomeGenBase.taiga) || biomegenbase.equals(BiomeGenBase.taigaHills) || isIceBiome(biomegenbase)) return Block.blockSnow.blockID; if (biomegenbase.equals(BiomeGenBase.forest) || biomegenbase.equals(BiomeGenBase.forestHills)) return Block.cobblestone.blockID; if (biomegenbase.equals(BiomeGenBase.extremeHills) || biomegenbase.equals(BiomeGenBase.extremeHillsEdge)) return Block.stone.blockID; if (biomegenbase.equals(BiomeGenBase.plains)) return Block.planks.blockID; if (biomegenbase.equals(BiomeGenBase.swampland)) return Block.cobblestoneMossy.blockID; if (biomegenbase.equals(BiomeGenBase.ocean)) return Block.stoneBrick.blockID; if (biomegenbase.equals(BiomeGenBase.river)) return Block.planks.blockID; if (biomegenbase.equals(BiomeGenBase.jungle) || biomegenbase.equals(BiomeGenBase.jungleHills)) return Block.cobblestoneMossy.blockID; if (isMushroomBiome(biomegenbase)) return Block.mushroomCapRed.blockID; else return Block.brick.blockID; } private boolean isIceBiome(BiomeGenBase biomegenbase) { return biomegenbase.equals(BiomeGenBase.frozenOcean) || biomegenbase.equals(BiomeGenBase.frozenRiver) || biomegenbase.equals(BiomeGenBase.icePlains) || biomegenbase.equals(BiomeGenBase.iceMountains); } private boolean isMushroomBiome(BiomeGenBase biomegenbase) { return biomegenbase.equals(BiomeGenBase.mushroomIsland) || biomegenbase.equals(BiomeGenBase.mushroomIslandShore); } private void addItems(TileEntityChest tileentitychest, Random random) { int i = 0; do { tileentitychest.setInventorySlotContents(random.nextInt(tileentitychest.getSizeInventory()), getItems(random)); } while (++i <= numberOfItems); } private ItemStack getItems(Random random) { String itemStack[] = stringOfIds.split(";")[random.nextInt(stringOfIds.split(";").length)].split(","); int id = 344; int size = 1; int meta = 0; if (itemStack.length > 0) id = CommonUtils.parseInt(itemStack[0].trim()); if (itemStack.length > 1) size = CommonUtils.parseInt(itemStack[1].trim()); if (itemStack.length > 2) meta = CommonUtils.parseInt(itemStack[2].trim()); if (Item.itemsList[id] == null) id = 344; if (!Item.itemsList[id].getHasSubtypes() && meta != 0) meta = 0; return new ItemStack(id, size, meta); } public String getSpawnerType(World world, BiomeGenBase biomegenbase, int x, int z) { if (isLavaNearby) return getMobString(spawnerNearLava, world, x, z); if (biomegenbase.equals(BiomeGenBase.desert) || biomegenbase.equals(BiomeGenBase.desertHills)) return getMobString(spawnerDesert, world, x, z); if (biomegenbase.equals(BiomeGenBase.forest) || biomegenbase.equals(BiomeGenBase.forestHills)) return getMobString(spawnerForest, world, x, z); if (biomegenbase.equals(BiomeGenBase.plains)) return getMobString(spawnerPlains, world, x, z); if (biomegenbase.equals(BiomeGenBase.swampland)) return getMobString(spawnerSwampland, world, x, z); if (biomegenbase.equals(BiomeGenBase.taiga) || biomegenbase.equals(BiomeGenBase.taigaHills)) return getMobString(spawnerTaiga, world, x, z); if (biomegenbase.equals(BiomeGenBase.extremeHills) || biomegenbase.equals(BiomeGenBase.extremeHillsEdge)) return getMobString(spawnerHills, world, x, z); if (biomegenbase.equals(BiomeGenBase.ocean)) return getMobString(spawnerOcean, world, x, z); if (biomegenbase.equals(BiomeGenBase.river)) return getMobString(spawnerRiver, world, x, z); if (biomegenbase.equals(BiomeGenBase.jungle) || biomegenbase.equals(BiomeGenBase.jungleHills)) return getMobString(spawnerJungle, world, x, z); if (isIceBiome(biomegenbase)) return getMobString(spawnerIceBiomes, world, x, z); if (isMushroomBiome(biomegenbase)) return getMobString(spawnerMushroom, world, x, z); else return getMobString(spawnerDefault, world, x, z); } public String[] getSpawnerMobList(World world, BiomeGenBase biomegenbase) { if (isLavaNearby) return spawnerNearLava.split(","); if (biomegenbase.equals(BiomeGenBase.desert) || biomegenbase.equals(BiomeGenBase.desertHills)) return spawnerDesert.split(","); if (biomegenbase.equals(BiomeGenBase.forest) || biomegenbase.equals(BiomeGenBase.forestHills)) return spawnerForest.split(","); if (biomegenbase.equals(BiomeGenBase.plains)) return spawnerPlains.split(","); if (biomegenbase.equals(BiomeGenBase.swampland)) return spawnerSwampland.split(","); if (biomegenbase.equals(BiomeGenBase.taiga) || biomegenbase.equals(BiomeGenBase.taigaHills)) return spawnerTaiga.split(","); if (biomegenbase.equals(BiomeGenBase.extremeHills) || biomegenbase.equals(BiomeGenBase.extremeHillsEdge)) return spawnerHills.split(","); if (biomegenbase.equals(BiomeGenBase.ocean)) return spawnerOcean.split(","); if (biomegenbase.equals(BiomeGenBase.river)) return spawnerRiver.split(","); if (biomegenbase.equals(BiomeGenBase.jungle) || biomegenbase.equals(BiomeGenBase.jungleHills)) return spawnerJungle.split(","); if (isIceBiome(biomegenbase)) return spawnerIceBiomes.split(","); if (isMushroomBiome(biomegenbase)) return spawnerMushroom.split(","); else return spawnerDefault.split(","); } private String getMobString(String s, World world, int x, int z) { Random random = new Random(); if (s.equalsIgnoreCase("default")) return getMobString(spawnerDefault, world, x, z); else { String mob = s.split(",")[random.nextInt(s.split(",").length)].trim(); if (mob.equalsIgnoreCase("slime") && !(new EntitySlime(world)).getCanSpawnHere()) return getMobString(spawnerDefault, world, x, z); return mob; } } public void setBox(World world, Random random, int xIn, int yIn, int zIn, int width, int height, int blockID) { for (int x = -width; x <= width; x++) for (int y = height; y >= -height; y--) for (int z = -width; z <= width; z++) { if (y == height || (Math.abs(x) == width && Math.abs(z) == width && y >= 0)) { world.setBlock(x + xIn, y + yIn, z + zIn, Block.stoneBrick.blockID, 0, 3); world.setBlock(x + xIn, y + yIn + 1, z + zIn, (FloatingRuins.harderDungeons ? Block.bedrock.blockID : Block.stoneBrick.blockID), 0, 3); } if (y >= 1 && ((Math.abs(x) == width) ^ (Math.abs(z) == width))) world.setBlock(x + xIn, y + yIn, z + zIn, blockID, 0, 3); if (y > 0 && y < height && Math.abs(z) < width && Math.abs(x) < width) world.setBlock(x + xIn, y + yIn, z + zIn, 0, 0, 3); if (y == -1 || y == 0) world.setBlock(x + xIn, y + yIn, z + zIn, Block.stoneBrick.blockID, 0, 3); if (y < -1) { int yg = CommonUtils.getHighestGroundBlock(world, x + xIn, y + yIn, z + zIn); if ((Math.abs(x) == width || Math.abs(z) == width) && !world.isBlockNormalCube(x + xIn, y + yIn, z + zIn) && yg < y + yIn && yg >= yIn - height) world.setBlock(x + xIn, y + yIn, z + zIn, Block.stoneBrick.blockID, 0, 3); } } } private void setIgloo(World world, int xIn, int yIn, int zIn, int range, int blockID) { for (int x = -range; x <= range; x++) for (int y = -range; y <= range; y++) for (int z = -range; z <= range; z++) { int dist = (int) Math.round(Math.sqrt(CommonUtils.sqr(x) + CommonUtils.sqr(y) + CommonUtils.sqr(z))); if (dist <= range) { if (y >= 0) { if (dist == range) world.setBlock(x + xIn, y + yIn, z + zIn, (FloatingRuins.harderDungeons && y > 2 ? Block.bedrock.blockID : blockID), 0, 3); // For wolves if (y == 0 && dist < range) world.setBlock(x + xIn, y + yIn, z + zIn, Block.grass.blockID, 0, 3); if (y > 0 && dist < range) { world.setBlock(x + xIn, y + yIn, z + zIn, 0, 0, 3); if (y == 1) world.setBlock(x + xIn, y + yIn, z + zIn, Block.snow.blockID, 0, 3); } } else { if (y == -1) world.setBlock(x + xIn, yIn - 1, z + zIn, blockID, 0, 3); int yg = CommonUtils.getHighestGroundBlock(world, x + xIn, y + yIn, z + zIn); if (dist == range && !world.isBlockNormalCube(x + xIn, y + yIn, z + zIn) && yg < y + yIn && yg >= yIn - range) world.setBlock(x + xIn, y + yIn, z + zIn, blockID, 0, 3); } } } } private void setPyramid(World world, int xIn, int yIn, int zIn, int range, int blockID) { for (int x = -range; x <= range; x++) for (int y = -range; y <= range; y++) for (int z = -range; z <= range; z++) { if (y >= 0) { if ((Math.abs(x) == range - y && Math.abs(x) >= Math.abs(z)) || (Math.abs(z) == range - y && Math.abs(z) >= Math.abs(x)) || y == 0) world.setBlock(xIn + x, y + yIn, zIn + z, (FloatingRuins.harderDungeons && y > 2 ? Block.bedrock.blockID : blockID), 0, 3); else if ((Math.abs(x) < range - y && Math.abs(x) >= Math.abs(z)) || (Math.abs(z) < range - y && Math.abs(z) >= Math.abs(x))) world.setBlock(xIn + x, y + yIn, zIn + z, 0, 0, 3); } else { if (y == -1) world.setBlock(x + xIn, y + yIn, z + zIn, blockID, 0, 3); int yg = CommonUtils.getHighestGroundBlock(world, x + xIn, y + yIn, z + zIn); if ((Math.abs(x) == range || Math.abs(z) == range) && !world.isBlockNormalCube(x + xIn, y + yIn, z + zIn) && yg < y + yIn && yg >= yIn - range) world.setBlock(x + xIn, y + yIn, z + zIn, blockID, 0, 3); } } } }
true
true
private void setSpawner(World world, BiomeGenBase biomegenbase, int x, int y, int z) { world.setBlock(x, y, z, Block.mobSpawner.blockID, 0, 3); world.setBlock(x + 1, y, z, Block.obsidian.blockID, 0, 3); world.setBlock(x - 1, y, z, Block.obsidian.blockID, 0, 3); world.setBlock(x, y, z + 1, Block.obsidian.blockID, 0, 3); world.setBlock(x, y, z - 1, Block.obsidian.blockID, 0, 3); if (FloatingRuins.harderDungeons) { world.setBlock(x, y - 1, z, Block.obsidian.blockID, 0, 3); world.setBlock(x, y + 1, z, Block.obsidian.blockID, 0, 3); } TileEntityMobSpawner tileEntityMobSpawner = (TileEntityMobSpawner) world.getBlockTileEntity(x, y, z); if (tileEntityMobSpawner != null) { String[] mobIDList; if (FloatingRuins.allowMultiMobSpawners) mobIDList = getSpawnerMobList(world, biomegenbase); else { mobIDList = new String[1]; mobIDList[0] = getSpawnerType(world, biomegenbase, x, z); } if (mobIDList.length == 1 && mobIDList[0].trim().equalsIgnoreCase("Default")) mobIDList = FloatingRuins.spawnerDefault.split(","); // get rid of extra whitespace from list to avoid NPEs for (int i = 0; i < mobIDList.length; i++) mobIDList[i] = mobIDList[i].trim(); NBTTagCompound spawnerNBT = new NBTTagCompound(); tileEntityMobSpawner.writeToNBT(spawnerNBT); NBTTagCompound properties; NBTTagList spawnPotentials = new NBTTagList(); for (int i = 0; i < mobIDList.length; i++) { properties = new NBTTagCompound(); NBTTagCompound potentialSpawn = new NBTTagCompound(); potentialSpawn.setInteger("Weight", world.rand.nextInt(4) + 1); String debug = " +" + mobIDList[i] + " wt(" + potentialSpawn.getInteger("Weight") + ") "; if (mobIDList[i].equals("WitherSkeleton")) { NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = zombie_weap[world.rand.nextInt(zombie_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); for (int j = 0; j < 4; j++) { item = new NBTTagCompound(); equipment.appendTag(item); } properties.setTag("Equipment", equipment); properties.setByte("SkeletonType", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", "Skeleton"); spawnerNBT.setString("EntityId", "Skeleton"); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Wolf")) { properties.setByte("Angry", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("ChargedCreeper") || (mobIDList[i].equals("Creeper") && biomegenbase.canSpawnLightningBolt())) { properties.setByte("powered", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", "Creeper"); spawnerNBT.setString("EntityId", "Creeper"); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("PigZombie")) { properties.setShort("Anger", (short) (400 + world.rand.nextInt(400))); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Zombie")) { boolean flag = world.rand.nextBoolean(); properties.setByte("isVillager", (byte) (flag ? 1 : 0)); if (flag) { properties.setInteger("ConversionTime", -1); debug += "+V "; } flag = world.rand.nextBoolean(); if (flag) { NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = zombie_weap[world.rand.nextInt(zombie_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = boots[world.rand.nextInt(boots.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = legs[world.rand.nextInt(legs.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = plates[world.rand.nextInt(plates.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = helms[world.rand.nextInt(helms.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); properties.setTag("Equipment", equipment); } potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Skeleton")) { boolean flag = world.rand.nextBoolean(); NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = skel_weap[world.rand.nextInt(skel_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); if (flag) { item = new NBTTagCompound(); equip = boots[world.rand.nextInt(boots.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = legs[world.rand.nextInt(legs.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = plates[world.rand.nextInt(plates.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = helms[world.rand.nextInt(helms.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); } else { for (int j = 0; j < 4; j++) { item = new NBTTagCompound(); equipment.appendTag(item); } } properties.setTag("Equipment", equipment); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else { potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } spawnPotentials.appendTag(potentialSpawn); FloatingRuins.debug(debug); } spawnerNBT.setTag("SpawnPotentials", spawnPotentials); if (FloatingRuins.harderDungeons) { spawnerNBT.setShort("MinSpawnDelay", (short) 80); spawnerNBT.setShort("MaxSpawnDelay", (short) 200); spawnerNBT.setShort("SpawnCount", (short) 6); spawnerNBT.setShort("MaxNearbyEntities", (short) 16); spawnerNBT.setShort("SpawnRange", (short) 7); } tileEntityMobSpawner.readFromNBT(spawnerNBT); } }
private void setSpawner(World world, BiomeGenBase biomegenbase, int x, int y, int z) { world.setBlock(x, y, z, Block.mobSpawner.blockID, 0, 3); world.setBlock(x + 1, y, z, Block.obsidian.blockID, 0, 3); world.setBlock(x - 1, y, z, Block.obsidian.blockID, 0, 3); world.setBlock(x, y, z + 1, Block.obsidian.blockID, 0, 3); world.setBlock(x, y, z - 1, Block.obsidian.blockID, 0, 3); if (FloatingRuins.harderDungeons) { world.setBlock(x, y - 1, z, Block.obsidian.blockID, 0, 3); world.setBlock(x, y + 1, z, Block.obsidian.blockID, 0, 3); } TileEntityMobSpawner tileEntityMobSpawner = (TileEntityMobSpawner) world.getBlockTileEntity(x, y, z); if (tileEntityMobSpawner != null) { String[] mobIDList; if (FloatingRuins.allowMultiMobSpawners) mobIDList = getSpawnerMobList(world, biomegenbase); else { mobIDList = new String[1]; mobIDList[0] = getSpawnerType(world, biomegenbase, x, z); } if (mobIDList.length == 1 && mobIDList[0].trim().equalsIgnoreCase("Default")) mobIDList = FloatingRuins.spawnerDefault.split(","); // get rid of extra whitespace from list to avoid NPEs for (int i = 0; i < mobIDList.length; i++) mobIDList[i] = mobIDList[i].trim(); NBTTagCompound spawnerNBT = new NBTTagCompound(); tileEntityMobSpawner.writeToNBT(spawnerNBT); NBTTagCompound properties; NBTTagList spawnPotentials = new NBTTagList(); for (int i = 0; i < mobIDList.length; i++) { properties = new NBTTagCompound(); NBTTagCompound potentialSpawn = new NBTTagCompound(); potentialSpawn.setInteger("Weight", world.rand.nextInt(4) + 1); String debug = " +" + mobIDList[i] + " wt(" + potentialSpawn.getInteger("Weight") + ") "; if (mobIDList[i].equals("WitherSkeleton")) { NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = zombie_weap[world.rand.nextInt(zombie_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); for (int j = 0; j < 4; j++) { item = new NBTTagCompound(); equipment.appendTag(item); } properties.setTag("Equipment", equipment); properties.setByte("SkeletonType", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", "Skeleton"); spawnerNBT.setString("EntityId", "Skeleton"); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Wolf")) { properties.setByte("Angry", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("ChargedCreeper")) { properties.setByte("powered", (byte) 1); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", "Creeper"); spawnerNBT.setString("EntityId", "Creeper"); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("PigZombie")) { properties.setShort("Anger", (short) (400 + world.rand.nextInt(400))); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Zombie")) { boolean flag = world.rand.nextBoolean(); properties.setByte("isVillager", (byte) (flag ? 1 : 0)); if (flag) { properties.setInteger("ConversionTime", -1); debug += "+V "; } flag = world.rand.nextBoolean(); if (flag) { NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = zombie_weap[world.rand.nextInt(zombie_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = boots[world.rand.nextInt(boots.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = legs[world.rand.nextInt(legs.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = plates[world.rand.nextInt(plates.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = helms[world.rand.nextInt(helms.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); properties.setTag("Equipment", equipment); } potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else if (mobIDList[i].equals("Skeleton")) { boolean flag = world.rand.nextBoolean(); NBTTagList equipment = new NBTTagList(); NBTTagCompound item = new NBTTagCompound(); debug += "+E:"; ItemStack equip = skel_weap[world.rand.nextInt(skel_weap.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); if (flag) { item = new NBTTagCompound(); equip = boots[world.rand.nextInt(boots.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = legs[world.rand.nextInt(legs.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = plates[world.rand.nextInt(plates.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); item = new NBTTagCompound(); equip = helms[world.rand.nextInt(helms.length)]; if (equip != null) { equip.writeToNBT(item); debug += equip.getItemName() + ";"; } equipment.appendTag(item); } else { for (int j = 0; j < 4; j++) { item = new NBTTagCompound(); equipment.appendTag(item); } } properties.setTag("Equipment", equipment); potentialSpawn.setCompoundTag("Properties", properties); potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } else { potentialSpawn.setString("Type", mobIDList[i]); spawnerNBT.setString("EntityId", mobIDList[i]); spawnerNBT.setCompoundTag("SpawnData", properties); } spawnPotentials.appendTag(potentialSpawn); FloatingRuins.debug(debug); } spawnerNBT.setTag("SpawnPotentials", spawnPotentials); if (FloatingRuins.harderDungeons) { spawnerNBT.setShort("MinSpawnDelay", (short) 80); spawnerNBT.setShort("MaxSpawnDelay", (short) 200); spawnerNBT.setShort("SpawnCount", (short) 6); spawnerNBT.setShort("MaxNearbyEntities", (short) 16); spawnerNBT.setShort("SpawnRange", (short) 7); } tileEntityMobSpawner.readFromNBT(spawnerNBT); } }
diff --git a/jnihds/src/main/uk/ac/starlink/hds/HDSPackage.java b/jnihds/src/main/uk/ac/starlink/hds/HDSPackage.java index 07fead7c6..99347067e 100644 --- a/jnihds/src/main/uk/ac/starlink/hds/HDSPackage.java +++ b/jnihds/src/main/uk/ac/starlink/hds/HDSPackage.java @@ -1,45 +1,45 @@ package uk.ac.starlink.hds; import java.util.logging.Level; import java.util.logging.Logger; /** * Provides information about the status of the JNIHDS package. * This class offers a method which can be invoked to determine whether * the {@link HDSObject} class is available for use. * * @author Mark Taylor (Starlink) */ public class HDSPackage { private static Boolean loaded; private static Logger logger = Logger.getLogger( "uk.ac.starlink.hds" ); /** Private sol constructor to prevent instantiation. */ private HDSPackage() {} /** * Indicates whether the HDSObject class is available or not. * This will return <tt>true</tt> if the JNIHDS classes can be used, * buf <tt>false</tt> if the requisite native code is not * available (the shared library is not on <tt>java.library.path</tt>). * If the classes are not available, then the first time it is invoked * it will write a warning to that effect via the logger. * * @return <tt>true</tt> iff the HDSObject class is available */ public static boolean isAvailable() { if ( loaded == null ) { try { int i = HDSObject.DAT__SZNAM; loaded = Boolean.TRUE; } catch ( LinkageError e ) { logger.log( Level.INFO, e.getMessage(), e ); - logger.warning( "JNIHDS load failed - no HDF/HDS access" ); + logger.warning( "JNIHDS load failed - no NDF/HDS access" ); loaded = Boolean.FALSE; } } return loaded.booleanValue(); } }
true
true
public static boolean isAvailable() { if ( loaded == null ) { try { int i = HDSObject.DAT__SZNAM; loaded = Boolean.TRUE; } catch ( LinkageError e ) { logger.log( Level.INFO, e.getMessage(), e ); logger.warning( "JNIHDS load failed - no HDF/HDS access" ); loaded = Boolean.FALSE; } } return loaded.booleanValue(); }
public static boolean isAvailable() { if ( loaded == null ) { try { int i = HDSObject.DAT__SZNAM; loaded = Boolean.TRUE; } catch ( LinkageError e ) { logger.log( Level.INFO, e.getMessage(), e ); logger.warning( "JNIHDS load failed - no NDF/HDS access" ); loaded = Boolean.FALSE; } } return loaded.booleanValue(); }
diff --git a/tests/org.eclipse.rap.rwt.cluster.test/src/org/eclipse/rap/rwt/cluster/test/UICallBackTestBase.java b/tests/org.eclipse.rap.rwt.cluster.test/src/org/eclipse/rap/rwt/cluster/test/UICallBackTestBase.java index 5f02d0944..5b556d8e2 100644 --- a/tests/org.eclipse.rap.rwt.cluster.test/src/org/eclipse/rap/rwt/cluster/test/UICallBackTestBase.java +++ b/tests/org.eclipse.rap.rwt.cluster.test/src/org/eclipse/rap/rwt/cluster/test/UICallBackTestBase.java @@ -1,166 +1,166 @@ /******************************************************************************* * Copyright (c) 2011 EclipseSource and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * EclipseSource - initial API and implementation ******************************************************************************/ package org.eclipse.rap.rwt.cluster.test; import java.io.IOException; import javax.servlet.http.HttpSession; import junit.framework.TestCase; import org.eclipse.rap.rwt.cluster.test.entrypoints.SessionTimeoutEntryPoint; import org.eclipse.rap.rwt.cluster.test.entrypoints.UICallbackEntryPoint; import org.eclipse.rap.rwt.cluster.testfixture.ClusterTestHelper; import org.eclipse.rap.rwt.cluster.testfixture.client.RWTClient; import org.eclipse.rap.rwt.cluster.testfixture.client.Response; import org.eclipse.rap.rwt.cluster.testfixture.server.IServletEngine; import org.eclipse.rap.rwt.cluster.testfixture.server.IServletEngineFactory; import org.eclipse.rwt.internal.uicallback.UICallBackManager; import org.eclipse.rwt.lifecycle.UICallBack; import org.eclipse.swt.widgets.Display; @SuppressWarnings("restriction") public abstract class UICallBackTestBase extends TestCase { private IServletEngine servletEngine; private RWTClient client; abstract IServletEngineFactory getServletEngineFactory(); public void testUICallbackRequestResponse() throws Exception { servletEngine.start( UICallbackEntryPoint.class ); client.sendStartupRequest(); client.sendInitializationRequest(); HttpSession session = ClusterTestHelper.getFirstSession( servletEngine ); final Display display = ClusterTestHelper.getSessionDisplay( session ); Thread thread = new Thread( new Runnable() { public void run() { sleep( 2000 ); UICallBack.runNonUIThreadWithFakeContext( display, new Runnable() { public void run() { UICallBackManager uiCallBackManager = UICallBackManager.getInstance(); uiCallBackManager.setRequestCheckInterval( 500 ); uiCallBackManager.setHasRunnables( true ); uiCallBackManager.releaseBlockedRequest(); } } ); } } ); thread.setDaemon( true ); thread.start(); Response response = client.sendUICallBackRequest( 0 ); thread.join(); String expected = "\"target\": \"uicb\",\n\"action\": \"call\",\n\"method\": \"sendUIRequest\""; - assertEquals( expected, response.getContentText().trim() ); + assertTrue( response.getContentText().trim().indexOf( expected ) != -1 ); } public void testAbortConnectionDuringUICallbackRequest() throws Exception { servletEngine.start( UICallbackEntryPoint.class ); client.sendStartupRequest(); client.sendInitializationRequest(); configureCallbackRequestCheckInterval( 400 ); try { client.sendUICallBackRequest( 200 ); fail(); } catch( IOException expected ) { assertEquals( "Read timed out", expected.getMessage() ); } Thread.sleep( 800 ); UICallBackManager uiCallBackManager = getUICallBackManager(); assertFalse( uiCallBackManager.isCallBackRequestBlocked() ); } public void testUICallBackRequestDoesNotKeepSessionAlive() throws Exception { servletEngine.start( SessionTimeoutEntryPoint.class ); client.sendStartupRequest(); client.sendInitializationRequest(); getUICallBackManager().setRequestCheckInterval( 100 ); asyncSendUICallBackRequest(); Thread.sleep( SessionTimeoutEntryPoint.SESSION_SWEEP_INTERVAL ); assertTrue( SessionTimeoutEntryPoint.isSessionInvalidated() ); } public void testUICallBackRequestDoesNotPreventEngineShutdown() throws Exception { servletEngine.start( SessionTimeoutEntryPoint.class ); client.sendStartupRequest(); client.sendInitializationRequest(); UICallBackManager uiCallBackManager = getUICallBackManager(); asyncSendUICallBackRequest(); while( !uiCallBackManager.isCallBackRequestBlocked() ) { Thread.yield(); } servletEngine.stop( 2000 ); assertTrue( SessionTimeoutEntryPoint.isSessionInvalidated() ); } protected void setUp() throws Exception { servletEngine = getServletEngineFactory().createServletEngine(); client = new RWTClient( servletEngine ); } protected void tearDown() throws Exception { servletEngine.stop(); } private UICallBackManager getUICallBackManager() { final UICallBackManager[] result = { null }; HttpSession session = ClusterTestHelper.getFirstSession( servletEngine ); Display display = ClusterTestHelper.getSessionDisplay( session ); UICallBack.runNonUIThreadWithFakeContext( display, new Runnable() { public void run() { result[ 0 ] = UICallBackManager.getInstance(); } } ); return result[ 0 ]; } private void sleep( int duration ) { try { Thread.sleep( duration ); } catch( InterruptedException ie ) { throw new RuntimeException( ie ); } } private void asyncSendUICallBackRequest() { Thread thread = new Thread( new Runnable() { public void run() { try { client.sendUICallBackRequest( 0 ); } catch( IOException ignore ) { } } } ); thread.setDaemon( true ); thread.start(); } private void configureCallbackRequestCheckInterval( final int interval ) { HttpSession session = ClusterTestHelper.getFirstSession( servletEngine ); Display display = ClusterTestHelper.getSessionDisplay( session ); UICallBack.runNonUIThreadWithFakeContext( display, new Runnable() { public void run() { UICallBackManager.getInstance().setRequestCheckInterval( interval ); } } ); } }
true
true
public void testUICallbackRequestResponse() throws Exception { servletEngine.start( UICallbackEntryPoint.class ); client.sendStartupRequest(); client.sendInitializationRequest(); HttpSession session = ClusterTestHelper.getFirstSession( servletEngine ); final Display display = ClusterTestHelper.getSessionDisplay( session ); Thread thread = new Thread( new Runnable() { public void run() { sleep( 2000 ); UICallBack.runNonUIThreadWithFakeContext( display, new Runnable() { public void run() { UICallBackManager uiCallBackManager = UICallBackManager.getInstance(); uiCallBackManager.setRequestCheckInterval( 500 ); uiCallBackManager.setHasRunnables( true ); uiCallBackManager.releaseBlockedRequest(); } } ); } } ); thread.setDaemon( true ); thread.start(); Response response = client.sendUICallBackRequest( 0 ); thread.join(); String expected = "\"target\": \"uicb\",\n\"action\": \"call\",\n\"method\": \"sendUIRequest\""; assertEquals( expected, response.getContentText().trim() ); }
public void testUICallbackRequestResponse() throws Exception { servletEngine.start( UICallbackEntryPoint.class ); client.sendStartupRequest(); client.sendInitializationRequest(); HttpSession session = ClusterTestHelper.getFirstSession( servletEngine ); final Display display = ClusterTestHelper.getSessionDisplay( session ); Thread thread = new Thread( new Runnable() { public void run() { sleep( 2000 ); UICallBack.runNonUIThreadWithFakeContext( display, new Runnable() { public void run() { UICallBackManager uiCallBackManager = UICallBackManager.getInstance(); uiCallBackManager.setRequestCheckInterval( 500 ); uiCallBackManager.setHasRunnables( true ); uiCallBackManager.releaseBlockedRequest(); } } ); } } ); thread.setDaemon( true ); thread.start(); Response response = client.sendUICallBackRequest( 0 ); thread.join(); String expected = "\"target\": \"uicb\",\n\"action\": \"call\",\n\"method\": \"sendUIRequest\""; assertTrue( response.getContentText().trim().indexOf( expected ) != -1 ); }
diff --git a/okapi/connectors/apertium/src/main/java/net/sf/okapi/connectors/apertium/ApertiumMTConnector.java b/okapi/connectors/apertium/src/main/java/net/sf/okapi/connectors/apertium/ApertiumMTConnector.java index db0be1647..a5344cd75 100644 --- a/okapi/connectors/apertium/src/main/java/net/sf/okapi/connectors/apertium/ApertiumMTConnector.java +++ b/okapi/connectors/apertium/src/main/java/net/sf/okapi/connectors/apertium/ApertiumMTConnector.java @@ -1,167 +1,169 @@ /*=========================================================================== Copyright (C) 2009-2011 by the Okapi Framework contributors ----------------------------------------------------------------------------- This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html ===========================================================================*/ package net.sf.okapi.connectors.apertium; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Map; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import net.sf.okapi.common.IParameters; import net.sf.okapi.common.Util; import net.sf.okapi.common.LocaleId; import net.sf.okapi.common.query.MatchType; import net.sf.okapi.common.resource.TextFragment; import net.sf.okapi.lib.translation.BaseConnector; import net.sf.okapi.lib.translation.QueryResult; import net.sf.okapi.lib.translation.QueryUtil; public class ApertiumMTConnector extends BaseConnector { private Parameters params; private JSONParser parser; private QueryUtil util; public ApertiumMTConnector () { params = new Parameters(); util = new QueryUtil(); parser = new JSONParser(); } @Override public String getName () { return "Apertium MT"; } @Override public String getSettingsDisplay () { return String.format("Server: %s\n%s", params.getServer(), (Util.isEmpty(params.getApiKey()) ? "Without API key" : "With API key")); } @Override public void close () { // Nothing to do } @Override public void open () { // Nothing to do } @Override public int query (String plainText) { return query(new TextFragment(plainText)); } /** * Queries the Apertium API. * See http://wiki.apertium.org/wiki/Apertium_web_service for details. * @param fragment the fragment to query. * @return the number of translations (1 or 0). */ @Override public int query (TextFragment fragment) { result = null; current = -1; try { // Check if there is actually text to translate if ( !fragment.hasText(false) ) return 0; // Convert the fragment to coded HTML String qtext = util.toCodedHTML(fragment); // Create the connection and query URL url; if ( Util.isEmpty(params.getApiKey()) ) { url = new URL(params.getServer() + String.format("?format=html&markUnknown=no&q=%s&langpair=%s|%s", URLEncoder.encode(qtext, "UTF-8"), srcCode, trgCode)); } else { url = new URL(params.getServer() + String.format("?key=%s&format=html&markUnknown=no&q=%s&langpair=%s|%s", URLEncoder.encode(params.getApiKey(), "UTF-8"), URLEncoder.encode(qtext, "UTF-8"), srcCode, trgCode)); } URLConnection conn = url.openConnection(); conn.setConnectTimeout(params.getTimeout()*1000); // Get the response JSONObject object = (JSONObject)parser.parse(new InputStreamReader(conn.getInputStream(), "UTF-8")); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)object; @SuppressWarnings("unchecked") Map<String, Object> data = (Map<String, Object>)map.get("responseData"); String res = (String)data.get("translatedText"); if ( res == null ) { // Probably an unsupported pair - return 0; + long code = (Long)map.get("responseStatus"); + res = (String)map.get("responseDetails"); + throw new RuntimeException(String.format("Error code %d: %s.", code, res)); } // Remove extra \n if needed if ( res.endsWith("\n") && !qtext.endsWith("\n")) { res = res.substring(0, res.length()-1); } result = new QueryResult(); result.weight = getWeight(); result.source = fragment; if ( fragment.hasCode() ) { result.target = new TextFragment(util.fromCodedHTML(res, fragment), fragment.getClonedCodes()); } else { result.target = new TextFragment(util.fromCodedHTML(res, fragment)); } result.score = 95; // Arbitrary score for MT result.origin = getName(); result.matchType = MatchType.MT; current = 0; } catch ( Throwable e ) { throw new RuntimeException("Error querying the server." + e.getMessage(), e); } return ((current==0) ? 1 : 0); } @Override protected String toInternalCode (LocaleId standardCode) { String lang = standardCode.getLanguage(); String reg = standardCode.getRegion(); if ( reg != null ) { // Temporary fix for the Aranese case (until we get real LocaleID) if ( reg.equals("aran") ) lang += "_aran"; // Temporary fix for the Brazilian Portuguese case (until we get real LocaleID) if ( reg.equals("br") ) lang += "_BR"; } return lang; } @Override public IParameters getParameters () { return params; } @Override public void setParameters (IParameters params) { this.params = (Parameters)params; } }
true
true
public int query (TextFragment fragment) { result = null; current = -1; try { // Check if there is actually text to translate if ( !fragment.hasText(false) ) return 0; // Convert the fragment to coded HTML String qtext = util.toCodedHTML(fragment); // Create the connection and query URL url; if ( Util.isEmpty(params.getApiKey()) ) { url = new URL(params.getServer() + String.format("?format=html&markUnknown=no&q=%s&langpair=%s|%s", URLEncoder.encode(qtext, "UTF-8"), srcCode, trgCode)); } else { url = new URL(params.getServer() + String.format("?key=%s&format=html&markUnknown=no&q=%s&langpair=%s|%s", URLEncoder.encode(params.getApiKey(), "UTF-8"), URLEncoder.encode(qtext, "UTF-8"), srcCode, trgCode)); } URLConnection conn = url.openConnection(); conn.setConnectTimeout(params.getTimeout()*1000); // Get the response JSONObject object = (JSONObject)parser.parse(new InputStreamReader(conn.getInputStream(), "UTF-8")); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)object; @SuppressWarnings("unchecked") Map<String, Object> data = (Map<String, Object>)map.get("responseData"); String res = (String)data.get("translatedText"); if ( res == null ) { // Probably an unsupported pair return 0; } // Remove extra \n if needed if ( res.endsWith("\n") && !qtext.endsWith("\n")) { res = res.substring(0, res.length()-1); } result = new QueryResult(); result.weight = getWeight(); result.source = fragment; if ( fragment.hasCode() ) { result.target = new TextFragment(util.fromCodedHTML(res, fragment), fragment.getClonedCodes()); } else { result.target = new TextFragment(util.fromCodedHTML(res, fragment)); } result.score = 95; // Arbitrary score for MT result.origin = getName(); result.matchType = MatchType.MT; current = 0; } catch ( Throwable e ) { throw new RuntimeException("Error querying the server." + e.getMessage(), e); } return ((current==0) ? 1 : 0); }
public int query (TextFragment fragment) { result = null; current = -1; try { // Check if there is actually text to translate if ( !fragment.hasText(false) ) return 0; // Convert the fragment to coded HTML String qtext = util.toCodedHTML(fragment); // Create the connection and query URL url; if ( Util.isEmpty(params.getApiKey()) ) { url = new URL(params.getServer() + String.format("?format=html&markUnknown=no&q=%s&langpair=%s|%s", URLEncoder.encode(qtext, "UTF-8"), srcCode, trgCode)); } else { url = new URL(params.getServer() + String.format("?key=%s&format=html&markUnknown=no&q=%s&langpair=%s|%s", URLEncoder.encode(params.getApiKey(), "UTF-8"), URLEncoder.encode(qtext, "UTF-8"), srcCode, trgCode)); } URLConnection conn = url.openConnection(); conn.setConnectTimeout(params.getTimeout()*1000); // Get the response JSONObject object = (JSONObject)parser.parse(new InputStreamReader(conn.getInputStream(), "UTF-8")); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)object; @SuppressWarnings("unchecked") Map<String, Object> data = (Map<String, Object>)map.get("responseData"); String res = (String)data.get("translatedText"); if ( res == null ) { // Probably an unsupported pair long code = (Long)map.get("responseStatus"); res = (String)map.get("responseDetails"); throw new RuntimeException(String.format("Error code %d: %s.", code, res)); } // Remove extra \n if needed if ( res.endsWith("\n") && !qtext.endsWith("\n")) { res = res.substring(0, res.length()-1); } result = new QueryResult(); result.weight = getWeight(); result.source = fragment; if ( fragment.hasCode() ) { result.target = new TextFragment(util.fromCodedHTML(res, fragment), fragment.getClonedCodes()); } else { result.target = new TextFragment(util.fromCodedHTML(res, fragment)); } result.score = 95; // Arbitrary score for MT result.origin = getName(); result.matchType = MatchType.MT; current = 0; } catch ( Throwable e ) { throw new RuntimeException("Error querying the server." + e.getMessage(), e); } return ((current==0) ? 1 : 0); }
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/JsIdentifierNames.java b/src/main/java/com/redhat/ceylon/compiler/js/JsIdentifierNames.java index f9654394..99f72b95 100644 --- a/src/main/java/com/redhat/ceylon/compiler/js/JsIdentifierNames.java +++ b/src/main/java/com/redhat/ceylon/compiler/js/JsIdentifierNames.java @@ -1,316 +1,320 @@ package com.redhat.ceylon.compiler.js; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; /** * Manages the identifier names in the JavaScript code generated for a Ceylon * compilation unit. * * @author Ivo Kasiuk */ public class JsIdentifierNames { private static long uniqueID = 0; private static long nextUID() { if (++uniqueID <= 0) { uniqueID = 1; } return uniqueID; } private static Set<String> reservedWords = new HashSet<String>(); private static Set<String> substitutedMemberNames = new HashSet<String>(); static { // Identifiers that have to be escaped because they are keywords in // JavaScript. We don't have to include identifiers that are also // keywords in Ceylon because no such identifiers can occur in Ceylon // source code anyway. //reservedWords.add("abstract"); reservedWords.add("boolean"); //reservedWords.add("break"); reservedWords.add("byte"); //reservedWords.add("case"); //reservedWords.add("catch"); reservedWords.add("char"); //reservedWords.add("class"); reservedWords.add("const"); //reservedWords.add("continue"); reservedWords.add("debugger"); reservedWords.add("default"); reservedWords.add("delete"); reservedWords.add("do"); reservedWords.add("double"); //reservedWords.add("else"); reservedWords.add("enum"); reservedWords.add("export"); //reservedWords.add("extends"); reservedWords.add("false"); reservedWords.add("final"); //reservedWords.add("finally"); reservedWords.add("float"); //reservedWords.add("for"); //reservedWords.add("function"); reservedWords.add("goto"); //reservedWords.add("if"); reservedWords.add("implements"); //reservedWords.add("import"); //reservedWords.add("in"); reservedWords.add("instanceof"); reservedWords.add("int"); //reservedWords.add("interface"); reservedWords.add("long"); reservedWords.add("native"); reservedWords.add("new"); reservedWords.add("null"); //reservedWords.add("package"); reservedWords.add("private"); reservedWords.add("protected"); reservedWords.add("public"); //reservedWords.add("return"); reservedWords.add("short"); reservedWords.add("static"); //reservedWords.add("super"); //reservedWords.add("switch"); reservedWords.add("synchronized"); //reservedWords.add("this"); //reservedWords.add("throw"); reservedWords.add("throws"); reservedWords.add("transient"); reservedWords.add("true"); //reservedWords.add("try"); reservedWords.add("typeof"); reservedWords.add("var"); //reservedWords.add("void"); reservedWords.add("volatile"); //reservedWords.add("while"); reservedWords.add("with"); // The names of the following members also have to be escaped to avoid // collisions with members of native JavaScript classes in the // implementation of the language module. substitutedMemberNames.add("ceylon.language::String.split"); substitutedMemberNames.add("ceylon.language::String.replace"); substitutedMemberNames.add("ceylon.language::Iterable.filter"); substitutedMemberNames.add("ceylon.language::Iterable.every"); substitutedMemberNames.add("ceylon.language::Iterable.map"); substitutedMemberNames.add("ceylon.language::Iterable.sort"); } /** * Determine the identifier name to be used in the generated JavaScript code * to represent the given declaration. */ public String name(Declaration decl) { return getName(decl, false, false); } /** * Determine a secondary, private identifier name for the given declaration. */ public String privateName(Declaration decl) { return getName(decl, false, true); } /** * Determine the function name to be used in the generated JavaScript code * for the getter of the given declaration. */ public String getter(Declaration decl) { if (decl == null) { return ""; } String name = getName(decl, true, false); return String.format("get%c%s", Character.toUpperCase(name.charAt(0)), name.substring(1)); } /** * Determine the function name to be used in the generated JavaScript code * for the setter of the given declaration. */ public String setter(Declaration decl) { String name = getName(decl, true, false); return String.format("set%c%s", Character.toUpperCase(name.charAt(0)), name.substring(1)); } /** * Determine the identifier to be used in the generated JavaScript code as * an alias for the given package. */ public String moduleAlias(Module pkg) { if (JsCompiler.compilingLanguageModule && pkg.getLanguageModule()==pkg) { //If we're compiling the language module, omit the package name return ""; } StringBuilder sb = new StringBuilder("$$$"); for (String s: pkg.getName()) { sb.append(s.substring(0,1)); } sb.append(getUID(pkg)); return sb.toString(); } /** * Creates a new unique identifier. */ public String createTempVariable(String baseName) { return String.format("%s$%d", baseName, nextUID()); } /** * Creates a new unique identifier. */ public String createTempVariable() { return createTempVariable("tmpvar"); } /** * Determine the identifier to be used for the self variable of the given type. */ public String self(TypeDeclaration decl) { String name = decl.getName(); if (!(decl.isShared() || decl.isToplevel())) { // The identifier will not be used outside the generated .js file, // so we can simply disambiguate it with a numeric ID. name = String.format("%s$%d", name, getUID(decl)); } else { name += nestingSuffix(decl); } return String.format("$$%c%s", Character.toLowerCase(name.charAt(0)), name.substring(1)); } /** * Returns a disambiguation suffix for the given scope. It is guaranteed that * the suffixes generated for two different scopes are different. */ public String scopeSuffix(Scope scope) { return String.format("$$%s", scope.getQualifiedNameString().replace("::","$").replace('.', '$')); } /** * Generates a disambiguation suffix if the given declaration is a nested * declaration whose name may collide with other declarations. * Currently this is required only for types which are nested inside other * types. */ private String nestingSuffix(Declaration decl) { String suffix = ""; if (decl instanceof TypeDeclaration) { // The generated suffix consists of the names of the enclosing types. StringBuilder sb = new StringBuilder(); // Use the original declaration if it's an overriden class: an overriding // member must have the same name as the member it overrides. Scope scope = originalDeclaration(decl).getContainer(); while (scope instanceof TypeDeclaration) { sb.append('$'); sb.append(((TypeDeclaration) scope).getName()); scope = scope.getContainer(); } suffix = sb.toString(); } return suffix; } public void forceName(Declaration decl, String name) { uniqueVarNames.put(decl, name); } private Map<Module, Long> moduleUIDs = new HashMap<Module, Long>(); private Map<Declaration, Long> uniqueVarIDs = new HashMap<Declaration, Long>(); private Map<Declaration, String> uniqueVarNames = new HashMap<Declaration, String>(); private String getName(Declaration decl, boolean forGetterSetter, boolean priv) { if (decl == null) { return null; } String name = decl.getName(); boolean nonLocal = !priv; if (nonLocal) { // check if it's a shared member or a toplevel function nonLocal = (decl.isShared() && decl.isMember()) || (decl.isToplevel() && (forGetterSetter || (decl instanceof Method) || (decl instanceof ClassOrInterface))); } if (nonLocal && (decl instanceof com.redhat.ceylon.compiler.typechecker.model.Class) && Character.isLowerCase(decl.getName().charAt(0))) { // A lower-case class name belongs to an object and is not public. nonLocal = false; } if (nonLocal) { // The identifier might be accessed from other .js files, so it must // be reliably reproducible. In most cases simply using the original // name is ok because otherwise it would result in a name collision in // Ceylon too. We just have to take care of a few exceptions: String suffix = nestingSuffix(decl); if (suffix.length() > 0) { // nested type name += suffix; } else if (!forGetterSetter && reservedWords.contains(name)) { // JavaScript keyword name = '$' + name; } else { Declaration refinedDecl = originalDeclaration(decl); if (substitutedMemberNames.contains(refinedDecl.getQualifiedNameString())) { // member name that could collide with the name of a native // JavaScript class name = '$' + name; } } } else { // The identifier will not be used outside the generated .js file, // so we can simply disambiguate it with a numeric ID. name = uniqueVarNames.get(decl); if (name == null) { name = String.format(priv ? "%s$%d_" : "%s$%d", decl.getName(), getUID(decl)); } } //Fix #204 - same top-level declarations in different packages if (decl.isToplevel() && !decl.getUnit().getPackage().equals(decl.getUnit().getPackage().getModule().getRootPackage())) { String rootName = decl.getUnit().getPackage().getModule().getRootPackage().getNameAsString(); String pkgName = decl.getUnit().getPackage().getNameAsString(); - name += pkgName.substring(rootName.length()).replaceAll("\\.", "\\$"); + rootName = pkgName.substring(rootName.length()).replaceAll("\\.", "\\$"); + if (rootName.charAt(0) != '$') { + rootName = '$' + rootName; + } + name += rootName; } return name; } private Declaration originalDeclaration(Declaration decl) { Declaration refinedDecl = decl; while (true) { Declaration d = refinedDecl.getRefinedDeclaration(); if ((d == null) || (d == refinedDecl)) { break; } refinedDecl = d; } return refinedDecl; } private long getUID(Declaration decl) { Long id = uniqueVarIDs.get(decl); if (id == null) { id = nextUID(); uniqueVarIDs.put(decl, id); } return id; } private long getUID(Module pkg) { Long id = moduleUIDs.get(pkg); if (id == null) { id = nextUID(); moduleUIDs.put(pkg, id); } return id; } }
true
true
private String getName(Declaration decl, boolean forGetterSetter, boolean priv) { if (decl == null) { return null; } String name = decl.getName(); boolean nonLocal = !priv; if (nonLocal) { // check if it's a shared member or a toplevel function nonLocal = (decl.isShared() && decl.isMember()) || (decl.isToplevel() && (forGetterSetter || (decl instanceof Method) || (decl instanceof ClassOrInterface))); } if (nonLocal && (decl instanceof com.redhat.ceylon.compiler.typechecker.model.Class) && Character.isLowerCase(decl.getName().charAt(0))) { // A lower-case class name belongs to an object and is not public. nonLocal = false; } if (nonLocal) { // The identifier might be accessed from other .js files, so it must // be reliably reproducible. In most cases simply using the original // name is ok because otherwise it would result in a name collision in // Ceylon too. We just have to take care of a few exceptions: String suffix = nestingSuffix(decl); if (suffix.length() > 0) { // nested type name += suffix; } else if (!forGetterSetter && reservedWords.contains(name)) { // JavaScript keyword name = '$' + name; } else { Declaration refinedDecl = originalDeclaration(decl); if (substitutedMemberNames.contains(refinedDecl.getQualifiedNameString())) { // member name that could collide with the name of a native // JavaScript class name = '$' + name; } } } else { // The identifier will not be used outside the generated .js file, // so we can simply disambiguate it with a numeric ID. name = uniqueVarNames.get(decl); if (name == null) { name = String.format(priv ? "%s$%d_" : "%s$%d", decl.getName(), getUID(decl)); } } //Fix #204 - same top-level declarations in different packages if (decl.isToplevel() && !decl.getUnit().getPackage().equals(decl.getUnit().getPackage().getModule().getRootPackage())) { String rootName = decl.getUnit().getPackage().getModule().getRootPackage().getNameAsString(); String pkgName = decl.getUnit().getPackage().getNameAsString(); name += pkgName.substring(rootName.length()).replaceAll("\\.", "\\$"); } return name; }
private String getName(Declaration decl, boolean forGetterSetter, boolean priv) { if (decl == null) { return null; } String name = decl.getName(); boolean nonLocal = !priv; if (nonLocal) { // check if it's a shared member or a toplevel function nonLocal = (decl.isShared() && decl.isMember()) || (decl.isToplevel() && (forGetterSetter || (decl instanceof Method) || (decl instanceof ClassOrInterface))); } if (nonLocal && (decl instanceof com.redhat.ceylon.compiler.typechecker.model.Class) && Character.isLowerCase(decl.getName().charAt(0))) { // A lower-case class name belongs to an object and is not public. nonLocal = false; } if (nonLocal) { // The identifier might be accessed from other .js files, so it must // be reliably reproducible. In most cases simply using the original // name is ok because otherwise it would result in a name collision in // Ceylon too. We just have to take care of a few exceptions: String suffix = nestingSuffix(decl); if (suffix.length() > 0) { // nested type name += suffix; } else if (!forGetterSetter && reservedWords.contains(name)) { // JavaScript keyword name = '$' + name; } else { Declaration refinedDecl = originalDeclaration(decl); if (substitutedMemberNames.contains(refinedDecl.getQualifiedNameString())) { // member name that could collide with the name of a native // JavaScript class name = '$' + name; } } } else { // The identifier will not be used outside the generated .js file, // so we can simply disambiguate it with a numeric ID. name = uniqueVarNames.get(decl); if (name == null) { name = String.format(priv ? "%s$%d_" : "%s$%d", decl.getName(), getUID(decl)); } } //Fix #204 - same top-level declarations in different packages if (decl.isToplevel() && !decl.getUnit().getPackage().equals(decl.getUnit().getPackage().getModule().getRootPackage())) { String rootName = decl.getUnit().getPackage().getModule().getRootPackage().getNameAsString(); String pkgName = decl.getUnit().getPackage().getNameAsString(); rootName = pkgName.substring(rootName.length()).replaceAll("\\.", "\\$"); if (rootName.charAt(0) != '$') { rootName = '$' + rootName; } name += rootName; } return name; }
diff --git a/src/main/java/org/basex/gui/dialog/DialogProps.java b/src/main/java/org/basex/gui/dialog/DialogProps.java index d10444cb0..0b5dc1668 100644 --- a/src/main/java/org/basex/gui/dialog/DialogProps.java +++ b/src/main/java/org/basex/gui/dialog/DialogProps.java @@ -1,213 +1,213 @@ package org.basex.gui.dialog; import static org.basex.core.Text.*; import java.awt.BorderLayout; import java.awt.Font; import java.awt.GridLayout; import org.basex.core.cmd.InfoDB; import org.basex.data.Data; import org.basex.data.DiskData; import org.basex.gui.GUI; import org.basex.gui.layout.BaseXBack; import org.basex.gui.layout.BaseXButton; import org.basex.gui.layout.BaseXCheckBox; import org.basex.gui.layout.BaseXEditor; import org.basex.gui.layout.BaseXLabel; import org.basex.gui.layout.BaseXLayout; import org.basex.gui.layout.BaseXTabs; import org.basex.index.IndexToken.IndexType; import org.basex.util.Token; import org.basex.util.TokenBuilder; /** * Database properties dialog. * * @author BaseX Team 2005-12, BSD License * @author Christian Gruen */ public final class DialogProps extends Dialog { /** Index checkboxes. */ private final BaseXCheckBox[] indexes = new BaseXCheckBox[4]; /** Button panel. */ private final BaseXBack buttons; /** Optimize button. */ private final BaseXButton optimize; /** Resource panel. */ final DialogResources resources; /** Add panel. */ final DialogAdd add; /** Editable full-text options. */ private DialogFT ft; /** Optimize flag. */ private boolean opt; /** * Default constructor. * @param main reference to the main window */ public DialogProps(final GUI main) { super(main, DB_PROPS); panel.setLayout(new BorderLayout(5, 0)); optimize = new BaseXButton(OPTIMIZE_D, this); - buttons = newButtons(optimize, OK, CANCEL); + buttons = newButtons(optimize, B_OK, CANCEL); // resource tree resources = new DialogResources(this); // tab: database info final Data data = gui.context.data(); final BaseXBack tabInfo = new BaseXBack(new BorderLayout(0, 8)).border(8); final Font f = tabInfo.getFont(); final BaseXLabel doc = new BaseXLabel(data.meta.name).border( 0, 0, 5, 0).large(); BaseXLayout.setWidth(doc, 400); tabInfo.add(doc, BorderLayout.NORTH); final String db = InfoDB.db(data.meta, true, false, true); final TokenBuilder info = new TokenBuilder(db); if(data.nspaces.size() != 0) { info.bold().add(NL + NAMESPACES + NL).norm().add(data.nspaces.info()); } final BaseXEditor text = text(info.finish()); text.setFont(f); tabInfo.add(text, BorderLayout.CENTER); // tab: resources add = new DialogAdd(this); final BaseXBack tabRes = add.border(8); // tab: name indexes final BaseXBack tabNames = new BaseXBack(new GridLayout(2, 1, 0, 8)).border(8); tabNames.add(addIndex(true, data)); tabNames.add(addIndex(false, data)); final String[] cb = { PATH_INDEX, TEXT_INDEX, ATTRIBUTE_INDEX, FULLTEXT_INDEX }; final boolean[] val = { data.meta.pathindex, data.meta.textindex, data.meta.attrindex, data.meta.ftxtindex }; final BaseXBack[] panels = new BaseXBack[indexes.length]; for(int i = 0; i < indexes.length; ++i) { indexes[i] = new BaseXCheckBox(cb[i], val[i], 0, this).large(); indexes[i].setEnabled(data instanceof DiskData); panels[i] = new BaseXBack(new BorderLayout()); } // tab: path index final BaseXBack tabPath = new BaseXBack(new GridLayout(1, 1)).border(8); panels[0].add(indexes[0], BorderLayout.NORTH); panels[0].add(text(val[0] ? data.info(IndexType.PATH) : Token.token(H_PATH_INDEX)), BorderLayout.CENTER); tabPath.add(panels[0]); // tab: value indexes final BaseXBack tabValues = new BaseXBack(new GridLayout(2, 1)).border(8); panels[1].add(indexes[1], BorderLayout.NORTH); panels[1].add(text(val[1] ? data.info(IndexType.TEXT) : Token.token(H_TEXT_INDEX)), BorderLayout.CENTER); tabValues.add(panels[1]); panels[2].add(indexes[2], BorderLayout.NORTH); panels[2].add(text(val[2] ? data.info(IndexType.ATTRIBUTE) : Token.token(H_ATTR_INDEX)), BorderLayout.CENTER); tabValues.add(panels[2]); // tab: full-text index final BaseXBack tabFT = new BaseXBack(new GridLayout(1, 1)).border(8); panels[3].add(indexes[3], BorderLayout.NORTH); if(!val[3]) ft = new DialogFT(this, false); panels[3].add(val[3] ? text(data.info(IndexType.FULLTEXT)) : ft, BorderLayout.CENTER); tabFT.add(panels[3]); final BaseXTabs tabs = new BaseXTabs(this); tabs.addTab(GENERAL, tabInfo); tabs.addTab(RESOURCES, tabRes); tabs.addTab(NAMES, tabNames); tabs.addTab(PATH_INDEX, tabPath); tabs.addTab(INDEXES, tabValues); tabs.addTab(FULLTEXT, tabFT); final BaseXBack back = new BaseXBack(new BorderLayout()); back.add(tabs, BorderLayout.CENTER); back.add(buttons, BorderLayout.SOUTH); set(resources, BorderLayout.WEST); set(back, BorderLayout.CENTER); action(null); setResizable(true); setMinimumSize(getPreferredSize()); finish(null); } /** * Adds an index panel. * @param elem element/attribute flag * @param data data reference * @return panel */ private BaseXBack addIndex(final boolean elem, final Data data) { final BaseXBack p = new BaseXBack(new BorderLayout()); String lbl = elem ? ELEMENTS : ATTRIBUTES; if(!data.meta.uptodate) lbl += " (" + OUT_OF_DATE + ')'; p.add(new BaseXLabel(lbl, false, true), BorderLayout.NORTH); final IndexType index = elem ? IndexType.TAG : IndexType.ATTNAME; p.add(text(data.info(index)), BorderLayout.CENTER); return p; } /** * Returns a text box. * @param txt contents * @return text box */ private BaseXEditor text(final byte[] txt) { final BaseXEditor text = new BaseXEditor(false, this); text.setText(txt); BaseXLayout.setHeight(text, 200); return text; } /** * Returns an array with the chosen indexes. * @return check box */ public boolean[] indexes() { final boolean[] in = new boolean[indexes.length]; for(int i = 0; i < indexes.length; ++i) in[i] = indexes[i].isSelected(); return in; } @Override public void action(final Object cmp) { resources.action(cmp); add.action(cmp); opt = cmp == optimize; if(opt) close(); if(ft != null) ft.action(indexes[3].isSelected()); enableOK(buttons, OPTIMIZE_D, !gui.context.data().meta.uptodate); } @Override public void close() { super.close(); if(ft != null) ft.setOptions(); } /** * Returns the optimize flag. * @return flag */ public boolean optimize() { return opt; } }
true
true
public DialogProps(final GUI main) { super(main, DB_PROPS); panel.setLayout(new BorderLayout(5, 0)); optimize = new BaseXButton(OPTIMIZE_D, this); buttons = newButtons(optimize, OK, CANCEL); // resource tree resources = new DialogResources(this); // tab: database info final Data data = gui.context.data(); final BaseXBack tabInfo = new BaseXBack(new BorderLayout(0, 8)).border(8); final Font f = tabInfo.getFont(); final BaseXLabel doc = new BaseXLabel(data.meta.name).border( 0, 0, 5, 0).large(); BaseXLayout.setWidth(doc, 400); tabInfo.add(doc, BorderLayout.NORTH); final String db = InfoDB.db(data.meta, true, false, true); final TokenBuilder info = new TokenBuilder(db); if(data.nspaces.size() != 0) { info.bold().add(NL + NAMESPACES + NL).norm().add(data.nspaces.info()); } final BaseXEditor text = text(info.finish()); text.setFont(f); tabInfo.add(text, BorderLayout.CENTER); // tab: resources add = new DialogAdd(this); final BaseXBack tabRes = add.border(8); // tab: name indexes final BaseXBack tabNames = new BaseXBack(new GridLayout(2, 1, 0, 8)).border(8); tabNames.add(addIndex(true, data)); tabNames.add(addIndex(false, data)); final String[] cb = { PATH_INDEX, TEXT_INDEX, ATTRIBUTE_INDEX, FULLTEXT_INDEX }; final boolean[] val = { data.meta.pathindex, data.meta.textindex, data.meta.attrindex, data.meta.ftxtindex }; final BaseXBack[] panels = new BaseXBack[indexes.length]; for(int i = 0; i < indexes.length; ++i) { indexes[i] = new BaseXCheckBox(cb[i], val[i], 0, this).large(); indexes[i].setEnabled(data instanceof DiskData); panels[i] = new BaseXBack(new BorderLayout()); } // tab: path index final BaseXBack tabPath = new BaseXBack(new GridLayout(1, 1)).border(8); panels[0].add(indexes[0], BorderLayout.NORTH); panels[0].add(text(val[0] ? data.info(IndexType.PATH) : Token.token(H_PATH_INDEX)), BorderLayout.CENTER); tabPath.add(panels[0]); // tab: value indexes final BaseXBack tabValues = new BaseXBack(new GridLayout(2, 1)).border(8); panels[1].add(indexes[1], BorderLayout.NORTH); panels[1].add(text(val[1] ? data.info(IndexType.TEXT) : Token.token(H_TEXT_INDEX)), BorderLayout.CENTER); tabValues.add(panels[1]); panels[2].add(indexes[2], BorderLayout.NORTH); panels[2].add(text(val[2] ? data.info(IndexType.ATTRIBUTE) : Token.token(H_ATTR_INDEX)), BorderLayout.CENTER); tabValues.add(panels[2]); // tab: full-text index final BaseXBack tabFT = new BaseXBack(new GridLayout(1, 1)).border(8); panels[3].add(indexes[3], BorderLayout.NORTH); if(!val[3]) ft = new DialogFT(this, false); panels[3].add(val[3] ? text(data.info(IndexType.FULLTEXT)) : ft, BorderLayout.CENTER); tabFT.add(panels[3]); final BaseXTabs tabs = new BaseXTabs(this); tabs.addTab(GENERAL, tabInfo); tabs.addTab(RESOURCES, tabRes); tabs.addTab(NAMES, tabNames); tabs.addTab(PATH_INDEX, tabPath); tabs.addTab(INDEXES, tabValues); tabs.addTab(FULLTEXT, tabFT); final BaseXBack back = new BaseXBack(new BorderLayout()); back.add(tabs, BorderLayout.CENTER); back.add(buttons, BorderLayout.SOUTH); set(resources, BorderLayout.WEST); set(back, BorderLayout.CENTER); action(null); setResizable(true); setMinimumSize(getPreferredSize()); finish(null); }
public DialogProps(final GUI main) { super(main, DB_PROPS); panel.setLayout(new BorderLayout(5, 0)); optimize = new BaseXButton(OPTIMIZE_D, this); buttons = newButtons(optimize, B_OK, CANCEL); // resource tree resources = new DialogResources(this); // tab: database info final Data data = gui.context.data(); final BaseXBack tabInfo = new BaseXBack(new BorderLayout(0, 8)).border(8); final Font f = tabInfo.getFont(); final BaseXLabel doc = new BaseXLabel(data.meta.name).border( 0, 0, 5, 0).large(); BaseXLayout.setWidth(doc, 400); tabInfo.add(doc, BorderLayout.NORTH); final String db = InfoDB.db(data.meta, true, false, true); final TokenBuilder info = new TokenBuilder(db); if(data.nspaces.size() != 0) { info.bold().add(NL + NAMESPACES + NL).norm().add(data.nspaces.info()); } final BaseXEditor text = text(info.finish()); text.setFont(f); tabInfo.add(text, BorderLayout.CENTER); // tab: resources add = new DialogAdd(this); final BaseXBack tabRes = add.border(8); // tab: name indexes final BaseXBack tabNames = new BaseXBack(new GridLayout(2, 1, 0, 8)).border(8); tabNames.add(addIndex(true, data)); tabNames.add(addIndex(false, data)); final String[] cb = { PATH_INDEX, TEXT_INDEX, ATTRIBUTE_INDEX, FULLTEXT_INDEX }; final boolean[] val = { data.meta.pathindex, data.meta.textindex, data.meta.attrindex, data.meta.ftxtindex }; final BaseXBack[] panels = new BaseXBack[indexes.length]; for(int i = 0; i < indexes.length; ++i) { indexes[i] = new BaseXCheckBox(cb[i], val[i], 0, this).large(); indexes[i].setEnabled(data instanceof DiskData); panels[i] = new BaseXBack(new BorderLayout()); } // tab: path index final BaseXBack tabPath = new BaseXBack(new GridLayout(1, 1)).border(8); panels[0].add(indexes[0], BorderLayout.NORTH); panels[0].add(text(val[0] ? data.info(IndexType.PATH) : Token.token(H_PATH_INDEX)), BorderLayout.CENTER); tabPath.add(panels[0]); // tab: value indexes final BaseXBack tabValues = new BaseXBack(new GridLayout(2, 1)).border(8); panels[1].add(indexes[1], BorderLayout.NORTH); panels[1].add(text(val[1] ? data.info(IndexType.TEXT) : Token.token(H_TEXT_INDEX)), BorderLayout.CENTER); tabValues.add(panels[1]); panels[2].add(indexes[2], BorderLayout.NORTH); panels[2].add(text(val[2] ? data.info(IndexType.ATTRIBUTE) : Token.token(H_ATTR_INDEX)), BorderLayout.CENTER); tabValues.add(panels[2]); // tab: full-text index final BaseXBack tabFT = new BaseXBack(new GridLayout(1, 1)).border(8); panels[3].add(indexes[3], BorderLayout.NORTH); if(!val[3]) ft = new DialogFT(this, false); panels[3].add(val[3] ? text(data.info(IndexType.FULLTEXT)) : ft, BorderLayout.CENTER); tabFT.add(panels[3]); final BaseXTabs tabs = new BaseXTabs(this); tabs.addTab(GENERAL, tabInfo); tabs.addTab(RESOURCES, tabRes); tabs.addTab(NAMES, tabNames); tabs.addTab(PATH_INDEX, tabPath); tabs.addTab(INDEXES, tabValues); tabs.addTab(FULLTEXT, tabFT); final BaseXBack back = new BaseXBack(new BorderLayout()); back.add(tabs, BorderLayout.CENTER); back.add(buttons, BorderLayout.SOUTH); set(resources, BorderLayout.WEST); set(back, BorderLayout.CENTER); action(null); setResizable(true); setMinimumSize(getPreferredSize()); finish(null); }
diff --git a/java/src/com/android/inputmethod/voice/RecognitionView.java b/java/src/com/android/inputmethod/voice/RecognitionView.java index 1e99c3cf..7cec0b04 100644 --- a/java/src/com/android/inputmethod/voice/RecognitionView.java +++ b/java/src/com/android/inputmethod/voice/RecognitionView.java @@ -1,324 +1,323 @@ /* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.voice; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.List; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.CornerPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathEffect; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.MarginLayoutParams; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.android.inputmethod.latin.R; /** * The user interface for the "Speak now" and "working" states. * Displays a recognition dialog (with waveform, voice meter, etc.), * plays beeps, shows errors, etc. */ public class RecognitionView { private static final String TAG = "RecognitionView"; private Handler mUiHandler; // Reference to UI thread private View mView; private Context mContext; private ImageView mImage; private TextView mText; private View mButton; private TextView mButtonText; private View mProgress; private Drawable mInitializing; private Drawable mError; private List<Drawable> mSpeakNow; private float mVolume = 0.0f; private int mLevel = 0; private enum State {LISTENING, WORKING, READY} private State mState = State.READY; private float mMinMicrophoneLevel; private float mMaxMicrophoneLevel; /** Updates the microphone icon to show user their volume.*/ private Runnable mUpdateVolumeRunnable = new Runnable() { public void run() { if (mState != State.LISTENING) { return; } final float min = mMinMicrophoneLevel; final float max = mMaxMicrophoneLevel; final int maxLevel = mSpeakNow.size() - 1; int index = (int) ((mVolume - min) / (max - min) * maxLevel); final int level = Math.min(Math.max(0, index), maxLevel); if (level != mLevel) { mImage.setImageDrawable(mSpeakNow.get(level)); mLevel = level; } mUiHandler.postDelayed(mUpdateVolumeRunnable, 50); } }; public RecognitionView(Context context, OnClickListener clickListener) { mUiHandler = new Handler(); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); mView = inflater.inflate(R.layout.recognition_status, null); ContentResolver cr = context.getContentResolver(); mMinMicrophoneLevel = SettingsUtil.getSettingsFloat( cr, SettingsUtil.LATIN_IME_MIN_MICROPHONE_LEVEL, 15.f); mMaxMicrophoneLevel = SettingsUtil.getSettingsFloat( cr, SettingsUtil.LATIN_IME_MAX_MICROPHONE_LEVEL, 30.f); // Pre-load volume level images Resources r = context.getResources(); mSpeakNow = new ArrayList<Drawable>(); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level0)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level1)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level2)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level3)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level4)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level5)); mSpeakNow.add(r.getDrawable(R.drawable.speak_now_level6)); mInitializing = r.getDrawable(R.drawable.mic_slash); mError = r.getDrawable(R.drawable.caution); mImage = (ImageView) mView.findViewById(R.id.image); mButton = mView.findViewById(R.id.button); mButton.setOnClickListener(clickListener); mText = (TextView) mView.findViewById(R.id.text); mButtonText = (TextView) mView.findViewById(R.id.button_text); mProgress = mView.findViewById(R.id.progress); mContext = context; } public View getView() { return mView; } public void restoreState() { mUiHandler.post(new Runnable() { public void run() { // Restart the spinner if (mState == State.WORKING) { ((ProgressBar)mProgress).setIndeterminate(false); ((ProgressBar)mProgress).setIndeterminate(true); } } }); } public void showInitializing() { mUiHandler.post(new Runnable() { public void run() { prepareDialog(false, mContext.getText(R.string.voice_initializing), mInitializing, mContext.getText(R.string.cancel)); } }); } public void showListening() { mUiHandler.post(new Runnable() { public void run() { mState = State.LISTENING; prepareDialog(false, mContext.getText(R.string.voice_listening), mSpeakNow.get(0), mContext.getText(R.string.cancel)); } }); mUiHandler.postDelayed(mUpdateVolumeRunnable, 50); } public void updateVoiceMeter(final float rmsdB) { mVolume = rmsdB; } public void showError(final String message) { mUiHandler.post(new Runnable() { public void run() { mState = State.READY; prepareDialog(false, message, mError, mContext.getText(R.string.ok)); } }); } public void showWorking( final ByteArrayOutputStream waveBuffer, final int speechStartPosition, final int speechEndPosition) { mUiHandler.post(new Runnable() { public void run() { mState = State.WORKING; prepareDialog(true, mContext.getText(R.string.voice_working), null, mContext .getText(R.string.cancel)); final ShortBuffer buf = ByteBuffer.wrap(waveBuffer.toByteArray()).order( ByteOrder.nativeOrder()).asShortBuffer(); buf.position(0); waveBuffer.reset(); showWave(buf, speechStartPosition / 2, speechEndPosition / 2); } }); } private void prepareDialog(boolean spinVisible, CharSequence text, Drawable image, CharSequence btnTxt) { if (spinVisible) { mProgress.setVisibility(View.VISIBLE); mImage.setVisibility(View.GONE); } else { mProgress.setVisibility(View.GONE); mImage.setImageDrawable(image); mImage.setVisibility(View.VISIBLE); } mText.setText(text); mButtonText.setText(btnTxt); } /** * @return an average abs of the specified buffer. */ private static int getAverageAbs(ShortBuffer buffer, int start, int i, int npw) { int from = start + i * npw; int end = from + npw; int total = 0; for (int x = from; x < end; x++) { total += Math.abs(buffer.get(x)); } return total / npw; } /** * Shows waveform of input audio. * * Copied from version in VoiceSearch's RecognitionActivity. * * TODO: adjust stroke width based on the size of data. * TODO: use dip rather than pixels. */ private void showWave(ShortBuffer waveBuffer, int startPosition, int endPosition) { final int w = ((View) mImage.getParent()).getWidth(); final int h = mImage.getHeight(); if (w <= 0 || h <= 0) { // view is not visible this time. Skip drawing. return; } final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); final Canvas c = new Canvas(b); final Paint paint = new Paint(); paint.setColor(0xFFFFFFFF); // 0xAARRGGBB paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setAlpha(0x90); final PathEffect effect = new CornerPathEffect(3); paint.setPathEffect(effect); final int numSamples = waveBuffer.remaining(); int endIndex; if (endPosition == 0) { endIndex = numSamples; } else { endIndex = Math.min(endPosition, numSamples); } int startIndex = startPosition - 2000; // include 250ms before speech if (startIndex < 0) { startIndex = 0; } final int numSamplePerWave = 200; // 8KHz 25ms = 200 samples final float scale = 10.0f / 65536.0f; final int count = (endIndex - startIndex) / numSamplePerWave; final float deltaX = 1.0f * w / count; - int yMax = h / 2 - 10; + int yMax = h / 2 - 8; Path path = new Path(); c.translate(0, yMax); float x = 0; path.moveTo(x, 0); - yMax -= 10; for (int i = 0; i < count; i++) { final int avabs = getAverageAbs(waveBuffer, startIndex, i , numSamplePerWave); int sign = ( (i & 01) == 0) ? -1 : 1; final float y = Math.min(yMax, avabs * h * scale) * sign; path.lineTo(x, y); x += deltaX; path.lineTo(x, y); } if (deltaX > 4) { paint.setStrokeWidth(3); } else { paint.setStrokeWidth(Math.max(1, (int) (deltaX -.05))); } c.drawPath(path, paint); mImage.setImageBitmap(b); mImage.setVisibility(View.VISIBLE); MarginLayoutParams mProgressParams = (MarginLayoutParams)mProgress.getLayoutParams(); - mProgressParams.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, - -h / 2 - 18, mContext.getResources().getDisplayMetrics()); + mProgressParams.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, + -h , mContext.getResources().getDisplayMetrics()); // Tweak the padding manually to fill out the whole view horizontally. // TODO: Do this in the xml layout instead. ((View) mImage.getParent()).setPadding(4, ((View) mImage.getParent()).getPaddingTop(), 3, ((View) mImage.getParent()).getPaddingBottom()); mProgress.setLayoutParams(mProgressParams); } public void finish() { mUiHandler.post(new Runnable() { public void run() { mState = State.READY; exitWorking(); } }); } private void exitWorking() { mProgress.setVisibility(View.GONE); mImage.setVisibility(View.VISIBLE); } }
false
true
private void showWave(ShortBuffer waveBuffer, int startPosition, int endPosition) { final int w = ((View) mImage.getParent()).getWidth(); final int h = mImage.getHeight(); if (w <= 0 || h <= 0) { // view is not visible this time. Skip drawing. return; } final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); final Canvas c = new Canvas(b); final Paint paint = new Paint(); paint.setColor(0xFFFFFFFF); // 0xAARRGGBB paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setAlpha(0x90); final PathEffect effect = new CornerPathEffect(3); paint.setPathEffect(effect); final int numSamples = waveBuffer.remaining(); int endIndex; if (endPosition == 0) { endIndex = numSamples; } else { endIndex = Math.min(endPosition, numSamples); } int startIndex = startPosition - 2000; // include 250ms before speech if (startIndex < 0) { startIndex = 0; } final int numSamplePerWave = 200; // 8KHz 25ms = 200 samples final float scale = 10.0f / 65536.0f; final int count = (endIndex - startIndex) / numSamplePerWave; final float deltaX = 1.0f * w / count; int yMax = h / 2 - 10; Path path = new Path(); c.translate(0, yMax); float x = 0; path.moveTo(x, 0); yMax -= 10; for (int i = 0; i < count; i++) { final int avabs = getAverageAbs(waveBuffer, startIndex, i , numSamplePerWave); int sign = ( (i & 01) == 0) ? -1 : 1; final float y = Math.min(yMax, avabs * h * scale) * sign; path.lineTo(x, y); x += deltaX; path.lineTo(x, y); } if (deltaX > 4) { paint.setStrokeWidth(3); } else { paint.setStrokeWidth(Math.max(1, (int) (deltaX -.05))); } c.drawPath(path, paint); mImage.setImageBitmap(b); mImage.setVisibility(View.VISIBLE); MarginLayoutParams mProgressParams = (MarginLayoutParams)mProgress.getLayoutParams(); mProgressParams.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, -h / 2 - 18, mContext.getResources().getDisplayMetrics()); // Tweak the padding manually to fill out the whole view horizontally. // TODO: Do this in the xml layout instead. ((View) mImage.getParent()).setPadding(4, ((View) mImage.getParent()).getPaddingTop(), 3, ((View) mImage.getParent()).getPaddingBottom()); mProgress.setLayoutParams(mProgressParams); }
private void showWave(ShortBuffer waveBuffer, int startPosition, int endPosition) { final int w = ((View) mImage.getParent()).getWidth(); final int h = mImage.getHeight(); if (w <= 0 || h <= 0) { // view is not visible this time. Skip drawing. return; } final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); final Canvas c = new Canvas(b); final Paint paint = new Paint(); paint.setColor(0xFFFFFFFF); // 0xAARRGGBB paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setAlpha(0x90); final PathEffect effect = new CornerPathEffect(3); paint.setPathEffect(effect); final int numSamples = waveBuffer.remaining(); int endIndex; if (endPosition == 0) { endIndex = numSamples; } else { endIndex = Math.min(endPosition, numSamples); } int startIndex = startPosition - 2000; // include 250ms before speech if (startIndex < 0) { startIndex = 0; } final int numSamplePerWave = 200; // 8KHz 25ms = 200 samples final float scale = 10.0f / 65536.0f; final int count = (endIndex - startIndex) / numSamplePerWave; final float deltaX = 1.0f * w / count; int yMax = h / 2 - 8; Path path = new Path(); c.translate(0, yMax); float x = 0; path.moveTo(x, 0); for (int i = 0; i < count; i++) { final int avabs = getAverageAbs(waveBuffer, startIndex, i , numSamplePerWave); int sign = ( (i & 01) == 0) ? -1 : 1; final float y = Math.min(yMax, avabs * h * scale) * sign; path.lineTo(x, y); x += deltaX; path.lineTo(x, y); } if (deltaX > 4) { paint.setStrokeWidth(3); } else { paint.setStrokeWidth(Math.max(1, (int) (deltaX -.05))); } c.drawPath(path, paint); mImage.setImageBitmap(b); mImage.setVisibility(View.VISIBLE); MarginLayoutParams mProgressParams = (MarginLayoutParams)mProgress.getLayoutParams(); mProgressParams.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, -h , mContext.getResources().getDisplayMetrics()); // Tweak the padding manually to fill out the whole view horizontally. // TODO: Do this in the xml layout instead. ((View) mImage.getParent()).setPadding(4, ((View) mImage.getParent()).getPaddingTop(), 3, ((View) mImage.getParent()).getPaddingBottom()); mProgress.setLayoutParams(mProgressParams); }
diff --git a/trunk/org/xbill/DNS/utils/hexdump.java b/trunk/org/xbill/DNS/utils/hexdump.java index 5b9fa90..6c80d0d 100644 --- a/trunk/org/xbill/DNS/utils/hexdump.java +++ b/trunk/org/xbill/DNS/utils/hexdump.java @@ -1,59 +1,59 @@ // Copyright (c) 1999 Brian Wellington ([email protected]) // Portions Copyright (c) 1999 Network Associates, Inc. package org.xbill.DNS.utils; import java.io.*; /** * A routine to produce a nice looking hex dump * * @author Brian Wellington */ public class hexdump { private static final char [] hex = "0123456789ABCDEF".toCharArray(); /** * Dumps a byte array into hex format. * @param description If not null, a description of the data. * @param b The data to be printed. * @param offset The start of the data in the array. * @param length The length of the data in the array. */ public static String dump(String description, byte [] b, int offset, int length) { StringBuffer sb = new StringBuffer(); sb.append(length + "b"); if (description != null) sb.append(" (" + description + ")"); sb.append(':'); int prefixlen = sb.toString().length(); prefixlen = (prefixlen + 8) & ~ 7; sb.append('\t'); int perline = (80 - prefixlen) / 3; for (int i = 0; i < length; i++) { if (i != 0 && i % perline == 0) { sb.append('\n'); for (int j = 0; j < prefixlen / 8 ; j++) sb.append('\t'); } int value = (int)(b[i + offset]) & 0xFF; + sb.append(hex[(value >> 4)]); sb.append(hex[(value & 0xF)]); - sb.append(hex[(value >> 8)]); sb.append(' '); } sb.append('\n'); return sb.toString(); } public static String dump(String s, byte [] b) { return dump(s, b, 0, b.length); } }
false
true
public static String dump(String description, byte [] b, int offset, int length) { StringBuffer sb = new StringBuffer(); sb.append(length + "b"); if (description != null) sb.append(" (" + description + ")"); sb.append(':'); int prefixlen = sb.toString().length(); prefixlen = (prefixlen + 8) & ~ 7; sb.append('\t'); int perline = (80 - prefixlen) / 3; for (int i = 0; i < length; i++) { if (i != 0 && i % perline == 0) { sb.append('\n'); for (int j = 0; j < prefixlen / 8 ; j++) sb.append('\t'); } int value = (int)(b[i + offset]) & 0xFF; sb.append(hex[(value & 0xF)]); sb.append(hex[(value >> 8)]); sb.append(' '); } sb.append('\n'); return sb.toString(); }
public static String dump(String description, byte [] b, int offset, int length) { StringBuffer sb = new StringBuffer(); sb.append(length + "b"); if (description != null) sb.append(" (" + description + ")"); sb.append(':'); int prefixlen = sb.toString().length(); prefixlen = (prefixlen + 8) & ~ 7; sb.append('\t'); int perline = (80 - prefixlen) / 3; for (int i = 0; i < length; i++) { if (i != 0 && i % perline == 0) { sb.append('\n'); for (int j = 0; j < prefixlen / 8 ; j++) sb.append('\t'); } int value = (int)(b[i + offset]) & 0xFF; sb.append(hex[(value >> 4)]); sb.append(hex[(value & 0xF)]); sb.append(' '); } sb.append('\n'); return sb.toString(); }
diff --git a/src/haven/HavenPanel.java b/src/haven/HavenPanel.java index 31196f2..93fe01b 100644 --- a/src/haven/HavenPanel.java +++ b/src/haven/HavenPanel.java @@ -1,165 +1,167 @@ package haven; import java.awt.Canvas; import java.awt.GraphicsConfiguration; import java.awt.event.*; import java.awt.image.*; import java.awt.Graphics; import java.util.*; public class HavenPanel extends Canvas implements Runnable, Graphical { RootWidget root; UI ui; int w, h; long fd = 60, fps = 0; List<InputEvent> events = new LinkedList<InputEvent>(); public HavenPanel(int w, int h) { setSize(this.w = w, this.h = h); } public void init() { setFocusTraversalKeysEnabled(false); createBufferStrategy(2); root = new RootWidget(new Coord(w, h), this); ui = new UI(root); addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void keyPressed(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void keyReleased(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } }); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void mouseReleased(MouseEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } }); addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { synchronized(events) { events.add(e); } } public void mouseMoved(MouseEvent e) { synchronized(events) { events.add(e); } } }); addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { - events.add(e); - events.notifyAll(); + synchronized(events) { + events.add(e); + events.notifyAll(); + } } }); } void redraw() { BufferStrategy bs = getBufferStrategy(); Graphics g = bs.getDrawGraphics(); try { root.draw(g); g.setColor(java.awt.Color.WHITE); Utils.drawtext(g, "FPS: " + fps, new Coord(0, 0)); } finally { g.dispose(); } bs.show(); } void dispatch() { synchronized(events) { while(events.size() > 0) { InputEvent e = events.remove(0); if(e instanceof MouseEvent) { MouseEvent me = (MouseEvent)e; if(me.getID() == MouseEvent.MOUSE_PRESSED) { if((me.getX() < 10) && (me.getY() < 10)) throw(new RuntimeException("test")); ui.mousedown(new Coord(me.getX(), me.getY()), me.getButton()); } else if(me.getID() == MouseEvent.MOUSE_RELEASED) { ui.mouseup(new Coord(me.getX(), me.getY()), me.getButton()); } else if(me.getID() == MouseEvent.MOUSE_MOVED || me.getID() == MouseEvent.MOUSE_DRAGGED) { ui.mousemove(new Coord(me.getX(), me.getY())); } else if(me instanceof MouseWheelEvent) { ui.mousewheel(new Coord(me.getX(), me.getY()), ((MouseWheelEvent)me).getWheelRotation()); } } else if(e instanceof KeyEvent) { KeyEvent ke = (KeyEvent)e; if(ke.getID() == KeyEvent.KEY_PRESSED) { ui.keydown(ke); } else if(ke.getID() == KeyEvent.KEY_RELEASED) { ui.keyup(ke); } else if(ke.getID() == KeyEvent.KEY_TYPED) { ui.type(ke); } } } } } public void run() { try { long now, fthen, then; int frames = 0; fthen = System.currentTimeMillis(); while(true) { then = System.currentTimeMillis(); synchronized(ui) { try { if(Session.current != null) Session.current.oc.ctick(); dispatch(); redraw(); } catch(Throwable t) { t.printStackTrace(); } } frames++; now = System.currentTimeMillis(); if(now - then < fd) { synchronized(events) { events.wait(fd - (now - then)); } } if(now - fthen > 1000) { fps = frames; frames = 0; fthen = now; } if(Thread.interrupted()) throw(new InterruptedException()); } } catch(InterruptedException e) {} } public GraphicsConfiguration getconf() { return(getGraphicsConfiguration()); } }
true
true
public void init() { setFocusTraversalKeysEnabled(false); createBufferStrategy(2); root = new RootWidget(new Coord(w, h), this); ui = new UI(root); addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void keyPressed(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void keyReleased(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } }); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void mouseReleased(MouseEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } }); addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { synchronized(events) { events.add(e); } } public void mouseMoved(MouseEvent e) { synchronized(events) { events.add(e); } } }); addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { events.add(e); events.notifyAll(); } }); }
public void init() { setFocusTraversalKeysEnabled(false); createBufferStrategy(2); root = new RootWidget(new Coord(w, h), this); ui = new UI(root); addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void keyPressed(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void keyReleased(KeyEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } }); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } public void mouseReleased(MouseEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } }); addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { synchronized(events) { events.add(e); } } public void mouseMoved(MouseEvent e) { synchronized(events) { events.add(e); } } }); addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { synchronized(events) { events.add(e); events.notifyAll(); } } }); }
diff --git a/bundles/GUI/src/main/java/org/paxle/gui/impl/StyleManager.java b/bundles/GUI/src/main/java/org/paxle/gui/impl/StyleManager.java index 9a256c76..03126d94 100644 --- a/bundles/GUI/src/main/java/org/paxle/gui/impl/StyleManager.java +++ b/bundles/GUI/src/main/java/org/paxle/gui/impl/StyleManager.java @@ -1,103 +1,104 @@ package org.paxle.gui.impl; import java.io.File; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.http.HttpContext; public class StyleManager { private static Log logger = LogFactory.getLog( StyleManager.class); /** HashMap containing available styles */ private static HashMap<String, File> styles = new HashMap<String, File>(); public static HashMap<String, File> getStyles() { return styles; } public static void searchForStyles() { // styles = new HashMap<String, File>(); File stylePath = new File("bundles/Styles"); File[] files = stylePath.listFiles(); for (int i = 0; i < files.length; i++) { styles.put( files[i].getName(), files[i]); } return; } public static void setStyle( String name) { ServletManager servletManager = Activator.getServletManager(); if( name.equals( "default")) { - servletManager.removeResource( "/css"); + //FIXME ! +// servletManager.removeResource( "/css"); servletManager.addResources("/css","/resources/templates/layout/css"); - servletManager.removeResource( "/js"); +// servletManager.removeResource( "/js"); servletManager.addResources("/js","/resources/js"); - servletManager.removeResource( "/images"); +// servletManager.removeResource( "/images"); servletManager.addResources("/images", "/resources/images"); return; } HttpContext httpContextStyle = new HttpContextStyle( name); try { JarFile styleJarFile = new JarFile( name); Enumeration<?> jarEntryEnum = styleJarFile.entries(); while (jarEntryEnum.hasMoreElements()) { JarEntry entry = (JarEntry) jarEntryEnum.nextElement(); if (entry.isDirectory()) { String alias = "/" + entry.getName().substring( 0, entry.getName().length() - 1); servletManager.removeResource( alias); servletManager.addResources( alias, alias, httpContextStyle); } } } catch (IOException e) { logger.error( "io: " + e); e.printStackTrace(); } return; } }
false
true
public static void setStyle( String name) { ServletManager servletManager = Activator.getServletManager(); if( name.equals( "default")) { servletManager.removeResource( "/css"); servletManager.addResources("/css","/resources/templates/layout/css"); servletManager.removeResource( "/js"); servletManager.addResources("/js","/resources/js"); servletManager.removeResource( "/images"); servletManager.addResources("/images", "/resources/images"); return; } HttpContext httpContextStyle = new HttpContextStyle( name); try { JarFile styleJarFile = new JarFile( name); Enumeration<?> jarEntryEnum = styleJarFile.entries(); while (jarEntryEnum.hasMoreElements()) { JarEntry entry = (JarEntry) jarEntryEnum.nextElement(); if (entry.isDirectory()) { String alias = "/" + entry.getName().substring( 0, entry.getName().length() - 1); servletManager.removeResource( alias); servletManager.addResources( alias, alias, httpContextStyle); } } } catch (IOException e) { logger.error( "io: " + e); e.printStackTrace(); } return; }
public static void setStyle( String name) { ServletManager servletManager = Activator.getServletManager(); if( name.equals( "default")) { //FIXME ! // servletManager.removeResource( "/css"); servletManager.addResources("/css","/resources/templates/layout/css"); // servletManager.removeResource( "/js"); servletManager.addResources("/js","/resources/js"); // servletManager.removeResource( "/images"); servletManager.addResources("/images", "/resources/images"); return; } HttpContext httpContextStyle = new HttpContextStyle( name); try { JarFile styleJarFile = new JarFile( name); Enumeration<?> jarEntryEnum = styleJarFile.entries(); while (jarEntryEnum.hasMoreElements()) { JarEntry entry = (JarEntry) jarEntryEnum.nextElement(); if (entry.isDirectory()) { String alias = "/" + entry.getName().substring( 0, entry.getName().length() - 1); servletManager.removeResource( alias); servletManager.addResources( alias, alias, httpContextStyle); } } } catch (IOException e) { logger.error( "io: " + e); e.printStackTrace(); } return; }
diff --git a/thirdparties-extension/org.apache.poi.xwpf.converter.core/src/main/java/org/apache/poi/xwpf/converter/core/XWPFDocumentVisitor.java b/thirdparties-extension/org.apache.poi.xwpf.converter.core/src/main/java/org/apache/poi/xwpf/converter/core/XWPFDocumentVisitor.java index c0d77c32..76863f79 100644 --- a/thirdparties-extension/org.apache.poi.xwpf.converter.core/src/main/java/org/apache/poi/xwpf/converter/core/XWPFDocumentVisitor.java +++ b/thirdparties-extension/org.apache.poi.xwpf.converter.core/src/main/java/org/apache/poi/xwpf/converter/core/XWPFDocumentVisitor.java @@ -1,1034 +1,1037 @@ package org.apache.poi.xwpf.converter.core; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.xwpf.converter.core.styles.XWPFStylesDocument; import org.apache.poi.xwpf.converter.core.utils.DxaUtil; import org.apache.poi.xwpf.converter.core.utils.StringUtils; import org.apache.poi.xwpf.converter.core.utils.XWPFRunHelper; import org.apache.poi.xwpf.converter.core.utils.XWPFTableUtil; import org.apache.poi.xwpf.usermodel.BodyElementType; import org.apache.poi.xwpf.usermodel.BodyType; import org.apache.poi.xwpf.usermodel.IBody; import org.apache.poi.xwpf.usermodel.IBodyElement; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFFooter; import org.apache.poi.xwpf.usermodel.XWPFHeader; import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFPictureData; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFStyle; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData; import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTPosH; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTPosV; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.STRelFromH; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.STRelFromV; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTEmpty; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHdrFtr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHdrFtrRef; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTOnOff; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPTab; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRunTrackChange; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSmartTagRun; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTabs; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; import org.openxmlformats.schemas.wordprocessingml.x2006.main.FtrDocument; import org.openxmlformats.schemas.wordprocessingml.x2006.main.HdrDocument; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrType; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STFldCharType; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff; public abstract class XWPFDocumentVisitor<T, O extends Options, E extends IXWPFMasterPage> { protected final XWPFDocument document; private final MasterPageManager masterPageManager; private XWPFHeader currentHeader; private XWPFFooter currentFooter; protected final XWPFStylesDocument stylesDocument; protected final O options; private String currentInstrText; private boolean pageBreakOnNextParagraph; public XWPFDocumentVisitor( XWPFDocument document, O options ) throws Exception { this.document = document; this.options = options; this.masterPageManager = new MasterPageManager( document, this ); this.stylesDocument = createStylesDocument( document ); } protected XWPFStylesDocument createStylesDocument( XWPFDocument document ) throws XmlException, IOException { return new XWPFStylesDocument( document ); } public XWPFStylesDocument getStylesDocument() { return stylesDocument; } public O getOptions() { return options; } public MasterPageManager getMasterPageManager() { return masterPageManager; } // ------------------------------ Start/End document visitor ----------- /** * Main entry for visit XWPFDocument. * * @param out * @throws Exception */ public void start() throws Exception { T container = startVisitDocument(); // Create IText, XHTML element for each XWPF elements from the w:body List<IBodyElement> bodyElements = document.getBodyElements(); visitBodyElements( bodyElements, container ); endVisitDocument(); } protected abstract T startVisitDocument() throws Exception; protected abstract void endVisitDocument() throws Exception; // ------------------------------ XWPF Elements visitor ----------- protected void visitBodyElements( List<IBodyElement> bodyElements, T container ) throws Exception { if ( !masterPageManager.isInitialized() ) { // master page manager which hosts each <:w;sectPr declared in the word/document.xml // must be initialized. The initialisation loop for each // <w:p paragraph to compute a list of <w:sectPr which contains information // about header/footer declared in the <w:headerReference/<w:footerReference masterPageManager.initialize(); } for ( int i = 0; i < bodyElements.size(); i++ ) { IBodyElement bodyElement = bodyElements.get( i ); visitBodyElement( bodyElement, i, container ); } } protected void visitBodyElement( IBodyElement bodyElement, int index, T container ) throws Exception { switch ( bodyElement.getElementType() ) { case PARAGRAPH: visitParagraph( (XWPFParagraph) bodyElement, index, container ); break; case TABLE: visitTable( (XWPFTable) bodyElement, index, container ); break; } } protected void visitParagraph( XWPFParagraph paragraph, int index, T container ) throws Exception { if ( isWordDocumentPartParsing() ) { // header/footer is not parsing. // It's the word/document.xml which is parsing // test if the current paragraph define a <w:sectPr // to update the header/footer declared in the <w:headerReference/<w:footerReference masterPageManager.update( paragraph ); } this.currentInstrText = null; if ( pageBreakOnNextParagraph ) { pageBreak(); } this.pageBreakOnNextParagraph = false; T paragraphContainer = startVisitParagraph( paragraph, container ); visitParagraphBody( paragraph, index, paragraphContainer ); endVisitParagraph( paragraph, container, paragraphContainer ); this.currentInstrText = null; } protected abstract T startVisitParagraph( XWPFParagraph paragraph, T parentContainer ) throws Exception; protected abstract void endVisitParagraph( XWPFParagraph paragraph, T parentContainer, T paragraphContainer ) throws Exception; protected void visitParagraphBody( XWPFParagraph paragraph, int index, T paragraphContainer ) throws Exception { List<XWPFRun> runs = paragraph.getRuns(); if ( runs.isEmpty() ) { // a new line must be generated if : // - there is next paragraph/table // - if the body is a cell (with none vMerge) and contains just this paragraph if ( isAddNewLine( paragraph, index ) ) { visitEmptyRun( paragraphContainer ); } // sometimes, POI tells that run is empty // but it can be have w:r in the w:pPr // <w:p><w:pPr .. <w:r> => See the header1.xml of DocxBig.docx , // => test if it exist w:r // CTP p = paragraph.getCTP(); // CTPPr pPr = p.getPPr(); // if (pPr != null) { // XmlObject[] wRuns = // pPr.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:r"); // if (wRuns != null) { // for ( int i = 0; i < wRuns.length; i++ ) // { // XmlObject o = wRuns[i]; // o.getDomNode().getParentNode() // if (o instanceof CTR) { // System.err.println(wRuns[i]); // } // // } // } // } // //XmlObject[] t = // o.selectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t"); // //paragraph.getCTP().get } else { // Loop for each element of <w:r, w:fldSimple // to keep the order of thoses elements. CTP ctp = paragraph.getCTP(); visitRuns( paragraph, ctp, paragraphContainer ); // for ( XWPFRun run : paragraph.getRuns() ) // { // Node parent = run.getCTR().getDomNode().getParentNode(); // // XmlObject u = (XmlObject)parent; // // parent.getUser() ; // // System.err.println( parent ); // visitRun( run, paragraphContainer ); // } } // Page Break // Cannot use paragraph.isPageBreak() because it throws NPE because // pageBreak.getVal() can be null. CTPPr ppr = paragraph.getCTP().getPPr(); if ( ppr != null ) { if ( ppr.isSetPageBreakBefore() ) { CTOnOff pageBreak = ppr.getPageBreakBefore(); if ( pageBreak != null && ( pageBreak.getVal() == null || pageBreak.getVal().intValue() == STOnOff.INT_TRUE ) ) { pageBreak(); } } } } private boolean isAddNewLine( XWPFParagraph paragraph, int index ) { // a new line must be generated if : // - there is next paragraph/table // - if the body is a cell (with none vMerge) and contains just this paragraph IBody body = paragraph.getBody(); List<IBodyElement> bodyElements = body.getBodyElements(); if ( body.getPartType() == BodyType.TABLECELL && bodyElements.size() == 1 ) { XWPFTableCell cell = (XWPFTableCell) body; STMerge.Enum vMerge = stylesDocument.getTableCellVMerge( cell ); if ( vMerge != null && vMerge.equals( STMerge.CONTINUE ) ) { // here a new line must not be generated because the body is a cell (with none vMerge) and contains just // this paragraph return false; } // Loop for each cell of the row : if all cells are empty, new line must be generated otherwise none empty // line must be generated. XWPFTableRow row = cell.getTableRow(); List<XWPFTableCell> cells = row.getTableCells(); for ( XWPFTableCell c : cells ) { if ( c.getBodyElements().size() != 1 ) { return false; } IBodyElement element = c.getBodyElements().get( 0 ); if ( element.getElementType() != BodyElementType.PARAGRAPH ) { return false; } return ( (XWPFParagraph) element ).getRuns().size() == 0; } return true; } // here a new line must be generated if there is next paragraph/table return bodyElements.size() > index + 1; } private void visitRuns( XWPFParagraph paragraph, CTP ctp, T paragraphContainer ) throws Exception { boolean fldCharTypeBegin = false; boolean pageNumber = false; CTR lastR = null; XmlCursor c = ctp.newCursor(); c.selectPath( "child::*" ); while ( c.toNextSelection() ) { XmlObject o = c.getObject(); if ( o instanceof CTR ) { /* * Test if it's : <w:r> <w:rPr /> <w:fldChar w:fldCharType="begin" /> </w:r> */ CTR r = (CTR) o; STFldCharType.Enum fldCharType = XWPFRunHelper.getFldCharType( r ); if ( fldCharType != null ) { if ( fldCharType.equals( STFldCharType.BEGIN ) ) { fldCharTypeBegin = true; lastR = null; } else if ( fldCharType.equals( STFldCharType.END ) ) { if ( pageNumber ) { XWPFRun run = new XWPFRun( lastR, paragraph ); visitRun( run, true, paragraphContainer ); } else { - XWPFRun run = new XWPFRun( lastR, paragraph ); - visitRun( run, false, paragraphContainer ); + if ( lastR != null ) + { + XWPFRun run = new XWPFRun( lastR, paragraph ); + visitRun( run, false, paragraphContainer ); + } } fldCharTypeBegin = false; lastR = null; pageNumber = false; } } else { if ( fldCharTypeBegin ) { // test if it's <w:r><w:instrText>PAGE</w:instrText></w:r> String instrText = XWPFRunHelper.getInstrText( r ); if ( instrText != null ) { pageNumber = instrText.trim().equalsIgnoreCase( "page" ); } } else { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, false, paragraphContainer ); } } lastR = r; } else if ( o instanceof CTHyperlink ) { CTHyperlink link = (CTHyperlink) o; for ( CTR r : link.getRList() ) { XWPFRun run = new XWPFHyperlinkRun( link, r, paragraph ); visitRun( run, false, paragraphContainer ); } } else if ( o instanceof CTSdtRun ) { CTSdtContentRun run = ( (CTSdtRun) o ).getSdtContent(); for ( CTR r : run.getRList() ) { XWPFRun ru = new XWPFRun( r, paragraph ); visitRun( ru, false, paragraphContainer ); } } else if ( o instanceof CTRunTrackChange ) { for ( CTR r : ( (CTRunTrackChange) o ).getRList() ) { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, false, paragraphContainer ); } } else if ( o instanceof CTSimpleField ) { CTSimpleField simpleField = (CTSimpleField) o; /* * Support page numbering<w:fldSimple w:instr=" PAGE \* MERGEFORMAT "> <w:r> <w:rPr> <w:noProof/> * </w:rPr> <w:t>- 1 -</w:t> </w:r> </w:fldSimple> */ String instr = simpleField.getInstr(); pageNumber = instr.toLowerCase().contains( "page" ); for ( CTR r : simpleField.getRList() ) { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, pageNumber, paragraphContainer ); } } else if ( o instanceof CTSmartTagRun ) { // Smart Tags can be nested many times. // This implementation does not preserve the tagging information // buildRunsInOrderFromXml(o); } } c.dispose(); } protected abstract void visitEmptyRun( T paragraphContainer ) throws Exception; protected void visitRun( XWPFRun run, boolean pageNumber, T paragraphContainer ) throws Exception { CTR ctr = run.getCTR(); // <w:lastRenderedPageBreak /> // List<CTEmpty> lastRenderedPageBreakList = ctr.getLastRenderedPageBreakList(); // if ( lastRenderedPageBreakList != null && lastRenderedPageBreakList.size() > 0 ) // { // for ( CTEmpty lastRenderedPageBreak : lastRenderedPageBreakList ) // { // pageBreak(); // } // } // Loop for each element of <w:run text, tab, image etc // to keep the order of thoses elements. XmlCursor c = ctr.newCursor(); c.selectPath( "./*" ); while ( c.toNextSelection() ) { XmlObject o = c.getObject(); if ( o instanceof CTText ) { CTText ctText = (CTText) o; String tagName = o.getDomNode().getNodeName(); // Field Codes (w:instrText, defined in spec sec. 17.16.23) // come up as instances of CTText, but we don't want them // in the normal text output if ( "w:instrText".equals( tagName ) ) { currentInstrText = ctText.getStringValue(); } else { // Check if it's hyperlink String hrefHyperlink = getCurrentHRefHyperLink(); if ( hrefHyperlink != null ) { visitHyperlink( ctText, hrefHyperlink, paragraphContainer ); } else { visitText( ctText, pageNumber, paragraphContainer ); } } } else if ( o instanceof CTPTab ) { visitTab( (CTPTab) o, paragraphContainer ); } else if ( o instanceof CTBr ) { visitBR( (CTBr) o, paragraphContainer ); } else if ( o instanceof CTEmpty ) { // Some inline text elements get returned not as // themselves, but as CTEmpty, owing to some odd // definitions around line 5642 of the XSDs // This bit works around it, and replicates the above // rules for that case String tagName = o.getDomNode().getNodeName(); if ( "w:tab".equals( tagName ) ) { CTTabs tabs = stylesDocument.getParagraphTabs( run.getParagraph() ); visitTabs( tabs, paragraphContainer ); } if ( "w:br".equals( tagName ) ) { visitBR( null, paragraphContainer ); } if ( "w:cr".equals( tagName ) ) { visitBR( null, paragraphContainer ); } } else if ( o instanceof CTDrawing ) { visitDrawing( (CTDrawing) o, paragraphContainer ); } } c.dispose(); } private String getCurrentHRefHyperLink() { if ( StringUtils.isEmpty( currentInstrText ) ) { return null; } currentInstrText = currentInstrText.trim(); // test if it's <w:instrText>HYPERLINK "http://code.google.com/p/xdocrepor"</w:instrText> if ( currentInstrText.startsWith( "HYPERLINK" ) ) { currentInstrText = currentInstrText.substring( "HYPERLINK".length(), currentInstrText.length() ); currentInstrText = currentInstrText.trim(); if ( currentInstrText.startsWith( "\"" ) ) { currentInstrText = currentInstrText.substring( 1, currentInstrText.length() ); } if ( currentInstrText.endsWith( "\"" ) ) { currentInstrText = currentInstrText.substring( 0, currentInstrText.length() - 1 ); } return currentInstrText; } return null; } protected abstract void visitHyperlink( CTText ctText, String hrefHyperlink, T paragraphContainer ) throws Exception; protected abstract void visitText( CTText ctText, boolean pageNumber, T paragraphContainer ) throws Exception; protected abstract void visitTab( CTPTab o, T paragraphContainer ) throws Exception; protected abstract void visitTabs( CTTabs tabs, T paragraphContainer ) throws Exception; protected void visitBR( CTBr br, T paragraphContainer ) throws Exception { org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrType.Enum brType = getBrType( br ); if ( brType.equals( STBrType.PAGE ) ) { pageBreakOnNextParagraph = true; } else { addNewLine( br, paragraphContainer ); } } private org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrType.Enum getBrType( CTBr br ) { if ( br != null ) { org.openxmlformats.schemas.wordprocessingml.x2006.main.STBrType.Enum brType = br.getType(); if ( brType != null ) { return brType; } } return STBrType.TEXT_WRAPPING; } protected abstract void addNewLine( CTBr br, T paragraphContainer ) throws Exception; protected abstract void pageBreak() throws Exception; protected void visitTable( XWPFTable table, int index, T container ) throws Exception { // 1) Compute colWidth float[] colWidths = XWPFTableUtil.computeColWidths( table ); T tableContainer = startVisitTable( table, colWidths, container ); visitTableBody( table, colWidths, tableContainer ); endVisitTable( table, container, tableContainer ); } protected void visitTableBody( XWPFTable table, float[] colWidths, T tableContainer ) throws Exception { // Proces Row boolean firstRow = false; boolean lastRow = false; List<XWPFTableRow> rows = table.getRows(); int rowsSize = rows.size(); for ( int i = 0; i < rowsSize; i++ ) { firstRow = ( i == 0 ); lastRow = isLastRow( i, rowsSize ); XWPFTableRow row = rows.get( i ); visitTableRow( row, colWidths, tableContainer, firstRow, lastRow, i, rowsSize ); } } private boolean isLastRow( int rowIndex, int rowsSize ) { return rowIndex == rowsSize - 1; } protected abstract T startVisitTable( XWPFTable table, float[] colWidths, T tableContainer ) throws Exception; protected abstract void endVisitTable( XWPFTable table, T parentContainer, T tableContainer ) throws Exception; protected void visitTableRow( XWPFTableRow row, float[] colWidths, T tableContainer, boolean firstRow, boolean lastRowIfNoneVMerge, int rowIndex, int rowsSize ) throws Exception { boolean headerRow = stylesDocument.isTableRowHeader( row ); startVisitTableRow( row, tableContainer, rowIndex, headerRow ); int nbColumns = colWidths.length; // Process cell boolean firstCol = true; boolean lastCol = false; boolean lastRow = false; List<XWPFTableCell> vMergedCells = null; List<XWPFTableCell> cells = row.getTableCells(); if ( nbColumns > cells.size() ) { // Columns number is not equal to cells number. // POI have a bug with // <w:tr w:rsidR="00C55C20"> // <w:tc> // <w:tc>... // <w:sdt> // <w:sdtContent> // <w:tc> <= this tc which is a XWPFTableCell is not included in the row.getTableCells(); firstCol = true; int cellIndex = -1; CTRow ctRow = row.getCtRow(); XmlCursor c = ctRow.newCursor(); c.selectPath( "./*" ); while ( c.toNextSelection() ) { XmlObject o = c.getObject(); if ( o instanceof CTTc ) { CTTc tc = (CTTc) o; XWPFTableCell cell = row.getTableCell( tc ); cellIndex = getCellIndex( cellIndex, cell ); lastCol = ( cellIndex == nbColumns ); vMergedCells = getVMergedCells( cell, rowIndex, cellIndex ); if ( vMergedCells == null || vMergedCells.size() > 0 ) { lastRow = isLastRow( lastRowIfNoneVMerge, rowIndex, rowsSize, vMergedCells ); visitCell( cell, tableContainer, firstRow, lastRow, firstCol, lastCol, rowIndex, cellIndex, vMergedCells ); } firstCol = false; } else if ( o instanceof CTSdtCell ) { // Fix bug of POI CTSdtCell sdtCell = (CTSdtCell) o; List<CTTc> tcList = sdtCell.getSdtContent().getTcList(); for ( CTTc ctTc : tcList ) { XWPFTableCell cell = new XWPFTableCell( ctTc, row, row.getTable().getBody() ); cellIndex = getCellIndex( cellIndex, cell ); lastCol = ( cellIndex == nbColumns ); vMergedCells = getVMergedCells( cell, rowIndex, cellIndex ); if ( vMergedCells == null || vMergedCells.size() > 0 ) { lastRow = isLastRow( lastRowIfNoneVMerge, rowIndex, rowsSize, vMergedCells ); visitCell( cell, tableContainer, firstRow, lastRow, firstCol, lastCol, rowIndex, cellIndex, vMergedCells ); } firstCol = false; } } } c.dispose(); } else { // Column number is equal to cells number. for ( int i = 0; i < cells.size(); i++ ) { lastCol = ( i == cells.size() - 1 ); XWPFTableCell cell = cells.get( i ); vMergedCells = getVMergedCells( cell, rowIndex, i ); if ( vMergedCells == null || vMergedCells.size() > 0 ) { lastRow = isLastRow( lastRowIfNoneVMerge, rowIndex, rowsSize, vMergedCells ); visitCell( cell, tableContainer, firstRow, lastRow, firstCol, lastCol, rowIndex, i, vMergedCells ); } firstCol = false; } } endVisitTableRow( row, tableContainer, firstRow, lastRow, headerRow ); } private boolean isLastRow( boolean lastRowIfNoneVMerge, int rowIndex, int rowsSize, List<XWPFTableCell> vMergedCells ) { if ( vMergedCells == null ) { return lastRowIfNoneVMerge; } return isLastRow( rowIndex - 1 + vMergedCells.size(), rowsSize ); } private int getCellIndex( int cellIndex, XWPFTableCell cell ) { BigInteger gridSpan = stylesDocument.getTableCellGridSpan( cell.getCTTc().getTcPr() ); if ( gridSpan != null ) { cellIndex = cellIndex + gridSpan.intValue(); } else { cellIndex++; } return cellIndex; } protected void startVisitTableRow( XWPFTableRow row, T tableContainer, int rowIndex, boolean headerRow ) throws Exception { } protected void endVisitTableRow( XWPFTableRow row, T tableContainer, boolean firstRow, boolean lastRow, boolean headerRow ) throws Exception { } protected void visitCell( XWPFTableCell cell, T tableContainer, boolean firstRow, boolean lastRow, boolean firstCol, boolean lastCol, int rowIndex, int cellIndex, List<XWPFTableCell> vMergedCells ) throws Exception { T tableCellContainer = startVisitTableCell( cell, tableContainer, firstRow, lastRow, firstCol, lastCol, vMergedCells ); visitTableCellBody( cell, vMergedCells, tableCellContainer ); endVisitTableCell( cell, tableContainer, tableCellContainer ); } private List<XWPFTableCell> getVMergedCells( XWPFTableCell cell, int rowIndex, int cellIndex ) { List<XWPFTableCell> vMergedCells = null; STMerge.Enum vMerge = stylesDocument.getTableCellVMerge( cell ); if ( vMerge != null ) { if ( vMerge.equals( STMerge.RESTART ) ) { // vMerge="restart" // Loop for each table cell of each row upon vMerge="restart" was found or cell without vMerge // was declared. vMergedCells = new ArrayList<XWPFTableCell>(); vMergedCells.add( cell ); XWPFTableRow row = null; XWPFTableCell c; XWPFTable table = cell.getTableRow().getTable(); for ( int i = rowIndex + 1; i < table.getRows().size(); i++ ) { row = table.getRow( i ); c = row.getCell( cellIndex ); if ( c == null ) { break; } vMerge = stylesDocument.getTableCellVMerge( c ); if ( vMerge != null && vMerge.equals( STMerge.CONTINUE ) ) { vMergedCells.add( c ); } else { return vMergedCells; } } } else { // vMerge="continue", ignore the cell because it was already processed return Collections.emptyList(); } } return vMergedCells; } protected void visitTableCellBody( XWPFTableCell cell, List<XWPFTableCell> vMergeCells, T tableCellContainer ) throws Exception { if ( vMergeCells != null ) { for ( XWPFTableCell mergedCell : vMergeCells ) { List<IBodyElement> bodyElements = mergedCell.getBodyElements(); visitBodyElements( bodyElements, tableCellContainer ); } } else { List<IBodyElement> bodyElements = cell.getBodyElements(); visitBodyElements( bodyElements, tableCellContainer ); } } protected abstract T startVisitTableCell( XWPFTableCell cell, T tableContainer, boolean firstRow, boolean lastRow, boolean firstCol, boolean lastCol, List<XWPFTableCell> vMergeCells ) throws Exception; protected abstract void endVisitTableCell( XWPFTableCell cell, T tableContainer, T tableCellContainer ) throws Exception; protected XWPFStyle getXWPFStyle( String styleID ) { if ( styleID == null ) return null; else return document.getStyles().getStyle( styleID ); } /** * Return true if word/document.xml is parsing and false otherwise. * * @return */ protected boolean isWordDocumentPartParsing() { return currentHeader == null && currentFooter == null; } // ------------------------------ Header/Footer visitor ----------- protected void visitHeaderRef( CTHdrFtrRef headerRef, CTSectPr sectPr, E masterPage ) throws Exception { this.currentHeader = getXWPFHeader( headerRef ); visitHeader( currentHeader, headerRef, sectPr, masterPage ); this.currentHeader = null; } protected abstract void visitHeader( XWPFHeader header, CTHdrFtrRef headerRef, CTSectPr sectPr, E masterPage ) throws Exception; protected void visitFooterRef( CTHdrFtrRef footerRef, CTSectPr sectPr, E masterPage ) throws Exception { this.currentFooter = getXWPFFooter( footerRef ); visitFooter( currentFooter, footerRef, sectPr, masterPage ); this.currentFooter = null; } protected abstract void visitFooter( XWPFFooter footer, CTHdrFtrRef footerRef, CTSectPr sectPr, E masterPage ) throws Exception; protected XWPFHeader getXWPFHeader( CTHdrFtrRef headerRef ) throws XmlException, IOException { PackagePart hdrPart = document.getPartById( headerRef.getId() ); List<XWPFHeader> headers = document.getHeaderList(); for ( XWPFHeader header : headers ) { if ( header.getPackagePart().equals( hdrPart ) ) { return header; } } HdrDocument hdrDoc = HdrDocument.Factory.parse( hdrPart.getInputStream() ); CTHdrFtr hdrFtr = hdrDoc.getHdr(); XWPFHeader hdr = new XWPFHeader( document, hdrFtr ); return hdr; } protected XWPFFooter getXWPFFooter( CTHdrFtrRef footerRef ) throws XmlException, IOException { PackagePart hdrPart = document.getPartById( footerRef.getId() ); List<XWPFFooter> footers = document.getFooterList(); for ( XWPFFooter footer : footers ) { if ( footer.getPackagePart().equals( hdrPart ) ) { return footer; } } FtrDocument hdrDoc = FtrDocument.Factory.parse( hdrPart.getInputStream() ); CTHdrFtr hdrFtr = hdrDoc.getFtr(); XWPFFooter ftr = new XWPFFooter( document, hdrFtr ); return ftr; } protected void visitDrawing( CTDrawing drawing, T parentContainer ) throws Exception { List<CTInline> inlines = drawing.getInlineList(); for ( CTInline inline : inlines ) { visitInline( inline, parentContainer ); } List<CTAnchor> anchors = drawing.getAnchorList(); for ( CTAnchor anchor : anchors ) { visitAnchor( anchor, parentContainer ); } } protected void visitAnchor( CTAnchor anchor, T parentContainer ) throws Exception { CTGraphicalObject graphic = anchor.getGraphic(); /* * wp:positionH relativeFrom="column"> <wp:posOffset>-898525</wp:posOffset> </wp:positionH> */ STRelFromH.Enum relativeFromH = null; Float offsetX = null; CTPosH positionH = anchor.getPositionH(); if ( positionH != null ) { relativeFromH = positionH.getRelativeFrom(); offsetX = DxaUtil.emu2points( positionH.getPosOffset() ); } STRelFromV.Enum relativeFromV = null; Float offsetY = null; CTPosV positionV = anchor.getPositionV(); if ( positionV != null ) { relativeFromV = positionV.getRelativeFrom(); offsetY = DxaUtil.emu2points( positionV.getPosOffset() ); } visitGraphicalObject( parentContainer, graphic, offsetX, relativeFromH, offsetY, relativeFromV ); } protected void visitInline( CTInline inline, T parentContainer ) throws Exception { CTGraphicalObject graphic = inline.getGraphic(); visitGraphicalObject( parentContainer, graphic, null, null, null, null ); } private void visitGraphicalObject( T parentContainer, CTGraphicalObject graphic, Float offsetX, STRelFromH.Enum relativeFromH, Float offsetY, STRelFromV.Enum relativeFromV ) throws Exception { if ( graphic != null ) { CTGraphicalObjectData graphicData = graphic.getGraphicData(); if ( graphicData != null ) { XmlCursor c = graphicData.newCursor(); c.selectPath( "./*" ); while ( c.toNextSelection() ) { XmlObject o = c.getObject(); if ( o instanceof CTPicture ) { visitPicture( (CTPicture) o, offsetX, relativeFromH, offsetY, relativeFromV, parentContainer ); } } c.dispose(); } } } protected abstract void visitPicture( CTPicture picture, Float offsetX, STRelFromH.Enum relativeFromH, Float offsetY, STRelFromV.Enum relativeFromV, T parentContainer ) throws Exception; protected XWPFPictureData getPictureDataByID( String blipId ) { if ( currentHeader != null ) { return currentHeader.getPictureDataByID( blipId ); } if ( currentFooter != null ) { return currentFooter.getPictureDataByID( blipId ); } return document.getPictureDataByID( blipId ); } /** * Set active master page. * * @param masterPage */ protected abstract void setActiveMasterPage( E masterPage ); /** * Create an instance of master page. * * @param sectPr * @return */ protected abstract IXWPFMasterPage createMasterPage( CTSectPr sectPr ); }
true
true
private void visitRuns( XWPFParagraph paragraph, CTP ctp, T paragraphContainer ) throws Exception { boolean fldCharTypeBegin = false; boolean pageNumber = false; CTR lastR = null; XmlCursor c = ctp.newCursor(); c.selectPath( "child::*" ); while ( c.toNextSelection() ) { XmlObject o = c.getObject(); if ( o instanceof CTR ) { /* * Test if it's : <w:r> <w:rPr /> <w:fldChar w:fldCharType="begin" /> </w:r> */ CTR r = (CTR) o; STFldCharType.Enum fldCharType = XWPFRunHelper.getFldCharType( r ); if ( fldCharType != null ) { if ( fldCharType.equals( STFldCharType.BEGIN ) ) { fldCharTypeBegin = true; lastR = null; } else if ( fldCharType.equals( STFldCharType.END ) ) { if ( pageNumber ) { XWPFRun run = new XWPFRun( lastR, paragraph ); visitRun( run, true, paragraphContainer ); } else { XWPFRun run = new XWPFRun( lastR, paragraph ); visitRun( run, false, paragraphContainer ); } fldCharTypeBegin = false; lastR = null; pageNumber = false; } } else { if ( fldCharTypeBegin ) { // test if it's <w:r><w:instrText>PAGE</w:instrText></w:r> String instrText = XWPFRunHelper.getInstrText( r ); if ( instrText != null ) { pageNumber = instrText.trim().equalsIgnoreCase( "page" ); } } else { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, false, paragraphContainer ); } } lastR = r; } else if ( o instanceof CTHyperlink ) { CTHyperlink link = (CTHyperlink) o; for ( CTR r : link.getRList() ) { XWPFRun run = new XWPFHyperlinkRun( link, r, paragraph ); visitRun( run, false, paragraphContainer ); } } else if ( o instanceof CTSdtRun ) { CTSdtContentRun run = ( (CTSdtRun) o ).getSdtContent(); for ( CTR r : run.getRList() ) { XWPFRun ru = new XWPFRun( r, paragraph ); visitRun( ru, false, paragraphContainer ); } } else if ( o instanceof CTRunTrackChange ) { for ( CTR r : ( (CTRunTrackChange) o ).getRList() ) { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, false, paragraphContainer ); } } else if ( o instanceof CTSimpleField ) { CTSimpleField simpleField = (CTSimpleField) o; /* * Support page numbering<w:fldSimple w:instr=" PAGE \* MERGEFORMAT "> <w:r> <w:rPr> <w:noProof/> * </w:rPr> <w:t>- 1 -</w:t> </w:r> </w:fldSimple> */ String instr = simpleField.getInstr(); pageNumber = instr.toLowerCase().contains( "page" ); for ( CTR r : simpleField.getRList() ) { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, pageNumber, paragraphContainer ); } } else if ( o instanceof CTSmartTagRun ) { // Smart Tags can be nested many times. // This implementation does not preserve the tagging information // buildRunsInOrderFromXml(o); } } c.dispose(); }
private void visitRuns( XWPFParagraph paragraph, CTP ctp, T paragraphContainer ) throws Exception { boolean fldCharTypeBegin = false; boolean pageNumber = false; CTR lastR = null; XmlCursor c = ctp.newCursor(); c.selectPath( "child::*" ); while ( c.toNextSelection() ) { XmlObject o = c.getObject(); if ( o instanceof CTR ) { /* * Test if it's : <w:r> <w:rPr /> <w:fldChar w:fldCharType="begin" /> </w:r> */ CTR r = (CTR) o; STFldCharType.Enum fldCharType = XWPFRunHelper.getFldCharType( r ); if ( fldCharType != null ) { if ( fldCharType.equals( STFldCharType.BEGIN ) ) { fldCharTypeBegin = true; lastR = null; } else if ( fldCharType.equals( STFldCharType.END ) ) { if ( pageNumber ) { XWPFRun run = new XWPFRun( lastR, paragraph ); visitRun( run, true, paragraphContainer ); } else { if ( lastR != null ) { XWPFRun run = new XWPFRun( lastR, paragraph ); visitRun( run, false, paragraphContainer ); } } fldCharTypeBegin = false; lastR = null; pageNumber = false; } } else { if ( fldCharTypeBegin ) { // test if it's <w:r><w:instrText>PAGE</w:instrText></w:r> String instrText = XWPFRunHelper.getInstrText( r ); if ( instrText != null ) { pageNumber = instrText.trim().equalsIgnoreCase( "page" ); } } else { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, false, paragraphContainer ); } } lastR = r; } else if ( o instanceof CTHyperlink ) { CTHyperlink link = (CTHyperlink) o; for ( CTR r : link.getRList() ) { XWPFRun run = new XWPFHyperlinkRun( link, r, paragraph ); visitRun( run, false, paragraphContainer ); } } else if ( o instanceof CTSdtRun ) { CTSdtContentRun run = ( (CTSdtRun) o ).getSdtContent(); for ( CTR r : run.getRList() ) { XWPFRun ru = new XWPFRun( r, paragraph ); visitRun( ru, false, paragraphContainer ); } } else if ( o instanceof CTRunTrackChange ) { for ( CTR r : ( (CTRunTrackChange) o ).getRList() ) { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, false, paragraphContainer ); } } else if ( o instanceof CTSimpleField ) { CTSimpleField simpleField = (CTSimpleField) o; /* * Support page numbering<w:fldSimple w:instr=" PAGE \* MERGEFORMAT "> <w:r> <w:rPr> <w:noProof/> * </w:rPr> <w:t>- 1 -</w:t> </w:r> </w:fldSimple> */ String instr = simpleField.getInstr(); pageNumber = instr.toLowerCase().contains( "page" ); for ( CTR r : simpleField.getRList() ) { XWPFRun run = new XWPFRun( r, paragraph ); visitRun( run, pageNumber, paragraphContainer ); } } else if ( o instanceof CTSmartTagRun ) { // Smart Tags can be nested many times. // This implementation does not preserve the tagging information // buildRunsInOrderFromXml(o); } } c.dispose(); }
diff --git a/glob-export/src/main/java/org/esa/beam/glob/export/text/TimeCsvExporter.java b/glob-export/src/main/java/org/esa/beam/glob/export/text/TimeCsvExporter.java index caabb43..4cf4523 100644 --- a/glob-export/src/main/java/org/esa/beam/glob/export/text/TimeCsvExporter.java +++ b/glob-export/src/main/java/org/esa/beam/glob/export/text/TimeCsvExporter.java @@ -1,107 +1,107 @@ package org.esa.beam.glob.export.text; import com.bc.ceres.core.ProgressMonitor; import org.esa.beam.framework.datamodel.Band; import org.esa.beam.framework.datamodel.GeoPos; import org.esa.beam.framework.datamodel.PixelPos; import org.esa.beam.glob.core.timeseries.datamodel.AbstractTimeSeries; import java.io.File; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * User: Thomas Storm * Date: 07.07.2010 * Time: 10:13:43 */ public class TimeCsvExporter extends CsvExporter { public TimeCsvExporter(List<List<Band>> rasterList, List<PixelPos> positions, File outputFile) { super(rasterList, positions, outputFile); forExcel = true; } @Override void setUpColumns() { columns.add("Pin"); if (exportImageCoords) { columns.add("Image position (x | y)"); } if (exportLatLon) { columns.add("Geo position (lat | lon)"); } columns.add("Variable"); if (exportUnit) { columns.add("Unit"); } // we assume all bandlists to contain the same time information, so the columns are built on the first // non-empty bandlist. for (List<Band> bandList : variablesList) { if (!bandList.isEmpty()) { for (Band band : bandList) { final Date date = band.getTimeCoding().getStartTime().getAsDate(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); columns.add(sdf.format(date)); } break; } } } @Override void setUpRows(ProgressMonitor pm) { int index = 0; pm.beginTask("Exporting pin data as csv-file...", positions.size()); for (PixelPos pixelPos : positions) { index++; for (List<Band> bandList : variablesList) { if (!bandList.isEmpty()) { rows.add(setUpRow(pixelPos, bandList, index)); } } pm.worked(1); } pm.done(); } private String setUpRow(PixelPos pixelPos, List<Band> bandList, int index) { Band refBand = bandList.get(0); final StringBuilder row = new StringBuilder(); row.append("Pin").append(index); row.append(getSeparator()); if (exportImageCoords) { DecimalFormat formatter = new DecimalFormat("0.00"); row.append(formatter.format(pixelPos.getX())); row.append(" | "); row.append(formatter.format(pixelPos.getY())); row.append(getSeparator()); } if (exportLatLon) { final GeoPos geoPos = new GeoPos(); refBand.getGeoCoding().getGeoPos(pixelPos, geoPos); row.append(geoPos.getLatString()).append(" (").append(geoPos.getLat()).append(") "); row.append(" | "); row.append(geoPos.getLonString()).append(" (").append(geoPos.getLon()).append(") "); row.append(getSeparator()); } row.append(AbstractTimeSeries.rasterToVariableName(refBand.getName())); row.append(getSeparator()); if (exportUnit) { - row.append(" (").append(refBand.getUnit()).append(")"); + row.append(refBand.getUnit()); row.append(getSeparator()); } for (int i = 0; i < bandList.size(); i++) { Band band = bandList.get(i); row.append(getValue(band, (int) pixelPos.x, (int) pixelPos.y, level)); if (i < bandList.size() - 1) { row.append(getSeparator()); } } return row.toString(); } }
true
true
private String setUpRow(PixelPos pixelPos, List<Band> bandList, int index) { Band refBand = bandList.get(0); final StringBuilder row = new StringBuilder(); row.append("Pin").append(index); row.append(getSeparator()); if (exportImageCoords) { DecimalFormat formatter = new DecimalFormat("0.00"); row.append(formatter.format(pixelPos.getX())); row.append(" | "); row.append(formatter.format(pixelPos.getY())); row.append(getSeparator()); } if (exportLatLon) { final GeoPos geoPos = new GeoPos(); refBand.getGeoCoding().getGeoPos(pixelPos, geoPos); row.append(geoPos.getLatString()).append(" (").append(geoPos.getLat()).append(") "); row.append(" | "); row.append(geoPos.getLonString()).append(" (").append(geoPos.getLon()).append(") "); row.append(getSeparator()); } row.append(AbstractTimeSeries.rasterToVariableName(refBand.getName())); row.append(getSeparator()); if (exportUnit) { row.append(" (").append(refBand.getUnit()).append(")"); row.append(getSeparator()); } for (int i = 0; i < bandList.size(); i++) { Band band = bandList.get(i); row.append(getValue(band, (int) pixelPos.x, (int) pixelPos.y, level)); if (i < bandList.size() - 1) { row.append(getSeparator()); } } return row.toString(); }
private String setUpRow(PixelPos pixelPos, List<Band> bandList, int index) { Band refBand = bandList.get(0); final StringBuilder row = new StringBuilder(); row.append("Pin").append(index); row.append(getSeparator()); if (exportImageCoords) { DecimalFormat formatter = new DecimalFormat("0.00"); row.append(formatter.format(pixelPos.getX())); row.append(" | "); row.append(formatter.format(pixelPos.getY())); row.append(getSeparator()); } if (exportLatLon) { final GeoPos geoPos = new GeoPos(); refBand.getGeoCoding().getGeoPos(pixelPos, geoPos); row.append(geoPos.getLatString()).append(" (").append(geoPos.getLat()).append(") "); row.append(" | "); row.append(geoPos.getLonString()).append(" (").append(geoPos.getLon()).append(") "); row.append(getSeparator()); } row.append(AbstractTimeSeries.rasterToVariableName(refBand.getName())); row.append(getSeparator()); if (exportUnit) { row.append(refBand.getUnit()); row.append(getSeparator()); } for (int i = 0; i < bandList.size(); i++) { Band band = bandList.get(i); row.append(getValue(band, (int) pixelPos.x, (int) pixelPos.y, level)); if (i < bandList.size() - 1) { row.append(getSeparator()); } } return row.toString(); }
diff --git a/modules/kernel/src/com/caucho/transaction/TransactionManagerImpl.java b/modules/kernel/src/com/caucho/transaction/TransactionManagerImpl.java index e82ca34eb..ceb2ca69b 100644 --- a/modules/kernel/src/com/caucho/transaction/TransactionManagerImpl.java +++ b/modules/kernel/src/com/caucho/transaction/TransactionManagerImpl.java @@ -1,582 +1,582 @@ /* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.transaction; import java.io.Serializable; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.InvalidTransactionException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.TransactionSynchronizationRegistry; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import com.caucho.config.inject.SingletonBindingHandle; import com.caucho.config.types.Period; import com.caucho.env.meter.MeterService; import com.caucho.env.meter.TimeSensor; import com.caucho.loader.Environment; import com.caucho.transaction.xalog.AbstractXALogManager; import com.caucho.transaction.xalog.AbstractXALogStream; import com.caucho.util.Alarm; import com.caucho.util.Crc64; import com.caucho.util.L10N; import com.caucho.util.RandomUtil; /** * Implementation of the transaction manager. */ public class TransactionManagerImpl implements TransactionManager, Serializable { private static final long serialVersionUID = 1L; private static L10N L = new L10N(TransactionManagerImpl.class); private static Logger log = Logger.getLogger(TransactionManagerImpl.class.getName()); private static TransactionManagerImpl _tm = new TransactionManagerImpl(); private long _serverId; private long _randomId = RandomUtil.getRandomLong(); private AtomicLong _sequence = new AtomicLong(Alarm.getCurrentTime()); private AbstractXALogManager _xaLogManager; private TransactionSynchronizationRegistry _syncRegistry = new TransactionSynchronizationRegistryImpl(this); // Thread local is dependent on the transaction manager. private ThreadLocal<TransactionImpl> _threadTransaction = new ThreadLocal<TransactionImpl>(); private ArrayList<WeakReference<TransactionImpl>> _transactionList = new ArrayList<WeakReference<TransactionImpl>>(); private long _timeout = -1; // statistics and counters // private TransactionManagerAdmin _admin; private TimeSensor _commitSensor = MeterService.createTimeMeter("Resin|XA|Commit"); private TimeSensor _rollbackSensor = MeterService.createTimeMeter("Resin|XA|Rollback"); private AtomicInteger _transactionCount = new AtomicInteger(); private AtomicLong _commitCount = new AtomicLong(); private AtomicLong _commitResourceFailCount = new AtomicLong(); private AtomicLong _rollbackCount = new AtomicLong(); private AtomicLong _unclosedResourceCount = new AtomicLong(); private String _lastUnclosedResourceMessage; private AtomicLong _unclosedTransactionCount = new AtomicLong(); public TransactionManagerImpl() { new TransactionManagerAdmin(this); } /** * Returns the local transaction manager. */ public static TransactionManagerImpl getInstance() { return _tm; } /** * Returns the local transaction manager. */ public static TransactionManagerImpl getLocal() { return _tm; } /** * Sets the timeout. */ public void setTimeout(Period timeout) { _timeout = timeout.getPeriod(); } /** * Gets the timeout. */ public long getTimeout() { return _timeout; } /** * Sets the XA log manager. */ public void setXALogManager(AbstractXALogManager xaLogManager) { _xaLogManager = xaLogManager; } /** * Returns the synchronization registry */ public TransactionSynchronizationRegistry getSyncRegistry() { return _syncRegistry; } /** * Create a new transaction and associate it with the thread. */ @Override public void begin() throws NotSupportedException, SystemException { getCurrent().begin(); } /** * Creates a new transaction id. */ XidImpl createXID() { return new XidImpl(getServerId(), _randomId, _sequence.incrementAndGet()); } /** * Creates a new transaction id. */ AbstractXALogStream getXALogStream() { if (_xaLogManager != null) return _xaLogManager.getStream(); else return null; } /** * Returns the server id. */ private long getServerId() { if (_serverId == 0) { String server = (String) Environment.getAttribute("caucho.server-id"); if (server == null) _serverId = 1; else _serverId = Crc64.generate(server); } return _serverId; } /** * Returns the transaction for the current thread. */ @Override public TransactionImpl getTransaction() { TransactionImpl trans = _threadTransaction.get(); if (trans == null || trans.getStatus() == Status.STATUS_NO_TRANSACTION || trans.getStatus() == Status.STATUS_UNKNOWN || trans.isSuspended()) { return null; } else { return trans; } } /** * Suspend the transaction. */ @Override public Transaction suspend() throws SystemException { TransactionImpl trans = _threadTransaction.get(); if (trans == null || (!trans.hasResources() && (trans.getStatus() == Status.STATUS_NO_TRANSACTION || trans .getStatus() == Status.STATUS_UNKNOWN))) return null; _threadTransaction.set(null); trans.suspend(); return trans; } /** * Resume the transaction. */ @Override public void resume(Transaction tobj) throws InvalidTransactionException, SystemException { Transaction old = _threadTransaction.get(); if (old != null && old.getStatus() != Status.STATUS_NO_TRANSACTION) throw new SystemException(L.l( "can't resume transaction with active transaction {0}", String .valueOf(old))); TransactionImpl impl = (TransactionImpl) tobj; impl.resume(); _threadTransaction.set(impl); } /** * Force any completion to be a rollback. */ @Override public void setRollbackOnly() throws SystemException { getCurrent().setRollbackOnly(); } /** * Force any completion to be a rollback. */ public void setRollbackOnly(Exception e) { getCurrent().setRollbackOnly(e); } /** * Returns the transaction's status */ @Override public int getStatus() throws SystemException { return getCurrent().getStatus(); } /** * sets the timeout for the transaction */ public void setTransactionTimeout(int seconds) throws SystemException { getCurrent().setTransactionTimeout(seconds); } /** * Commit the transaction. */ @Override public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException { getCurrent().commit(); } /** * Rollback the transaction. */ @Override public void rollback() { getCurrent().rollback(); } /** * Returns the current TransactionImpl, creating if necessary. * * <p/> * The TransactionImpl is not an official externally visible Transaction if * the status == NO_TRANSACTION. */ public TransactionImpl getCurrent() { TransactionImpl trans = _threadTransaction.get(); if (trans == null || trans.isDead()) { trans = new TransactionImpl(this); _threadTransaction.set(trans); addTransaction(trans); } return trans; } private void addTransaction(TransactionImpl trans) { synchronized (_transactionList) { for (int i = _transactionList.size() - 1; i >= 0; i--) { WeakReference<TransactionImpl> ref = _transactionList.get(i); if (ref.get() == null) _transactionList.remove(i); } _transactionList.add(new WeakReference<TransactionImpl>(trans)); } } /** * Returns the corresponding user transaction. */ public void recover(XAResource xaRes) throws XAException { Xid [] xids = null; try { xids = xaRes.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN); } catch (XAException e) { int code = e.errorCode; if (e.getMessage() == null || e.getMessage().isEmpty()) { XAException e1 = new XAException(L.l("Error during recovery (code=" + code + ")", e)); e1.errorCode = code; throw e1; } throw e; } if (xids == null) return; for (int i = 0; i < xids.length; i++) { byte []global = xids[i].getGlobalTransactionId(); if (global.length != XidImpl.GLOBAL_LENGTH) continue; XidImpl xidImpl = new XidImpl(xids[i].getGlobalTransactionId()); if (! xidImpl.isSameServer(getServerId())) continue; if (_xaLogManager != null && _xaLogManager.hasCommittedXid(xidImpl)) { log.fine(L.l("XAResource {0} commit xid {1}", xaRes, xidImpl)); try { - xaRes.commit(xidImpl, false); + xaRes.commit(xids[i], false); } catch (Throwable e) { log.log(Level.WARNING, e.toString(), e); } } else { // XXX: need to check if the transaction belongs to this TM // the ownership is encoded in the xid log.fine(L.l("XAResource {0} forget xid {1}", xaRes, xidImpl)); try { xaRes.forget(xidImpl); } catch (Throwable e) { if (log.isLoggable(Level.FINER)) log.log(Level.FINER, e.toString(), e); else log.fine(e.toString()); } } } } /** * Flushes the log stream (primarily for QA). */ public void flush() { if (_xaLogManager != null) _xaLogManager.flush(); } /** * Statistics */ long beginTransactionTime() { _transactionCount.incrementAndGet(); return Alarm.getCurrentTime(); } int getTransactionCount() { return _transactionCount.get(); } void addCommitResourceFail() { _commitResourceFailCount.incrementAndGet(); } long getCommitResourceFailCount() { return _commitResourceFailCount.get(); } long getCommitCount() { return _commitCount.get(); } void endCommitTime(long startTime) { _transactionCount.decrementAndGet(); _commitCount.incrementAndGet(); _commitSensor.add(startTime); } long getRollbackCount() { return _rollbackCount.get(); } void endRollbackTime(long startTime) { _transactionCount.decrementAndGet(); _rollbackCount.incrementAndGet(); _rollbackSensor.add(startTime); } void addUnclosedResource(String message) { _unclosedResourceCount.incrementAndGet(); _lastUnclosedResourceMessage = message; } long getUnclosedResourceCount() { return _unclosedResourceCount.get(); } String getLastUnclosedResourceMessage() { return _lastUnclosedResourceMessage; } void addUnclosedTransaction(String message) { _unclosedTransactionCount.incrementAndGet(); // _lastUnclosedTransactionMessage = message; } long getUnclosedTransactionCount() { return _unclosedTransactionCount.get(); } /** * Handles the case where a class loader is dropped. */ public void destroy() { AbstractXALogManager xaLogManager = _xaLogManager; _xaLogManager = null; if (xaLogManager != null) xaLogManager.close(); _serverId = 0; ArrayList<TransactionImpl> xaList = new ArrayList<TransactionImpl>(); synchronized (_transactionList) { for (int i = _transactionList.size() - 1; i >= 0; i--) { WeakReference<TransactionImpl> ref = _transactionList.get(i); TransactionImpl xa = ref.get(); if (xa != null) xaList.add(xa); } } for (TransactionImpl xa : xaList) { try { xa.rollback(); } catch (Throwable e) { log.log(Level.WARNING, e.toString(), e); } } } /** * Clearing for test purposes. */ public void testClear() { _serverId = 0; _timeout = -1; AbstractXALogManager logManager = _xaLogManager; _xaLogManager = null; _sequence.set(Alarm.getCurrentTime()); // _randomId = RandomUtil.getRandomLong(); if (logManager != null) logManager.close(); } /** * Serialize to a handle */ private Object writeReplace() { return new SingletonBindingHandle(TransactionManager.class); } public String toString() { return getClass().getSimpleName() + "[]"; } }
true
true
public void recover(XAResource xaRes) throws XAException { Xid [] xids = null; try { xids = xaRes.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN); } catch (XAException e) { int code = e.errorCode; if (e.getMessage() == null || e.getMessage().isEmpty()) { XAException e1 = new XAException(L.l("Error during recovery (code=" + code + ")", e)); e1.errorCode = code; throw e1; } throw e; } if (xids == null) return; for (int i = 0; i < xids.length; i++) { byte []global = xids[i].getGlobalTransactionId(); if (global.length != XidImpl.GLOBAL_LENGTH) continue; XidImpl xidImpl = new XidImpl(xids[i].getGlobalTransactionId()); if (! xidImpl.isSameServer(getServerId())) continue; if (_xaLogManager != null && _xaLogManager.hasCommittedXid(xidImpl)) { log.fine(L.l("XAResource {0} commit xid {1}", xaRes, xidImpl)); try { xaRes.commit(xidImpl, false); } catch (Throwable e) { log.log(Level.WARNING, e.toString(), e); } } else { // XXX: need to check if the transaction belongs to this TM // the ownership is encoded in the xid log.fine(L.l("XAResource {0} forget xid {1}", xaRes, xidImpl)); try { xaRes.forget(xidImpl); } catch (Throwable e) { if (log.isLoggable(Level.FINER)) log.log(Level.FINER, e.toString(), e); else log.fine(e.toString()); } } } }
public void recover(XAResource xaRes) throws XAException { Xid [] xids = null; try { xids = xaRes.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN); } catch (XAException e) { int code = e.errorCode; if (e.getMessage() == null || e.getMessage().isEmpty()) { XAException e1 = new XAException(L.l("Error during recovery (code=" + code + ")", e)); e1.errorCode = code; throw e1; } throw e; } if (xids == null) return; for (int i = 0; i < xids.length; i++) { byte []global = xids[i].getGlobalTransactionId(); if (global.length != XidImpl.GLOBAL_LENGTH) continue; XidImpl xidImpl = new XidImpl(xids[i].getGlobalTransactionId()); if (! xidImpl.isSameServer(getServerId())) continue; if (_xaLogManager != null && _xaLogManager.hasCommittedXid(xidImpl)) { log.fine(L.l("XAResource {0} commit xid {1}", xaRes, xidImpl)); try { xaRes.commit(xids[i], false); } catch (Throwable e) { log.log(Level.WARNING, e.toString(), e); } } else { // XXX: need to check if the transaction belongs to this TM // the ownership is encoded in the xid log.fine(L.l("XAResource {0} forget xid {1}", xaRes, xidImpl)); try { xaRes.forget(xidImpl); } catch (Throwable e) { if (log.isLoggable(Level.FINER)) log.log(Level.FINER, e.toString(), e); else log.fine(e.toString()); } } } }
diff --git a/src/plugins/WebOfTrust/WebOfTrust.java b/src/plugins/WebOfTrust/WebOfTrust.java index bb7a280e..728bf710 100644 --- a/src/plugins/WebOfTrust/WebOfTrust.java +++ b/src/plugins/WebOfTrust/WebOfTrust.java @@ -1,3250 +1,3250 @@ /* This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. */ package plugins.WebOfTrust; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Random; import plugins.WebOfTrust.Identity.FetchState; import plugins.WebOfTrust.Identity.IdentityID; import plugins.WebOfTrust.Score.ScoreID; import plugins.WebOfTrust.Trust.TrustID; import plugins.WebOfTrust.exceptions.DuplicateIdentityException; import plugins.WebOfTrust.exceptions.DuplicateScoreException; import plugins.WebOfTrust.exceptions.DuplicateTrustException; import plugins.WebOfTrust.exceptions.InvalidParameterException; import plugins.WebOfTrust.exceptions.NotInTrustTreeException; import plugins.WebOfTrust.exceptions.NotTrustedException; import plugins.WebOfTrust.exceptions.UnknownIdentityException; import plugins.WebOfTrust.introduction.IntroductionClient; import plugins.WebOfTrust.introduction.IntroductionPuzzle; import plugins.WebOfTrust.introduction.IntroductionPuzzleStore; import plugins.WebOfTrust.introduction.IntroductionServer; import plugins.WebOfTrust.introduction.OwnIntroductionPuzzle; import plugins.WebOfTrust.ui.fcp.FCPInterface; import plugins.WebOfTrust.ui.web.WebInterface; import com.db4o.Db4o; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.defragment.Defragment; import com.db4o.defragment.DefragmentConfig; import com.db4o.ext.ExtObjectContainer; import com.db4o.query.Query; import com.db4o.reflect.jdk.JdkReflector; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.l10n.BaseL10n; import freenet.l10n.BaseL10n.LANGUAGE; import freenet.l10n.PluginL10n; import freenet.node.RequestClient; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.FredPluginBaseL10n; import freenet.pluginmanager.FredPluginFCP; import freenet.pluginmanager.FredPluginL10n; import freenet.pluginmanager.FredPluginRealVersioned; import freenet.pluginmanager.FredPluginThreadless; import freenet.pluginmanager.FredPluginVersioned; import freenet.pluginmanager.PluginReplySender; import freenet.pluginmanager.PluginRespirator; import freenet.support.CurrentTimeUTC; import freenet.support.Logger; import freenet.support.Logger.LogLevel; import freenet.support.SimpleFieldSet; import freenet.support.SizeUtil; import freenet.support.api.Bucket; import freenet.support.io.FileUtil; /** * A web of trust plugin based on Freenet. * * @author xor ([email protected]), Julien Cornuwel ([email protected]) */ public class WebOfTrust implements FredPlugin, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginRealVersioned, FredPluginL10n, FredPluginBaseL10n { /* Constants */ public static final boolean FAST_DEBUG_MODE = false; /** The relative path of the plugin on Freenet's web interface */ public static final String SELF_URI = "/WebOfTrust"; /** Package-private method to allow unit tests to bypass some assert()s */ /** * The "name" of this web of trust. It is included in the document name of identity URIs. For an example, see the SEED_IDENTITIES * constant below. The purpose of this constant is to allow anyone to create his own custom web of trust which is completely disconnected * from the "official" web of trust of the Freenet project. It is also used as the session cookie namespace. */ public static final String WOT_NAME = "WebOfTrust"; public static final String DATABASE_FILENAME = WOT_NAME + ".db4o"; public static final int DATABASE_FORMAT_VERSION = 2; /** * The official seed identities of the WoT plugin: If a newbie wants to download the whole offficial web of trust, he needs at least one * trust list from an identity which is well-connected to the web of trust. To prevent newbies from having to add this identity manually, * the Freenet development team provides a list of seed identities - each of them is one of the developers. */ private static final String[] SEED_IDENTITIES = new String[] { "USK@QeTBVWTwBldfI-lrF~xf0nqFVDdQoSUghT~PvhyJ1NE,OjEywGD063La2H-IihD7iYtZm3rC0BP6UTvvwyF5Zh4,AQACAAE/WebOfTrust/1344", // xor "USK@z9dv7wqsxIBCiFLW7VijMGXD9Gl-EXAqBAwzQ4aq26s,4Uvc~Fjw3i9toGeQuBkDARUV5mF7OTKoAhqOA9LpNdo,AQACAAE/WebOfTrust/1270", // Toad "USK@o2~q8EMoBkCNEgzLUL97hLPdddco9ix1oAnEa~VzZtg,X~vTpL2LSyKvwQoYBx~eleI2RF6QzYJpzuenfcKDKBM,AQACAAE/WebOfTrust/9379", // Bombe // "USK@cI~w2hrvvyUa1E6PhJ9j5cCoG1xmxSooi7Nez4V2Gd4,A3ArC3rrJBHgAJV~LlwY9kgxM8kUR2pVYXbhGFtid78,AQACAAE/WebOfTrust/19", // TheSeeker. Disabled because he is using LCWoT and it does not support identity introduction ATM. "USK@D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc,xgddjFHx2S~5U6PeFkwqO5V~1gZngFLoM-xaoMKSBI8,AQACAAE/WebOfTrust/4959", // zidel }; /* References from the node */ /** The node's interface to connect the plugin with the node, needed for retrieval of all other interfaces */ private PluginRespirator mPR; private static PluginL10n l10n; /* References from the plugin itself */ /* Database & configuration of the plugin */ private ExtObjectContainer mDB; private Configuration mConfig; private IntroductionPuzzleStore mPuzzleStore; /** Used for exporting identities, identity introductions and introduction puzzles to XML and importing them from XML. */ private XMLTransformer mXMLTransformer; private RequestClient mRequestClient; /* Worker objects which actually run the plugin */ /** * Periodically wakes up and inserts any OwnIdentity which needs to be inserted. */ private IdentityInserter mInserter; /** * Fetches identities when it is told to do so by the plugin: * - At startup, all known identities are fetched * - When a new identity is received from a trust list it is fetched * - When a new identity is received by the IntrouductionServer it is fetched * - When an identity is manually added it is also fetched. * - ... */ private IdentityFetcher mFetcher; /** * Uploads captchas belonging to our own identities which others can solve to get on the trust list of them. Checks whether someone * uploaded solutions for them periodically and adds the new identities if a solution is received. */ private IntroductionServer mIntroductionServer; /** * Downloads captchas which the user can solve to announce his identities on other people's trust lists, provides the interface for * the UI to obtain the captchas and enter solutions. Uploads the solutions if the UI enters them. */ private IntroductionClient mIntroductionClient; /* Actual data of the WoT */ private boolean mFullScoreComputationNeeded = false; private boolean mTrustListImportInProgress = false; /* User interfaces */ private WebInterface mWebInterface; private FCPInterface mFCPInterface; /* Statistics */ private int mFullScoreRecomputationCount = 0; private long mFullScoreRecomputationMilliseconds = 0; private int mIncrementalScoreRecomputationCount = 0; private long mIncrementalScoreRecomputationMilliseconds = 0; /* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */ private static transient volatile boolean logDEBUG = false; private static transient volatile boolean logMINOR = false; static { Logger.registerClass(WebOfTrust.class); } public void runPlugin(PluginRespirator myPR) { try { Logger.normal(this, "Web Of Trust plugin version " + Version.getMarketingVersion() + " starting up..."); /* Catpcha generation needs headless mode on linux */ System.setProperty("java.awt.headless", "true"); mPR = myPR; /* TODO: This can be used for clean copies of the database to get rid of corrupted internal db4o structures. /* We should provide an option on the web interface to run this once during next startup and switch to the cloned database */ // cloneDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME), new File(getUserDataDirectory(), DATABASE_FILENAME + ".clone")); mDB = openDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() > WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("The WoT plugin's database format is newer than the WoT plugin which is being used."); mPuzzleStore = new IntroductionPuzzleStore(this); upgradeDB(); // Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher while this is executing. mXMLTransformer = new XMLTransformer(this); mRequestClient = new RequestClient() { public boolean persistent() { return false; } public void removeFrom(ObjectContainer container) { throw new UnsupportedOperationException(); } public boolean realTimeFlag() { return false; } }; mInserter = new IdentityInserter(this); mFetcher = new IdentityFetcher(this, getPluginRespirator()); // We only do this if debug logging is enabled since the integrity verification cannot repair anything anyway, // if the user does not read his logs there is no need to check the integrity. // TODO: Do this once every few startups and notify the user in the web ui if errors are found. if(logDEBUG) verifyDatabaseIntegrity(); // TODO: Only do this once every few startups once we are certain that score computation does not have any serious bugs. verifyAndCorrectStoredScores(); // Database is up now, integrity is checked. We can start to actually do stuff // TODO: This can be used for doing backups. Implement auto backup, maybe once a week or month //backupDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME + ".backup")); createSeedIdentities(); Logger.normal(this, "Starting fetches of all identities..."); synchronized(this) { synchronized(mFetcher) { for(Identity identity : getAllIdentities()) { if(shouldFetchIdentity(identity)) { try { mFetcher.fetch(identity.getID()); } catch(Exception e) { Logger.error(this, "Fetching identity failed!", e); } } } } } mInserter.start(); mIntroductionServer = new IntroductionServer(this, mFetcher); mIntroductionServer.start(); mIntroductionClient = new IntroductionClient(this); mIntroductionClient.start(); mWebInterface = new WebInterface(this, SELF_URI); mFCPInterface = new FCPInterface(this); Logger.normal(this, "Web Of Trust plugin starting up completed."); } catch(RuntimeException e){ Logger.error(this, "Error during startup", e); /* We call it so the database is properly closed */ terminate(); throw e; } } /** * Constructor for being used by the node and unit tests. Does not do anything. */ public WebOfTrust() { } /** * Constructor which does not generate an IdentityFetcher, IdentityInster, IntroductionPuzzleStore, user interface, etc. * For use by the unit tests to be able to run WoT without a node. * @param databaseFilename The filename of the database. */ public WebOfTrust(String databaseFilename) { mDB = openDatabase(new File(databaseFilename)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Database format version mismatch. Found: " + mConfig.getDatabaseFormatVersion() + "; expected: " + WebOfTrust.DATABASE_FORMAT_VERSION); mPuzzleStore = new IntroductionPuzzleStore(this); mFetcher = new IdentityFetcher(this, null); } private File getUserDataDirectory() { final File wotDirectory = new File(mPR.getNode().getUserDir(), WOT_NAME); if(!wotDirectory.exists() && !wotDirectory.mkdir()) throw new RuntimeException("Unable to create directory " + wotDirectory); return wotDirectory; } private com.db4o.config.Configuration getNewDatabaseConfiguration() { com.db4o.config.Configuration cfg = Db4o.newConfiguration(); // Required config options: cfg.reflectWith(new JdkReflector(getPluginClassLoader())); // TODO: Optimization: We do explicit activation everywhere. We could change this to 0 and test whether everything still works. // Ideally, we would benchmark both 0 and 1 and make it configurable. cfg.activationDepth(1); cfg.updateDepth(1); // This must not be changed: We only activate(this, 1) before store(this). Logger.normal(this, "Default activation depth: " + cfg.activationDepth()); cfg.exceptionsOnNotStorable(true); // The shutdown hook does auto-commit. We do NOT want auto-commit: if a transaction hasn't commit()ed, it's not safe to commit it. cfg.automaticShutDown(false); // Performance config options: cfg.callbacks(false); // We don't use callbacks yet. TODO: Investigate whether we might want to use them cfg.classActivationDepthConfigurable(false); // Registration of indices (also performance) // ATTENTION: Also update cloneDatabase() when adding new classes! @SuppressWarnings("unchecked") final Class<? extends Persistent>[] persistentClasses = new Class[] { Configuration.class, Identity.class, OwnIdentity.class, Trust.class, Score.class, IdentityFetcher.IdentityFetcherCommand.class, IdentityFetcher.AbortFetchCommand.class, IdentityFetcher.StartFetchCommand.class, IdentityFetcher.UpdateEditionHintCommand.class, IntroductionPuzzle.class, OwnIntroductionPuzzle.class }; for(Class<? extends Persistent> clazz : persistentClasses) { boolean classHasIndex = clazz.getAnnotation(Persistent.IndexedClass.class) != null; // TODO: We enable class indexes for all classes to make sure nothing breaks because it is the db4o default, check whether enabling // them only for the classes where we need them does not cause any harm. classHasIndex = true; if(logDEBUG) Logger.debug(this, "Persistent class: " + clazz.getCanonicalName() + "; hasIndex==" + classHasIndex); // TODO: Make very sure that it has no negative side effects if we disable class indices for some classes // Maybe benchmark in comparison to a database which has class indices enabled for ALL classes. cfg.objectClass(clazz).indexed(classHasIndex); // Check the class' fields for @IndexedField annotations for(Field field : clazz.getDeclaredFields()) { if(field.getAnnotation(Persistent.IndexedField.class) != null) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + field.getName()); cfg.objectClass(clazz).objectField(field.getName()).indexed(true); } } // Check whether the class itself has an @IndexedField annotation final Persistent.IndexedField annotation = clazz.getAnnotation(Persistent.IndexedField.class); if(annotation != null) { for(String fieldName : annotation.names()) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + fieldName); cfg.objectClass(clazz).objectField(fieldName).indexed(true); } } } // TODO: We should check whether db4o inherits the indexed attribute to child classes, for example for this one: // Unforunately, db4o does not provide any way to query the indexed() property of fields, you can only set it // We might figure out whether inheritance works by writing a benchmark. return cfg; } private synchronized void restoreDatabaseBackup(File databaseFile, File backupFile) throws IOException { Logger.warning(this, "Trying to restore database backup: " + backupFile.getAbsolutePath()); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(backupFile.exists()) { try { FileUtil.secureDelete(databaseFile, mPR.getNode().fastWeakRandom); } catch(IOException e) { Logger.warning(this, "Deleting of the database failed: " + databaseFile.getAbsolutePath()); } if(backupFile.renameTo(databaseFile)) { Logger.warning(this, "Backup restored!"); } else { throw new IOException("Unable to rename backup file back to database file: " + databaseFile.getAbsolutePath()); } } else { throw new IOException("Cannot restore backup, it does not exist!"); } } private synchronized void defragmentDatabase(File databaseFile) throws IOException { Logger.normal(this, "Defragmenting database ..."); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(mPR == null) { Logger.normal(this, "No PluginRespirator found, probably running as unit test, not defragmenting."); return; } final Random random = mPR.getNode().fastWeakRandom; // Open it first, because defrag will throw if it needs to upgrade the file. { final ObjectContainer database = Db4o.openFile(getNewDatabaseConfiguration(), databaseFile.getAbsolutePath()); // Db4o will throw during defragmentation if new fields were added to classes and we didn't initialize their values on existing // objects before defragmenting. So we just don't defragment if the database format version has changed. final boolean canDefragment = peekDatabaseFormatVersion(this, database.ext()) == WebOfTrust.DATABASE_FORMAT_VERSION; while(!database.close()); if(!canDefragment) { Logger.normal(this, "Not defragmenting, database format version changed!"); return; } if(!databaseFile.exists()) { Logger.error(this, "Database file does not exist after openFile: " + databaseFile.getAbsolutePath()); return; } } final File backupFile = new File(databaseFile.getAbsolutePath() + ".backup"); if(backupFile.exists()) { Logger.error(this, "Not defragmenting database: Backup file exists, maybe the node was shot during defrag: " + backupFile.getAbsolutePath()); return; } final File tmpFile = new File(databaseFile.getAbsolutePath() + ".temp"); FileUtil.secureDelete(tmpFile, random); /* As opposed to the default, BTreeIDMapping uses an on-disk file instead of in-memory for mapping IDs. /* Reduces memory usage during defragmentation while being slower. /* However as of db4o 7.4.63.11890, it is bugged and prevents defragmentation from succeeding for my database, so we don't use it for now. */ final DefragmentConfig config = new DefragmentConfig(databaseFile.getAbsolutePath(), backupFile.getAbsolutePath() // ,new BTreeIDMapping(tmpFile.getAbsolutePath()) ); /* Delete classes which are not known to the classloader anymore - We do NOT do this because: /* - It is buggy and causes exceptions often as of db4o 7.4.63.11890 /* - WOT has always had proper database upgrade code (function upgradeDB()) and does not rely on automatic schema evolution. /* If we need to get rid of certain objects we should do it in the database upgrade code, */ // config.storedClassFilter(new AvailableClassFilter()); config.db4oConfig(getNewDatabaseConfiguration()); try { Defragment.defrag(config); } catch (Exception e) { Logger.error(this, "Defragment failed", e); try { restoreDatabaseBackup(databaseFile, backupFile); return; } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e); } } final long oldSize = backupFile.length(); final long newSize = databaseFile.length(); if(newSize <= 0) { Logger.error(this, "Defrag produced an empty file! Trying to restore old database file..."); databaseFile.delete(); try { restoreDatabaseBackup(databaseFile, backupFile); } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e2); } } else { final double change = 100.0 * (((double)(oldSize - newSize)) / ((double)oldSize)); FileUtil.secureDelete(tmpFile, random); FileUtil.secureDelete(backupFile, random); Logger.normal(this, "Defragment completed. "+SizeUtil.formatSize(oldSize)+" ("+oldSize+") -> " +SizeUtil.formatSize(newSize)+" ("+newSize+") ("+(int)change+"% shrink)"); } } /** * ATTENTION: This function is duplicated in the Freetalk plugin, please backport any changes. * * Initializes the plugin's db4o database. */ private synchronized ExtObjectContainer openDatabase(File file) { Logger.normal(this, "Opening database using db4o " + Db4o.version()); if(mDB != null) throw new RuntimeException("Database is opened already!"); try { defragmentDatabase(file); } catch (IOException e) { throw new RuntimeException(e); } return Db4o.openFile(getNewDatabaseConfiguration(), file.getAbsolutePath()).ext(); } /** * ATTENTION: Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher while this is executing. * It doesn't synchronize on the IntroductionPuzzleStore and IdentityFetcher because it assumes that they are not being used yet. * (I didn't upgrade this function to do the locking because it would be much work to test the changes for little benefit) */ @SuppressWarnings("deprecation") private synchronized void upgradeDB() { int databaseVersion = mConfig.getDatabaseFormatVersion(); if(databaseVersion == WebOfTrust.DATABASE_FORMAT_VERSION) return; // Insert upgrade code here. See Freetalk.java for a skeleton. if(databaseVersion == 1) { Logger.normal(this, "Upgrading database version " + databaseVersion); //synchronized(this) { // Already done at function level //synchronized(mPuzzleStore) { // Normally would be needed for deleteWithoutCommit(Identity) but IntroductionClient/Server are not running yet //synchronized(mFetcher) { // Normally would be needed for deleteWithoutCommit(Identity) but the IdentityFetcher is not running yet synchronized(Persistent.transactionLock(mDB)) { try { Logger.normal(this, "Generating Score IDs..."); for(Score score : getAllScores()) { score.generateID(); score.storeWithoutCommit(); } Logger.normal(this, "Generating Trust IDs..."); for(Trust trust : getAllTrusts()) { trust.generateID(); trust.storeWithoutCommit(); } Logger.normal(this, "Searching for identities with mixed up insert/request URIs..."); for(Identity identity : getAllIdentities()) { try { USK.create(identity.getRequestURI()); } catch (MalformedURLException e) { if(identity instanceof OwnIdentity) { Logger.error(this, "Insert URI specified as request URI for OwnIdentity, not correcting the URIs as the insert URI" + "might have been published by solving captchas - the identity could be compromised: " + identity); } else { Logger.error(this, "Insert URI specified as request URI for non-own Identity, deleting: " + identity); deleteWithoutCommit(identity); } } } mConfig.setDatabaseFormatVersion(++databaseVersion); mConfig.storeAndCommit(); Logger.normal(this, "Upgraded database to version " + databaseVersion); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } //} } if(databaseVersion != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Your database is too outdated to be upgraded automatically, please create a new one by deleting " + DATABASE_FILENAME + ". Contact the developers if you really need your old data."); } /** * DO NOT USE THIS FUNCTION ON A DATABASE WHICH YOU WANT TO CONTINUE TO USE! * * Debug function for finding object leaks in the database. * * - Deletes all identities in the database - This should delete ALL objects in the database. * - Then it checks for whether any objects still exist - those are leaks. */ private synchronized void checkForDatabaseLeaks() { Logger.normal(this, "Checking for database leaks... This will delete all identities!"); { Logger.debug(this, "Checking FetchState leakage..."); final Query query = mDB.query(); query.constrain(FetchState.class); @SuppressWarnings("unchecked") ObjectSet<FetchState> result = (ObjectSet<FetchState>)query.execute(); for(FetchState state : result) { Logger.debug(this, "Checking " + state); final Query query2 = mDB.query(); query2.constrain(Identity.class); query.descend("mCurrentEditionFetchState").constrain(state).identity(); @SuppressWarnings("unchecked") ObjectSet<FetchState> result2 = (ObjectSet<FetchState>)query.execute(); switch(result2.size()) { case 0: Logger.error(this, "Found leaked FetchState!"); break; case 1: break; default: Logger.error(this, "Found re-used FetchState, count: " + result2.size()); break; } } Logger.debug(this, "Finished checking FetchState leakage, amount:" + result.size()); } Logger.normal(this, "Deleting ALL identities..."); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { beginTrustListImport(); for(Identity identity : getAllIdentities()) { deleteWithoutCommit(identity); } finishTrustListImport(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); // abortTrustListImport() does rollback already // Persistent.checkedRollbackAndThrow(mDB, this, e); throw e; } } } } Logger.normal(this, "Deleting ALL identities finished."); Query query = mDB.query(); query.constrain(Object.class); @SuppressWarnings("unchecked") ObjectSet<Object> result = query.execute(); for(Object leak : result) { Logger.error(this, "Found leaked object: " + leak); } Logger.warning(this, "Finished checking for database leaks. This database is empty now, delete it."); } private synchronized boolean verifyDatabaseIntegrity() { deleteDuplicateObjects(); deleteOrphanObjects(); Logger.debug(this, "Testing database integrity..."); final Query q = mDB.query(); q.constrain(Persistent.class); boolean result = true; for(final Persistent p : new Persistent.InitializingObjectSet<Persistent>(this, q)) { try { p.startupDatabaseIntegrityTest(); } catch(Exception e) { result = false; try { Logger.error(this, "Integrity test failed for " + p, e); } catch(Exception e2) { Logger.error(this, "Integrity test failed for Persistent of class " + p.getClass(), e); Logger.error(this, "Exception thrown by toString() was:", e2); } } } Logger.debug(this, "Database integrity test finished."); return result; } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Does a backup of the database using db4o's backup mechanism. * * This will NOT fix corrupted internal structures of databases - use cloneDatabase if you need to fix your database. */ private synchronized void backupDatabase(File newDatabase) { Logger.normal(this, "Backing up database to " + newDatabase.getAbsolutePath()); if(newDatabase.exists()) throw new RuntimeException("Target exists already: " + newDatabase.getAbsolutePath()); WebOfTrust backup = null; boolean success = false; try { mDB.backup(newDatabase.getAbsolutePath()); if(logDEBUG) { backup = new WebOfTrust(newDatabase.getAbsolutePath()); // We do not throw to make the clone mechanism more robust in case it is being used for creating backups Logger.debug(this, "Checking database integrity of clone..."); if(backup.verifyDatabaseIntegrity()) Logger.debug(this, "Checking database integrity of clone finished."); else Logger.error(this, "Database integrity check of clone failed!"); Logger.debug(this, "Checking this.equals(clone)..."); if(equals(backup)) Logger.normal(this, "Clone is equal!"); else Logger.error(this, "Clone is not equal!"); } success = true; } finally { if(backup != null) backup.terminate(); if(!success) newDatabase.delete(); } Logger.normal(this, "Backing up database finished."); } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Creates a clone of the source database by reading all objects of it into memory and then writing them out to the target database. * Does NOT copy the Configuration, the IntroductionPuzzles or the IdentityFetcher command queue. * * The difference to backupDatabase is that it does NOT use db4o's backup mechanism, instead it creates the whole database from scratch. * This is useful because the backup mechanism of db4o does nothing but copying the raw file: * It wouldn't fix databases which cannot be defragmented anymore due to internal corruption. * - Databases which were cloned by this function CAN be defragmented even if the original database couldn't. * * HOWEVER this function uses lots of memory as the whole database is copied into memory. */ private synchronized void cloneDatabase(File sourceDatabase, File targetDatabase) { Logger.normal(this, "Cloning " + sourceDatabase.getAbsolutePath() + " to " + targetDatabase.getAbsolutePath()); if(targetDatabase.exists()) throw new RuntimeException("Target exists already: " + targetDatabase.getAbsolutePath()); WebOfTrust original = null; WebOfTrust clone = null; boolean success = false; try { original = new WebOfTrust(sourceDatabase.getAbsolutePath()); // We need to copy all objects into memory and then close & unload the source database before writing the objects to the target one. // - I tried implementing this function in a way where it directly takes the objects from the source database and stores them // in the target database while the source is still open. This did not work: Identity objects disappeared magically, resulting // in Trust objects .storeWithoutCommit throwing "Mandatory object not found" on their associated identities. final HashSet<Identity> allIdentities = new HashSet<Identity>(original.getAllIdentities()); final HashSet<Trust> allTrusts = new HashSet<Trust>(original.getAllTrusts()); final HashSet<Score> allScores = new HashSet<Score>(original.getAllScores()); for(Identity identity : allIdentities) { identity.checkedActivate(16); identity.mWebOfTrust = null; identity.mDB = null; } for(Trust trust : allTrusts) { trust.checkedActivate(16); trust.mWebOfTrust = null; trust.mDB = null; } for(Score score : allScores) { score.checkedActivate(16); score.mWebOfTrust = null; score.mDB = null; } original.terminate(); original = null; System.gc(); // Now we write out the in-memory copies ... clone = new WebOfTrust(targetDatabase.getAbsolutePath()); for(Identity identity : allIdentities) { identity.initializeTransient(clone); identity.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Trust trust : allTrusts) { trust.initializeTransient(clone); trust.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Score score : allScores) { score.initializeTransient(clone); score.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); // And because cloning is a complex operation we do a mandatory database integrity check Logger.normal(this, "Checking database integrity of clone..."); if(clone.verifyDatabaseIntegrity()) Logger.normal(this, "Checking database integrity of clone finished."); else throw new RuntimeException("Database integrity check of clone failed!"); // ... and also test whether the Web Of Trust is equals() to the clone. This does a deep check of all identities, scores & trusts! original = new WebOfTrust(sourceDatabase.getAbsolutePath()); Logger.normal(this, "Checking original.equals(clone)..."); if(original.equals(clone)) Logger.normal(this, "Clone is equal!"); else throw new RuntimeException("Clone is not equal!"); success = true; } finally { if(original != null) original.terminate(); if(clone != null) clone.terminate(); if(!success) targetDatabase.delete(); } Logger.normal(this, "Cloning database finished."); } /** * Recomputes the {@link Score} of all identities and checks whether the score which is stored in the database is correct. * Incorrect scores are corrected & stored. * * The function is synchronized and does a transaction, no outer synchronization is needed. * ATTENTION: It is NOT synchronized on the IntroductionPuzzleStore or the IdentityFetcher. They must NOT be running yet when using this function! */ protected synchronized void verifyAndCorrectStoredScores() { Logger.normal(this, "Veriying all stored scores ..."); synchronized(Persistent.transactionLock(mDB)) { try { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } Logger.normal(this, "Veriying all stored scores finished."); } /** * Debug function for deleting duplicate identities etc. which might have been created due to bugs :) */ private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteIdentity() synchronized(mFetcher) { // // Needed for deleteIdentity() synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For removeTrustWithoutCommit. Done at function level already. synchronized(mFetcher) { // For removeTrustWithoutCommit synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ protected int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected synchronized boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { for(String seedURI : SEED_IDENTITIES) { Identity seed; synchronized(Persistent.transactionLock(mDB)) { try { seed = getIdentityByURI(seedURI); if(seed instanceof OwnIdentity) { OwnIdentity ownSeed = (OwnIdentity)seed; ownSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); ownSeed.storeAndCommit(); } else { try { seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { seed = new Identity(this, seedURI, null, true); // We have to explicitely set the edition number because the constructor only considers the given edition as a hint. seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch (Exception e) { Logger.error(this, "Seed identity creation error", e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore and the IdentityFetcher before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) score.deleteWithoutCommit(); if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) score.deleteWithoutCommit(); } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) trust.deleteWithoutCommit(); if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when endTrustListImport is called. * * You MUST synchronize on this WoT around beginTrustListImport, abortTrustListImport and finishTrustListImport! * You MUST create a database transaction by synchronizing on Persistent.transactionLock(db). */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Finishes the import of the current trust list and clears the "trust list * * Does NOT commit the transaction, you must do this. */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. - * For understanding how score calculation works you should first read {@link computeAllScores + * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); } catch(NotInTrustTreeException e) { currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) currentStoredTrusteeScore.storeWithoutCommit(); // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Created identity " + identity); // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For setTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.addContext(newContext); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeContext(context); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { Identity identity = getOwnIdentityByID(ownIdentityID); identity.setProperty(property, value); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeProperty(property); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
true
true
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteIdentity() synchronized(mFetcher) { // // Needed for deleteIdentity() synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For removeTrustWithoutCommit. Done at function level already. synchronized(mFetcher) { // For removeTrustWithoutCommit synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ protected int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected synchronized boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { for(String seedURI : SEED_IDENTITIES) { Identity seed; synchronized(Persistent.transactionLock(mDB)) { try { seed = getIdentityByURI(seedURI); if(seed instanceof OwnIdentity) { OwnIdentity ownSeed = (OwnIdentity)seed; ownSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); ownSeed.storeAndCommit(); } else { try { seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { seed = new Identity(this, seedURI, null, true); // We have to explicitely set the edition number because the constructor only considers the given edition as a hint. seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch (Exception e) { Logger.error(this, "Seed identity creation error", e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore and the IdentityFetcher before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) score.deleteWithoutCommit(); if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) score.deleteWithoutCommit(); } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) trust.deleteWithoutCommit(); if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when endTrustListImport is called. * * You MUST synchronize on this WoT around beginTrustListImport, abortTrustListImport and finishTrustListImport! * You MUST create a database transaction by synchronizing on Persistent.transactionLock(db). */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Finishes the import of the current trust list and clears the "trust list * * Does NOT commit the transaction, you must do this. */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link computeAllScores * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); } catch(NotInTrustTreeException e) { currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) currentStoredTrusteeScore.storeWithoutCommit(); // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Created identity " + identity); // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For setTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.addContext(newContext); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeContext(context); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { Identity identity = getOwnIdentityByID(ownIdentityID); identity.setProperty(property, value); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeProperty(property); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteIdentity() synchronized(mFetcher) { // // Needed for deleteIdentity() synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For removeTrustWithoutCommit. Done at function level already. synchronized(mFetcher) { // For removeTrustWithoutCommit synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ protected int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected synchronized boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { for(String seedURI : SEED_IDENTITIES) { Identity seed; synchronized(Persistent.transactionLock(mDB)) { try { seed = getIdentityByURI(seedURI); if(seed instanceof OwnIdentity) { OwnIdentity ownSeed = (OwnIdentity)seed; ownSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); ownSeed.storeAndCommit(); } else { try { seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { seed = new Identity(this, seedURI, null, true); // We have to explicitely set the edition number because the constructor only considers the given edition as a hint. seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch (Exception e) { Logger.error(this, "Seed identity creation error", e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore and the IdentityFetcher before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) score.deleteWithoutCommit(); if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) score.deleteWithoutCommit(); } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) trust.deleteWithoutCommit(); if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when endTrustListImport is called. * * You MUST synchronize on this WoT around beginTrustListImport, abortTrustListImport and finishTrustListImport! * You MUST create a database transaction by synchronizing on Persistent.transactionLock(db). */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Finishes the import of the current trust list and clears the "trust list * * Does NOT commit the transaction, you must do this. */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); } catch(NotInTrustTreeException e) { currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) currentStoredTrusteeScore.storeWithoutCommit(); // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Created identity " + identity); // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For setTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.addContext(newContext); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeContext(context); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { Identity identity = getOwnIdentityByID(ownIdentityID); identity.setProperty(property, value); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeProperty(property); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
diff --git a/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java b/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java index cb7088cd1..b3a373707 100644 --- a/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java +++ b/Model/src/java/fr/cg95/cvq/service/users/impl/UserWorkflowService.java @@ -1,963 +1,964 @@ package fr.cg95.cvq.service.users.impl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.scheduling.annotation.Async; import au.com.bytecode.opencsv.CSVWriter; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import fr.cg95.cvq.authentication.IAuthenticationService; import fr.cg95.cvq.business.QoS; import fr.cg95.cvq.business.authority.LocalAuthorityResource; import fr.cg95.cvq.business.users.Address; import fr.cg95.cvq.business.users.Adult; import fr.cg95.cvq.business.users.Child; import fr.cg95.cvq.business.users.FamilyStatusType; import fr.cg95.cvq.business.users.HomeFolder; import fr.cg95.cvq.business.users.Individual; import fr.cg95.cvq.business.users.IndividualRole; import fr.cg95.cvq.business.users.RoleType; import fr.cg95.cvq.business.users.TitleType; import fr.cg95.cvq.business.users.UserAction; import fr.cg95.cvq.business.users.UserEvent; import fr.cg95.cvq.business.users.UserState; import fr.cg95.cvq.business.users.UserWorkflow; import fr.cg95.cvq.business.users.external.HomeFolderMapping; import fr.cg95.cvq.business.users.external.IndividualMapping; import fr.cg95.cvq.dao.hibernate.HibernateUtil; import fr.cg95.cvq.dao.jpa.IGenericDAO; import fr.cg95.cvq.dao.users.IHomeFolderDAO; import fr.cg95.cvq.dao.users.IIndividualDAO; import fr.cg95.cvq.exception.CvqAuthenticationFailedException; import fr.cg95.cvq.exception.CvqBadPasswordException; import fr.cg95.cvq.exception.CvqDisabledAccountException; import fr.cg95.cvq.exception.CvqException; import fr.cg95.cvq.exception.CvqInvalidTransitionException; import fr.cg95.cvq.exception.CvqModelException; import fr.cg95.cvq.exception.CvqValidationException; import fr.cg95.cvq.schema.ximport.HomeFolderImportDocument; import fr.cg95.cvq.security.SecurityContext; import fr.cg95.cvq.security.annotation.Context; import fr.cg95.cvq.security.annotation.ContextPrivilege; import fr.cg95.cvq.security.annotation.ContextType; import fr.cg95.cvq.security.annotation.IsUser; import fr.cg95.cvq.service.authority.ILocalAuthorityLifecycleAware; import fr.cg95.cvq.service.authority.ILocalAuthorityRegistry; import fr.cg95.cvq.service.authority.impl.LocalAuthorityRegistry; import fr.cg95.cvq.service.users.IUserNotificationService; import fr.cg95.cvq.service.users.IUserSearchService; import fr.cg95.cvq.service.users.IUserService; import fr.cg95.cvq.service.users.IUserWorkflowService; import fr.cg95.cvq.util.JSONUtils; import fr.cg95.cvq.util.UserUtils; import fr.cg95.cvq.util.development.BusinessObjectsFactory; import fr.cg95.cvq.util.mail.IMailService; import fr.cg95.cvq.util.translation.ITranslationService; import fr.cg95.cvq.xml.common.AddressType; import fr.cg95.cvq.xml.common.AdultType; import fr.cg95.cvq.xml.common.ChildType; import fr.cg95.cvq.xml.common.HomeFolderType; import fr.cg95.cvq.xml.common.IndividualType; public class UserWorkflowService implements IUserWorkflowService, ApplicationEventPublisherAware, ILocalAuthorityLifecycleAware { private static Logger logger = Logger.getLogger(UserWorkflowService.class); private ApplicationEventPublisher applicationEventPublisher; private ILocalAuthorityRegistry localAuthorityRegistry; private IAuthenticationService authenticationService; private IMailService mailService; private ITranslationService translationService; private IUserService userService; private IUserNotificationService userNotificationService; private IUserSearchService userSearchService; private IHomeFolderDAO homeFolderDAO; private IIndividualDAO individualDAO; private IGenericDAO genericDAO; private Map<String, UserWorkflow> workflows = new HashMap<String, UserWorkflow>(); @Override public void addLocalAuthority(String localAuthorityName) { try { if (LocalAuthorityRegistry.DEVELOPMENT_LOCAL_AUTHORITY.equals(localAuthorityName) && userSearchService.getByLogin("jean.dupont") == null) { Address address = BusinessObjectsFactory.gimmeAddress( "12", "Rue d'Aligre", "Paris", "75012"); Adult homeFolderResponsible = BusinessObjectsFactory.gimmeAdult(TitleType.MISTER, "Dupont", "Jean", address, FamilyStatusType.SINGLE); homeFolderResponsible.setPassword("aaaaaaaa"); HomeFolder homeFolder = create(homeFolderResponsible, false); Adult other = BusinessObjectsFactory.gimmeAdult(TitleType.MISTER, "Durand", "Jacques", address, FamilyStatusType.SINGLE); add(homeFolder, other, false); Child child = BusinessObjectsFactory.gimmeChild("Moreau", "Émilie"); add(homeFolder, child); link(homeFolderResponsible, child, Collections.singleton(RoleType.CLR_FATHER)); } } catch (Exception e) { e.printStackTrace(); logger.error("addLocalAuthority() Unable to create test home folder"); } } @Override public void removeLocalAuthority(String localAuthorityName) { } @Override public UserState[] getPossibleTransitions(UserState state) { return getWorkflow().getPossibleTransitions(state); } @Override @Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.READ) public UserState[] getPossibleTransitions(Individual user) { UserState[] allStates = getPossibleTransitions(user.getState()); List<UserState> result = new ArrayList<UserState>(allStates.length); for (UserState state : allStates) result.add(state); if (userSearchService.getHomeFolderResponsible(user.getHomeFolder().getId()).getId() .equals(user.getId())) { for (Individual i : user.getHomeFolder().getIndividuals()) { if (!i.getId().equals(user.getId()) && !UserState.ARCHIVED.equals(i.getState())) { result.remove(UserState.ARCHIVED); break; } } } return result.toArray(new UserState[result.size()]); } @Override @Context(types = {ContextType.AGENT}, privilege = ContextPrivilege.READ) public UserState[] getPossibleTransitions(HomeFolder user) { return getPossibleTransitions(user.getState()); } @Override public boolean isValidTransition(UserState from, UserState to) { return getWorkflow().isValidTransition(from, to); } @Override public UserState[] getStatesBefore(UserState state) { return getWorkflow().getStatesBefore(state); } @Override public UserState[] getStatesWithProperty(String propertyName) { return getWorkflow().getStatesWithProperty(propertyName); } private UserWorkflow getWorkflow() { String name = SecurityContext.getCurrentSite().getName(); UserWorkflow workflow = workflows.get(name); if (workflow == null) { File file = localAuthorityRegistry.getLocalAuthorityResourceFileForLocalAuthority(name, LocalAuthorityResource.Type.XML, "userWorkflow", false); if (file.exists()) { workflow = UserWorkflow.load(file); workflows.put(name, workflow); } else { workflow = workflows.get("default"); if (workflow == null) { file = localAuthorityRegistry.getReferentialResource( LocalAuthorityResource.Type.XML, "userWorkflow"); workflow = UserWorkflow.load(file); workflows.put("default", workflow); } } } return workflow; } @Override @Context(types = {ContextType.UNAUTH_ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public HomeFolder create(Adult adult, boolean temporary) throws CvqException { HomeFolder homeFolder = new HomeFolder(); homeFolder.setAddress(adult.getAddress()); homeFolder.setEnabled(Boolean.TRUE); homeFolder.setState(SecurityContext.isFrontOfficeContext() ? UserState.NEW : UserState.VALID); homeFolder.setTemporary(temporary); homeFolderDAO.create(homeFolder); if (SecurityContext.isFrontOfficeContext()) { // FIXME hack to avoid CredentialBean's explosion in setCurrentEcitizen() adult.setHomeFolder(homeFolder); SecurityContext.setCurrentEcitizen(adult); } add(homeFolder, adult, !temporary); UserAction action = new UserAction(UserAction.Type.CREATION, homeFolder.getId()); action = (UserAction) genericDAO.create(action); homeFolder.getActions().add(action); if (SecurityContext.isFrontOfficeContext()) { // FIXME attribute all previous actions to the newly created responsible which had no ID Gson gson = new Gson(); for (UserAction tempAction : homeFolder.getActions()) { tempAction.setUserId(adult.getId()); JsonObject payload = JSONUtils.deserialize(tempAction.getData()); JsonObject user = payload.getAsJsonObject("user"); user.addProperty("id", adult.getId()); user.addProperty("name", UserUtils.getDisplayName(adult.getId())); tempAction.setData(gson.toJson(payload)); } } link(adult, homeFolder, Collections.singleton(RoleType.HOME_FOLDER_RESPONSIBLE)); logger.debug("create() successfully created home folder " + homeFolder.getId()); homeFolderDAO.update(homeFolder); return homeFolder; } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public Long add(HomeFolder homeFolder, Adult adult, boolean assignLogin) throws CvqException { if (assignLogin) { adult.setLogin(authenticationService.generateLogin(adult)); } if (adult.getPassword() != null) adult.setPassword(authenticationService.encryptPassword(adult.getPassword())); return add(homeFolder, adult); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public Long add(HomeFolder homeFolder, Child child) throws CvqModelException, CvqInvalidTransitionException { return add(homeFolder, (Individual)child); } private Long add(HomeFolder homeFolder, Individual individual) throws CvqModelException, CvqInvalidTransitionException { homeFolder.getIndividuals().add(individual); individual.setHomeFolder(homeFolder); individual.setState(SecurityContext.isFrontOfficeContext() ? UserState.NEW : UserState.VALID); individual.setCreationDate(new Date()); individual.setQoS(SecurityContext.isFrontOfficeContext() ? QoS.GOOD : null); individual.setLastModificationDate(new Date()); if (individual.getAddress() == null) individual.setAddress(homeFolder.getAddress()); Long id = individualDAO.create(individual).getId(); UserAction action = new UserAction(UserAction.Type.CREATION, id); action = (UserAction) genericDAO.create(action); individual.getHomeFolder().getActions().add(action); if (SecurityContext.isFrontOfficeContext() && !UserState.NEW.equals(individual.getHomeFolder().getState()) && !UserState.MODIFIED.equals(individual.getHomeFolder().getState())) { changeState(homeFolder, UserState.MODIFIED); } homeFolderDAO.update(homeFolder); applicationEventPublisher.publishEvent(new UserEvent(this, action)); return id; } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void modify(HomeFolder homeFolder) { if (SecurityContext.isFrontOfficeContext() && !UserState.NEW.equals(homeFolder.getState())) { homeFolder.setState(UserState.MODIFIED); } homeFolderDAO.update(homeFolder); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void modify(Individual individual, JsonObject atom) throws CvqException { if (individual == null) throw new CvqException("No adult object provided"); else if (individual.getId() == null) throw new CvqException("Cannot modify a transient individual"); if (SecurityContext.isFrontOfficeContext()) { if (!UserState.NEW.equals(individual.getState())) { individual.setState(UserState.MODIFIED); individual.setLastModificationDate(new Date()); individual.setQoS(QoS.GOOD); } if (!UserState.NEW.equals(individual.getHomeFolder().getState())) individual.getHomeFolder().setState(UserState.MODIFIED); } JsonObject payload = new JsonObject(); payload.add("atom", atom); UserAction action = new UserAction(UserAction.Type.MODIFICATION, individual.getId(), payload); action = (UserAction) genericDAO.create(action); // FIXME hack for specific business when changing a user's first or last name if ("identity".equals(atom.get("name").getAsString())) { JsonObject fields = atom.get("fields").getAsJsonObject(); if (fields.has("firstName") || fields.has("lastName")) { String firstName = fields.has("firstName") ? fields.get("firstName").getAsJsonObject().get("from").getAsString() : individual.getFirstName(); String lastName = fields.has("lastName") ? fields.get("lastName").getAsJsonObject().get("from").getAsString() : individual.getLastName(); Gson gson = new Gson(); payload = JSONUtils.deserialize(action.getData()); payload.get("target").getAsJsonObject() .addProperty("name", firstName + ' ' + lastName); if (individual.getId().equals(payload.get("user").getAsJsonObject().get("id").getAsLong())) { payload.get("user").getAsJsonObject() .addProperty("name", firstName + ' ' + lastName); } if (individual instanceof Adult) { Adult adult = (Adult)individual; if (!StringUtils.isEmpty(adult.getLogin())) { JsonObject login = new JsonObject(); login.addProperty("from", adult.getLogin()); adult.setLogin(authenticationService.generateLogin(adult)); login.addProperty("to", adult.getLogin()); payload.get("atom").getAsJsonObject().get("fields").getAsJsonObject() .add("login", login); // hack to refresh security context HibernateUtil.getSession().flush(); } } action.setData(gson.toJson(payload)); } } individual.getHomeFolder().getActions().add(action); homeFolderDAO.update(individual.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); } @Override @Context(types = {ContextType.ECITIZEN}, privilege = ContextPrivilege.WRITE) public void modifyPassword(Adult adult, String oldPassword, String newPassword) throws CvqException, CvqBadPasswordException { try { authenticationService.authenticate(adult.getLogin(), oldPassword); } catch (CvqAuthenticationFailedException cafe) { String warning = "modifyPassword() old password does not match for user " + adult.getLogin(); logger.warn(warning); throw new CvqBadPasswordException(warning); } catch (CvqDisabledAccountException cdae) { logger.info("modifyPassword() account is disabled, still authorizing password change"); } authenticationService.resetAdultPassword(adult, newPassword); } @Override public String resetPassword(Adult adult) throws CvqException { String password = authenticationService.generatePassword(); authenticationService.resetAdultPassword(adult, password); String message; if (!StringUtils.isBlank(adult.getEmail())) { userNotificationService.notifyByEmail( SecurityContext.getCurrentSite().getAdminEmail(), adult.getEmail(), translationService.translate("account.notification.passwordReset.adult.subject"), translationService.translate("account.notification.passwordReset.adult.body", new String[]{password}), null, null); message = translationService.translate("account.message.passwordResetSuccessAdultEmail", new String[]{adult.getEmail()}); } else if (!StringUtils.isBlank(SecurityContext.getCurrentSite().getAdminEmail())) { mailService.send( SecurityContext.getCurrentSite().getAdminEmail(), SecurityContext.getCurrentSite().getAdminEmail(), null, translationService.translate("account.notification.passwordReset.admin.subject", new String[]{SecurityContext.getCurrentSite().getDisplayTitle()}), translationService.translate("account.notification.passwordReset.admin.body", new String[] { translationService.translate("homeFolder.adult.title." + adult.getTitle().toString().toLowerCase()), adult.getLastName(), adult.getFirstName(), adult.getLogin(), password })); message = translationService.translate("account.message.passwordResetSuccessAdminEmail"); } else { message = translationService.translate("account.message.passwordResetSuccessNoEmail", new String[]{password}); } return message; } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void link(Individual owner, HomeFolder target, Collection<RoleType> types) { Set<RoleType> missing = new HashSet<RoleType>(types); for (IndividualRole role : owner.getHomeFolderRoles(target.getId())) { if (types.contains(role.getRole())) missing.remove(role.getRole()); else owner.getIndividualRoles().remove(role); } for (RoleType type : missing) { IndividualRole newRole = new IndividualRole(); newRole.setRole(type); newRole.setHomeFolderId(target.getId()); owner.getIndividualRoles().add(newRole); } if (SecurityContext.isFrontOfficeContext() && !UserState.NEW.equals(target.getState())) { target.setState(UserState.MODIFIED); } JsonObject payload = new JsonObject(); JsonObject jsonResponsible = new JsonObject(); JsonArray jsonTypes = new JsonArray(); for (RoleType type : types) jsonTypes.add(new JsonPrimitive(type.toString())); jsonResponsible.add("types", jsonTypes); jsonResponsible.addProperty("id", owner.getId()); jsonResponsible.addProperty("name", UserUtils.getDisplayName(owner.getId())); payload.add("responsible", jsonResponsible); UserAction action = new UserAction(UserAction.Type.MODIFICATION, target.getId(), payload); action = (UserAction) genericDAO.create(action); owner.getHomeFolder().getActions().add(action); homeFolderDAO.update(owner.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void unlink(Individual owner, HomeFolder target) { Set<IndividualRole> roles = owner.getHomeFolderRoles(target.getId()); if (roles.isEmpty()) return; Set<RoleType> deleted = new HashSet<RoleType>(); for (IndividualRole role : roles) { owner.getIndividualRoles().remove(role); deleted.add(role.getRole()); } if (SecurityContext.isFrontOfficeContext() && !UserState.NEW.equals(target.getState())) { target.setState(UserState.MODIFIED); } JsonObject payload = new JsonObject(); JsonObject jsonResponsible = new JsonObject(); JsonArray jsonTypes = new JsonArray(); for (RoleType type : deleted) jsonTypes.add(new JsonPrimitive(type.toString())); jsonResponsible.add("deleted", jsonTypes); jsonResponsible.addProperty("id", owner.getId()); jsonResponsible.addProperty("name", UserUtils.getDisplayName(owner.getId())); payload.add("responsible", jsonResponsible); UserAction action = new UserAction(UserAction.Type.MODIFICATION, target.getId(), payload); action = (UserAction) genericDAO.create(action); owner.getHomeFolder().getActions().add(action); homeFolderDAO.update(owner.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void link(Individual owner, Individual target, Collection<RoleType> types) { Set<RoleType> missing = new HashSet<RoleType>(types); for (IndividualRole role : owner.getIndividualRoles(target.getId())) { if (types.contains(role.getRole())) missing.remove(role.getRole()); else owner.getIndividualRoles().remove(role); } if (missing.isEmpty()) return; for (RoleType type : missing) { IndividualRole newRole = new IndividualRole(); newRole.setRole(type); newRole.setIndividualId(target.getId()); owner.getIndividualRoles().add(newRole); } if (SecurityContext.isFrontOfficeContext()) { if (!UserState.NEW.equals(target.getState())) { target.setState(UserState.MODIFIED); target.setLastModificationDate(new Date()); target.setQoS(QoS.GOOD); } if (!UserState.NEW.equals(target.getHomeFolder().getState())) target.getHomeFolder().setState(UserState.MODIFIED); } JsonObject payload = new JsonObject(); JsonObject jsonResponsible = new JsonObject(); JsonArray jsonTypes = new JsonArray(); for (RoleType type : types) jsonTypes.add(new JsonPrimitive(type.toString())); jsonResponsible.add("types", jsonTypes); jsonResponsible.addProperty("id", owner.getId()); jsonResponsible.addProperty("name", UserUtils.getDisplayName(owner.getId())); payload.add("responsible", jsonResponsible); UserAction action = new UserAction(UserAction.Type.MODIFICATION, target.getId(), payload); action = (UserAction) genericDAO.create(action); owner.getHomeFolder().getActions().add(action); homeFolderDAO.update(owner.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void unlink( Individual owner, Individual target) { Set<IndividualRole> roles = owner.getIndividualRoles(target.getId()); if (roles.isEmpty()) return; Set<RoleType> deleted = new HashSet<RoleType>(); for (IndividualRole role : roles) { owner.getIndividualRoles().remove(role); deleted.add(role.getRole()); } if (SecurityContext.isFrontOfficeContext()) { if (!UserState.NEW.equals(target.getState())) { target.setState(UserState.MODIFIED); target.setLastModificationDate(new Date()); target.setQoS(QoS.GOOD); } if (!UserState.NEW.equals(target.getHomeFolder().getState())) target.getHomeFolder().setState(UserState.MODIFIED); } JsonObject payload = new JsonObject(); JsonObject jsonResponsible = new JsonObject(); JsonArray jsonTypes = new JsonArray(); for (RoleType type : deleted) jsonTypes.add(new JsonPrimitive(type.toString())); jsonResponsible.add("deleted", jsonTypes); jsonResponsible.addProperty("id", owner.getId()); jsonResponsible.addProperty("name", UserUtils.getDisplayName(owner.getId())); payload.add("responsible", jsonResponsible); UserAction action = new UserAction(UserAction.Type.MODIFICATION, target.getId(), payload); action = (UserAction) genericDAO.create(action); owner.getHomeFolder().getActions().add(action); homeFolderDAO.update(owner.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void changeState(HomeFolder homeFolder, UserState state) throws CvqModelException, CvqInvalidTransitionException { if (!isValidTransition(homeFolder.getState(), state)) throw new CvqInvalidTransitionException( translationService.translate( "user.state." + homeFolder.getState().toString().toLowerCase()), translationService.translate( "user.state." + state.toString().toLowerCase())); if (UserState.VALID.equals(state)) { for (Individual individual : homeFolder.getIndividuals()) { if (!UserState.VALID.equals(individual.getState()) && !UserState.ARCHIVED.equals(individual.getState())) throw new CvqModelException(""); } } homeFolder.setState(state); JsonObject payload = new JsonObject(); payload.addProperty("state", state.toString()); UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, homeFolder.getId(), payload); action = (UserAction) genericDAO.create(action); homeFolder.getActions().add(action); homeFolderDAO.update(homeFolder); applicationEventPublisher.publishEvent(new UserEvent(this, action)); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void validateHomeFolder(@IsUser HomeFolder homeFolder) throws CvqModelException, CvqInvalidTransitionException { // collect individuals ids to not iterate on individuals directly // coz' it throws ConcurrentModificationException in called methods (changeState) List<Long> ids=new ArrayList<Long>(); for (Individual i : homeFolder.getIndividuals()) { ids.add(i.getId()); } for (Long id : ids) { Individual individual = userSearchService.getById(id); if (individual.getState().equals(UserState.NEW) || individual.getState().equals(UserState.MODIFIED)) { changeState(individual,UserState.VALID); } } } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void changeState(Individual individual, UserState state) throws CvqModelException, CvqInvalidTransitionException { if (!isValidTransition(individual.getState(), state)) throw new CvqInvalidTransitionException( translationService.translate( "user.state." + individual.getState().toString().toLowerCase()), translationService.translate( "user.state." + state.toString().toLowerCase())); HomeFolder homeFolder = individual.getHomeFolder(); // if trying to archive home folder responsible, check it is the last non archived individual // in home folder Long responsibleId = userSearchService.getHomeFolderResponsible(homeFolder.getId()).getId(); if (UserState.ARCHIVED.equals(state) && individual.getId().equals(responsibleId)) { for (Individual i : homeFolder.getIndividuals()) { // check that other individuals are also archived if (!UserState.ARCHIVED.equals(i.getState()) && !i.getId().equals(responsibleId)) throw new CvqModelException("user.state.error.mustArchiveResponsibleLast"); } } if (UserState.ARCHIVED.equals(state)) { //Forbid to delete an adult if he's the last responsible of someone. if (individual.getClass().equals(Adult.class)) { Set<Child> children = userSearchService.havingAsOnlyResponsible((Adult)individual); if (!children.isEmpty()) throw new CvqModelException(translationService.translate( "user.state.error.cannotDeleteLastResponsible", new Object[]{ UserUtils.getDisplayName(individual.getId()), UserUtils.getDisplayName(( (Child)(children.toArray()[0]) ).getId()) })); } //Remove in and out roles. List<Individual> individualsCopy = new ArrayList<Individual>(homeFolder.getIndividuals()); for (Individual responsible : individualsCopy) { unlink(responsible, individual); unlink(individual, responsible); } } // update individual state and notify individual.setState(state); individual.setLastModificationDate(new Date()); // NdBOR : why only in Back Office context ? if (SecurityContext.isBackOfficeContext()) { individual.setQoS(null); } JsonObject payload = new JsonObject(); payload.addProperty("state", state.toString()); UserAction action = new UserAction(UserAction.Type.STATE_CHANGE, individual.getId(), payload); action = (UserAction) genericDAO.create(action); homeFolder.getActions().add(action); homeFolderDAO.update(individual.getHomeFolder()); applicationEventPublisher.publishEvent(new UserEvent(this, action)); // change home folder state if needed if (UserState.INVALID.equals(state) && !UserState.INVALID.equals(homeFolder.getState())) changeState(homeFolder, UserState.INVALID); else if (UserState.VALID.equals(state) || UserState.ARCHIVED.equals(state)) { UserState homeFolderState = state; for (Individual i : homeFolder.getIndividuals()) { if (UserState.VALID.equals(i.getState())) { homeFolderState = UserState.VALID; } else if (!UserState.ARCHIVED.equals(i.getState())) { homeFolderState = null; break; } } if (homeFolderState != null && !homeFolderState.equals(homeFolder.getState())) changeState(individual.getHomeFolder(), homeFolderState); } } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void delete(Long id) { delete(userSearchService.getHomeFolderById(id)); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void delete(Individual individual) { HomeFolder homeFolder = individual.getHomeFolder(); for (Individual responsible : homeFolder.getIndividuals()) { unlink(responsible, individual); } UserAction action = new UserAction(UserAction.Type.DELETION, individual.getId()); action = (UserAction) genericDAO.create(action); applicationEventPublisher.publishEvent(new UserEvent(this, action)); homeFolder.getActions().add(action); homeFolder.getIndividuals().remove(individual); individual.setAddress(null); individual.setHomeFolder(null); individualDAO.delete(individual); homeFolderDAO.update(homeFolder); } @Override @Context(types = {ContextType.ECITIZEN, ContextType.AGENT}, privilege = ContextPrivilege.WRITE) public void delete(HomeFolder homeFolder) { applicationEventPublisher.publishEvent(new UserEvent(this, new UserAction(UserAction.Type.DELETION, homeFolder.getId()))); List<Individual> individuals = homeFolder.getIndividuals(); // need to stack adults and children to ensure that adults are deleted before children // because of legal responsibles constraints Set<Adult> adults = new HashSet<Adult>(); Set<Child> children = new HashSet<Child>(); for (Individual individual : individuals) { if (individual instanceof Adult) adults.add((Adult)individual); else if (individual instanceof Child) children.add((Child) individual); } for (Adult adult : adults) { delete(adult); } for (Child child : children) { delete(child); } homeFolderDAO.delete(homeFolder); } @Override @Async @Context(types = {ContextType.ADMIN}, privilege = ContextPrivilege.WRITE) public void importHomeFolders(HomeFolderImportDocument doc) throws CvqException, IOException { SecurityContext.setCurrentContext(SecurityContext.ADMIN_CONTEXT); ByteArrayOutputStream creationsOutput = new ByteArrayOutputStream(); CSVWriter creations = new CSVWriter(new OutputStreamWriter(creationsOutput)); creations.writeNext(new String[] { translationService.translate("homeFolder.property.id"), translationService.translate("homeFolder.property.externalId"), translationService.translate("homeFolder.individual.property.firstName"), translationService.translate("homeFolder.individual.property.lastName"), translationService.translate("homeFolder.adult.property.login"), translationService.translate("homeFolder.adult.property.password"), translationService.translate("homeFolder.adult.property.email"), translationService.translate("homeFolder.individual.property.address") }); boolean hasCreations = false; ByteArrayOutputStream duplicatesOutput = new ByteArrayOutputStream(); CSVWriter duplicates = new CSVWriter(new OutputStreamWriter(duplicatesOutput)); duplicates.writeNext(new String[] { translationService.translate("homeFolder.property.externalId"), translationService.translate("homeFolder.individual.property.firstName"), translationService.translate("homeFolder.individual.property.lastName"), translationService.translate("homeFolder.adult.property.email"), translationService.translate("homeFolder.adult.property.homePhone"), translationService.translate("homeFolder.individual.property.address") }); boolean hasDuplicates = false; ByteArrayOutputStream failuresOutput = new ByteArrayOutputStream(); CSVWriter failures = new CSVWriter(new OutputStreamWriter(failuresOutput)); failures.writeNext(new String[] { translationService.translate("homeFolder.property.externalId"), translationService.translate("Error") }); boolean hasFailures = false; String label = doc.getHomeFolderImport().getExternalServiceLabel(); homeFolders : for (HomeFolderType homeFolder : doc.getHomeFolderImport().getHomeFolderArray()) { HibernateUtil.beginTransaction(); try { Adult responsible = null; List<Adult> adults = new ArrayList<Adult>(); List<Child> children = new ArrayList<Child>(); List<Individual> individuals = new ArrayList<Individual>(); HomeFolderMapping homeFolderMapping = null; if (label != null && homeFolder.getExternalId() != null) { homeFolderMapping = new HomeFolderMapping(label, null, homeFolder.getExternalId()); } Address homeFolderAddress = Address.xmlToModel(homeFolder.getAddress()); for (IndividualType individual : homeFolder.getIndividualsArray()) { String email = null; String phone = null; if (individual instanceof AdultType) { AdultType adult = (AdultType)individual; email = adult.getEmail(); phone = adult.getHomePhone(); Adult a = Adult.xmlToModel(adult); boolean isResponsible = false; Iterator<IndividualRole> it = a.getIndividualRoles().iterator(); while (it.hasNext()) { if (RoleType.HOME_FOLDER_RESPONSIBLE.equals(it.next().getRole())) { if (responsible != null) throw new CvqModelException("homeFolder.error.onlyOneResponsibleIsAllowed"); isResponsible = true; it.remove(); } } if (isResponsible) responsible = a; else adults.add(a); individuals.add(a); } else { Child c = Child.xmlToModel((ChildType)individual); children.add(c); individuals.add(c); } AddressType address = individual.getAddress(); if (individualDAO.hasSimilarIndividuals(individual.getFirstName(), individual.getLastName(), email, phone, address.getStreetNumber(), address.getStreetName(), address.getPostalCode(), address.getCity())) { duplicates.writeNext(new String[] { homeFolder.getExternalId(), individual.getFirstName(), individual.getLastName(), email, phone, address.getStreetNumber() == null ? String.format("%s %s %s", address.getStreetName(), address.getPostalCode(), address.getCity()) : String.format("%s %s %s %s", address.getStreetNumber(), address.getStreetName(), address.getPostalCode(), address.getCity()) }); hasDuplicates = true; continue homeFolders; } if (homeFolderMapping != null) { homeFolderMapping.getIndividualsMappings().add( new IndividualMapping(null, individual.getExternalId(), homeFolderMapping)); } } if (responsible == null) throw new CvqModelException("homeFolder.error.responsibleIsRequired"); HomeFolder result = create(responsible, false); HibernateUtil.getSession().flush(); for (Adult a : adults) add(result, a, false); adults.add(responsible); for (Child c : children) { add(result, c); for (Adult a : adults) { List<RoleType> roles = new ArrayList<RoleType>(); Iterator<IndividualRole> it = a.getIndividualRoles().iterator(); while (it.hasNext()) { IndividualRole role = it.next(); - if (c.getFullName().equals(role.getIndividualName())) { + if (role.getIndividualName() != null + && c.getFullName().toUpperCase().equals(role.getIndividualName().toUpperCase())) { roles.add(role.getRole()); it.remove(); genericDAO.delete(role); } } if (!roles.isEmpty()) { for (RoleType role : roles) link(a, c, Collections.singleton(role)); } } } HibernateUtil.getSession().flush(); for (Individual i : individuals) { List<String> errors = userService.validate(i); if (!errors.isEmpty()) throw new CvqValidationException(errors); } String password = authenticationService.generatePassword(); authenticationService.resetAdultPassword(responsible, password); creations.writeNext(new String[] { String.valueOf(result.getId()), homeFolder.getExternalId(), responsible.getFirstName(), responsible.getLastName(), responsible.getLogin(), password, responsible.getEmail(), homeFolderAddress.getStreetNumber() == null ? String.format("%s %s %s", homeFolderAddress.getStreetName(), homeFolderAddress.getPostalCode(), homeFolderAddress.getCity()) : String.format("%s %s %s %s", homeFolderAddress.getStreetNumber(), homeFolderAddress.getStreetName(), homeFolderAddress.getPostalCode(), homeFolderAddress.getCity()) }); if (homeFolderMapping != null) { homeFolderMapping.setHomeFolderId(result.getId()); for (int i = 0; i < individuals.size(); i++) { homeFolderMapping.getIndividualsMappings().get(i).setIndividualId( individuals.get(i).getId()); } genericDAO.create(homeFolderMapping); // FIXME attribute all actions to the external service Gson gson = new Gson(); for (UserAction action : result.getActions()) { JsonObject payload = JSONUtils.deserialize(action.getData()); JsonObject user = payload.getAsJsonObject("user"); user.addProperty("name", homeFolderMapping.getExternalServiceLabel()); action.setData(gson.toJson(payload)); } homeFolderDAO.update(result); } HibernateUtil.commitTransaction(); hasCreations = true; } catch (Throwable t) { failures.writeNext(new String[]{homeFolder.getExternalId(), t.getMessage()}); HibernateUtil.rollbackTransaction(); hasFailures = true; } } creations.close(); duplicates.close(); failures.close(); Map<String, byte[]> attachments = new LinkedHashMap<String, byte[]>(); if (hasCreations) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.creations") + ".csv", creationsOutput.toByteArray()); } if (hasDuplicates) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.duplicates") + ".csv", duplicatesOutput.toByteArray()); } if (hasFailures) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.errors") + ".csv", failuresOutput.toByteArray()); } try { mailService.send(null, SecurityContext.getCurrentSite().getAdminEmail(), null, translationService.translate("homeFolder.import.notification.subject", new Object[]{ SecurityContext.getCurrentSite().getDisplayTitle() }), translationService.translate("homeFolder.import.notification.body"), attachments); } catch (CvqException e) { logger.error("importHomeFolders : could not notify result", e); } } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } public void setLocalAuthorityRegistry(ILocalAuthorityRegistry localAuthorityRegistry) { this.localAuthorityRegistry = localAuthorityRegistry; } public void setAuthenticationService(IAuthenticationService authenticationService) { this.authenticationService = authenticationService; } public void setMailService(IMailService mailService) { this.mailService = mailService; } public void setTranslationService(ITranslationService translationService) { this.translationService = translationService; } public void setUserService(IUserService userService) { this.userService = userService; } public void setUserNotificationService(IUserNotificationService userNotificationService) { this.userNotificationService = userNotificationService; } public void setUserSearchService(IUserSearchService userSearchService) { this.userSearchService = userSearchService; } public void setHomeFolderDAO(IHomeFolderDAO homeFolderDAO) { this.homeFolderDAO = homeFolderDAO; } public void setIndividualDAO(IIndividualDAO individualDAO) { this.individualDAO = individualDAO; } public IGenericDAO getGenericDAO() { return genericDAO; } public void setGenericDAO(IGenericDAO genericDAO) { this.genericDAO = genericDAO; } }
true
true
public void importHomeFolders(HomeFolderImportDocument doc) throws CvqException, IOException { SecurityContext.setCurrentContext(SecurityContext.ADMIN_CONTEXT); ByteArrayOutputStream creationsOutput = new ByteArrayOutputStream(); CSVWriter creations = new CSVWriter(new OutputStreamWriter(creationsOutput)); creations.writeNext(new String[] { translationService.translate("homeFolder.property.id"), translationService.translate("homeFolder.property.externalId"), translationService.translate("homeFolder.individual.property.firstName"), translationService.translate("homeFolder.individual.property.lastName"), translationService.translate("homeFolder.adult.property.login"), translationService.translate("homeFolder.adult.property.password"), translationService.translate("homeFolder.adult.property.email"), translationService.translate("homeFolder.individual.property.address") }); boolean hasCreations = false; ByteArrayOutputStream duplicatesOutput = new ByteArrayOutputStream(); CSVWriter duplicates = new CSVWriter(new OutputStreamWriter(duplicatesOutput)); duplicates.writeNext(new String[] { translationService.translate("homeFolder.property.externalId"), translationService.translate("homeFolder.individual.property.firstName"), translationService.translate("homeFolder.individual.property.lastName"), translationService.translate("homeFolder.adult.property.email"), translationService.translate("homeFolder.adult.property.homePhone"), translationService.translate("homeFolder.individual.property.address") }); boolean hasDuplicates = false; ByteArrayOutputStream failuresOutput = new ByteArrayOutputStream(); CSVWriter failures = new CSVWriter(new OutputStreamWriter(failuresOutput)); failures.writeNext(new String[] { translationService.translate("homeFolder.property.externalId"), translationService.translate("Error") }); boolean hasFailures = false; String label = doc.getHomeFolderImport().getExternalServiceLabel(); homeFolders : for (HomeFolderType homeFolder : doc.getHomeFolderImport().getHomeFolderArray()) { HibernateUtil.beginTransaction(); try { Adult responsible = null; List<Adult> adults = new ArrayList<Adult>(); List<Child> children = new ArrayList<Child>(); List<Individual> individuals = new ArrayList<Individual>(); HomeFolderMapping homeFolderMapping = null; if (label != null && homeFolder.getExternalId() != null) { homeFolderMapping = new HomeFolderMapping(label, null, homeFolder.getExternalId()); } Address homeFolderAddress = Address.xmlToModel(homeFolder.getAddress()); for (IndividualType individual : homeFolder.getIndividualsArray()) { String email = null; String phone = null; if (individual instanceof AdultType) { AdultType adult = (AdultType)individual; email = adult.getEmail(); phone = adult.getHomePhone(); Adult a = Adult.xmlToModel(adult); boolean isResponsible = false; Iterator<IndividualRole> it = a.getIndividualRoles().iterator(); while (it.hasNext()) { if (RoleType.HOME_FOLDER_RESPONSIBLE.equals(it.next().getRole())) { if (responsible != null) throw new CvqModelException("homeFolder.error.onlyOneResponsibleIsAllowed"); isResponsible = true; it.remove(); } } if (isResponsible) responsible = a; else adults.add(a); individuals.add(a); } else { Child c = Child.xmlToModel((ChildType)individual); children.add(c); individuals.add(c); } AddressType address = individual.getAddress(); if (individualDAO.hasSimilarIndividuals(individual.getFirstName(), individual.getLastName(), email, phone, address.getStreetNumber(), address.getStreetName(), address.getPostalCode(), address.getCity())) { duplicates.writeNext(new String[] { homeFolder.getExternalId(), individual.getFirstName(), individual.getLastName(), email, phone, address.getStreetNumber() == null ? String.format("%s %s %s", address.getStreetName(), address.getPostalCode(), address.getCity()) : String.format("%s %s %s %s", address.getStreetNumber(), address.getStreetName(), address.getPostalCode(), address.getCity()) }); hasDuplicates = true; continue homeFolders; } if (homeFolderMapping != null) { homeFolderMapping.getIndividualsMappings().add( new IndividualMapping(null, individual.getExternalId(), homeFolderMapping)); } } if (responsible == null) throw new CvqModelException("homeFolder.error.responsibleIsRequired"); HomeFolder result = create(responsible, false); HibernateUtil.getSession().flush(); for (Adult a : adults) add(result, a, false); adults.add(responsible); for (Child c : children) { add(result, c); for (Adult a : adults) { List<RoleType> roles = new ArrayList<RoleType>(); Iterator<IndividualRole> it = a.getIndividualRoles().iterator(); while (it.hasNext()) { IndividualRole role = it.next(); if (c.getFullName().equals(role.getIndividualName())) { roles.add(role.getRole()); it.remove(); genericDAO.delete(role); } } if (!roles.isEmpty()) { for (RoleType role : roles) link(a, c, Collections.singleton(role)); } } } HibernateUtil.getSession().flush(); for (Individual i : individuals) { List<String> errors = userService.validate(i); if (!errors.isEmpty()) throw new CvqValidationException(errors); } String password = authenticationService.generatePassword(); authenticationService.resetAdultPassword(responsible, password); creations.writeNext(new String[] { String.valueOf(result.getId()), homeFolder.getExternalId(), responsible.getFirstName(), responsible.getLastName(), responsible.getLogin(), password, responsible.getEmail(), homeFolderAddress.getStreetNumber() == null ? String.format("%s %s %s", homeFolderAddress.getStreetName(), homeFolderAddress.getPostalCode(), homeFolderAddress.getCity()) : String.format("%s %s %s %s", homeFolderAddress.getStreetNumber(), homeFolderAddress.getStreetName(), homeFolderAddress.getPostalCode(), homeFolderAddress.getCity()) }); if (homeFolderMapping != null) { homeFolderMapping.setHomeFolderId(result.getId()); for (int i = 0; i < individuals.size(); i++) { homeFolderMapping.getIndividualsMappings().get(i).setIndividualId( individuals.get(i).getId()); } genericDAO.create(homeFolderMapping); // FIXME attribute all actions to the external service Gson gson = new Gson(); for (UserAction action : result.getActions()) { JsonObject payload = JSONUtils.deserialize(action.getData()); JsonObject user = payload.getAsJsonObject("user"); user.addProperty("name", homeFolderMapping.getExternalServiceLabel()); action.setData(gson.toJson(payload)); } homeFolderDAO.update(result); } HibernateUtil.commitTransaction(); hasCreations = true; } catch (Throwable t) { failures.writeNext(new String[]{homeFolder.getExternalId(), t.getMessage()}); HibernateUtil.rollbackTransaction(); hasFailures = true; } } creations.close(); duplicates.close(); failures.close(); Map<String, byte[]> attachments = new LinkedHashMap<String, byte[]>(); if (hasCreations) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.creations") + ".csv", creationsOutput.toByteArray()); } if (hasDuplicates) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.duplicates") + ".csv", duplicatesOutput.toByteArray()); } if (hasFailures) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.errors") + ".csv", failuresOutput.toByteArray()); } try { mailService.send(null, SecurityContext.getCurrentSite().getAdminEmail(), null, translationService.translate("homeFolder.import.notification.subject", new Object[]{ SecurityContext.getCurrentSite().getDisplayTitle() }), translationService.translate("homeFolder.import.notification.body"), attachments); } catch (CvqException e) { logger.error("importHomeFolders : could not notify result", e); } }
public void importHomeFolders(HomeFolderImportDocument doc) throws CvqException, IOException { SecurityContext.setCurrentContext(SecurityContext.ADMIN_CONTEXT); ByteArrayOutputStream creationsOutput = new ByteArrayOutputStream(); CSVWriter creations = new CSVWriter(new OutputStreamWriter(creationsOutput)); creations.writeNext(new String[] { translationService.translate("homeFolder.property.id"), translationService.translate("homeFolder.property.externalId"), translationService.translate("homeFolder.individual.property.firstName"), translationService.translate("homeFolder.individual.property.lastName"), translationService.translate("homeFolder.adult.property.login"), translationService.translate("homeFolder.adult.property.password"), translationService.translate("homeFolder.adult.property.email"), translationService.translate("homeFolder.individual.property.address") }); boolean hasCreations = false; ByteArrayOutputStream duplicatesOutput = new ByteArrayOutputStream(); CSVWriter duplicates = new CSVWriter(new OutputStreamWriter(duplicatesOutput)); duplicates.writeNext(new String[] { translationService.translate("homeFolder.property.externalId"), translationService.translate("homeFolder.individual.property.firstName"), translationService.translate("homeFolder.individual.property.lastName"), translationService.translate("homeFolder.adult.property.email"), translationService.translate("homeFolder.adult.property.homePhone"), translationService.translate("homeFolder.individual.property.address") }); boolean hasDuplicates = false; ByteArrayOutputStream failuresOutput = new ByteArrayOutputStream(); CSVWriter failures = new CSVWriter(new OutputStreamWriter(failuresOutput)); failures.writeNext(new String[] { translationService.translate("homeFolder.property.externalId"), translationService.translate("Error") }); boolean hasFailures = false; String label = doc.getHomeFolderImport().getExternalServiceLabel(); homeFolders : for (HomeFolderType homeFolder : doc.getHomeFolderImport().getHomeFolderArray()) { HibernateUtil.beginTransaction(); try { Adult responsible = null; List<Adult> adults = new ArrayList<Adult>(); List<Child> children = new ArrayList<Child>(); List<Individual> individuals = new ArrayList<Individual>(); HomeFolderMapping homeFolderMapping = null; if (label != null && homeFolder.getExternalId() != null) { homeFolderMapping = new HomeFolderMapping(label, null, homeFolder.getExternalId()); } Address homeFolderAddress = Address.xmlToModel(homeFolder.getAddress()); for (IndividualType individual : homeFolder.getIndividualsArray()) { String email = null; String phone = null; if (individual instanceof AdultType) { AdultType adult = (AdultType)individual; email = adult.getEmail(); phone = adult.getHomePhone(); Adult a = Adult.xmlToModel(adult); boolean isResponsible = false; Iterator<IndividualRole> it = a.getIndividualRoles().iterator(); while (it.hasNext()) { if (RoleType.HOME_FOLDER_RESPONSIBLE.equals(it.next().getRole())) { if (responsible != null) throw new CvqModelException("homeFolder.error.onlyOneResponsibleIsAllowed"); isResponsible = true; it.remove(); } } if (isResponsible) responsible = a; else adults.add(a); individuals.add(a); } else { Child c = Child.xmlToModel((ChildType)individual); children.add(c); individuals.add(c); } AddressType address = individual.getAddress(); if (individualDAO.hasSimilarIndividuals(individual.getFirstName(), individual.getLastName(), email, phone, address.getStreetNumber(), address.getStreetName(), address.getPostalCode(), address.getCity())) { duplicates.writeNext(new String[] { homeFolder.getExternalId(), individual.getFirstName(), individual.getLastName(), email, phone, address.getStreetNumber() == null ? String.format("%s %s %s", address.getStreetName(), address.getPostalCode(), address.getCity()) : String.format("%s %s %s %s", address.getStreetNumber(), address.getStreetName(), address.getPostalCode(), address.getCity()) }); hasDuplicates = true; continue homeFolders; } if (homeFolderMapping != null) { homeFolderMapping.getIndividualsMappings().add( new IndividualMapping(null, individual.getExternalId(), homeFolderMapping)); } } if (responsible == null) throw new CvqModelException("homeFolder.error.responsibleIsRequired"); HomeFolder result = create(responsible, false); HibernateUtil.getSession().flush(); for (Adult a : adults) add(result, a, false); adults.add(responsible); for (Child c : children) { add(result, c); for (Adult a : adults) { List<RoleType> roles = new ArrayList<RoleType>(); Iterator<IndividualRole> it = a.getIndividualRoles().iterator(); while (it.hasNext()) { IndividualRole role = it.next(); if (role.getIndividualName() != null && c.getFullName().toUpperCase().equals(role.getIndividualName().toUpperCase())) { roles.add(role.getRole()); it.remove(); genericDAO.delete(role); } } if (!roles.isEmpty()) { for (RoleType role : roles) link(a, c, Collections.singleton(role)); } } } HibernateUtil.getSession().flush(); for (Individual i : individuals) { List<String> errors = userService.validate(i); if (!errors.isEmpty()) throw new CvqValidationException(errors); } String password = authenticationService.generatePassword(); authenticationService.resetAdultPassword(responsible, password); creations.writeNext(new String[] { String.valueOf(result.getId()), homeFolder.getExternalId(), responsible.getFirstName(), responsible.getLastName(), responsible.getLogin(), password, responsible.getEmail(), homeFolderAddress.getStreetNumber() == null ? String.format("%s %s %s", homeFolderAddress.getStreetName(), homeFolderAddress.getPostalCode(), homeFolderAddress.getCity()) : String.format("%s %s %s %s", homeFolderAddress.getStreetNumber(), homeFolderAddress.getStreetName(), homeFolderAddress.getPostalCode(), homeFolderAddress.getCity()) }); if (homeFolderMapping != null) { homeFolderMapping.setHomeFolderId(result.getId()); for (int i = 0; i < individuals.size(); i++) { homeFolderMapping.getIndividualsMappings().get(i).setIndividualId( individuals.get(i).getId()); } genericDAO.create(homeFolderMapping); // FIXME attribute all actions to the external service Gson gson = new Gson(); for (UserAction action : result.getActions()) { JsonObject payload = JSONUtils.deserialize(action.getData()); JsonObject user = payload.getAsJsonObject("user"); user.addProperty("name", homeFolderMapping.getExternalServiceLabel()); action.setData(gson.toJson(payload)); } homeFolderDAO.update(result); } HibernateUtil.commitTransaction(); hasCreations = true; } catch (Throwable t) { failures.writeNext(new String[]{homeFolder.getExternalId(), t.getMessage()}); HibernateUtil.rollbackTransaction(); hasFailures = true; } } creations.close(); duplicates.close(); failures.close(); Map<String, byte[]> attachments = new LinkedHashMap<String, byte[]>(); if (hasCreations) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.creations") + ".csv", creationsOutput.toByteArray()); } if (hasDuplicates) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.duplicates") + ".csv", duplicatesOutput.toByteArray()); } if (hasFailures) { attachments.put(translationService .translate("homeFolder.import.notification.attachmentName.errors") + ".csv", failuresOutput.toByteArray()); } try { mailService.send(null, SecurityContext.getCurrentSite().getAdminEmail(), null, translationService.translate("homeFolder.import.notification.subject", new Object[]{ SecurityContext.getCurrentSite().getDisplayTitle() }), translationService.translate("homeFolder.import.notification.body"), attachments); } catch (CvqException e) { logger.error("importHomeFolders : could not notify result", e); } }
diff --git a/impl/src/main/java/org/jboss/solder/exception/control/ExceptionHandledInterceptor.java b/impl/src/main/java/org/jboss/solder/exception/control/ExceptionHandledInterceptor.java index 344c5277..643475ec 100644 --- a/impl/src/main/java/org/jboss/solder/exception/control/ExceptionHandledInterceptor.java +++ b/impl/src/main/java/org/jboss/solder/exception/control/ExceptionHandledInterceptor.java @@ -1,70 +1,77 @@ /* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.solder.exception.control; import javax.enterprise.event.ObserverException; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; /** * @author <a href="http://community.jboss.org/people/LightGuard">Jason Porter</a> */ @Interceptor @ExceptionHandled public class ExceptionHandledInterceptor { @Inject private BeanManager bm; /** * Around invoke method implementation. * * @param ctx InvocationContext as defined by the Interceptor Spec. * @return value of {@link javax.interceptor.InvocationContext#proceed()}, unless an exception occurs, if the method returns a primitive the value * will be 0 for int, short, long, float and false for boolean. */ @AroundInvoke - public Object passExceptionsToSolderCatch(final InvocationContext ctx) throws Throwable { + public Object passExceptionsToSolderCatch(final InvocationContext ctx) throws Exception { Object result = null; try { result = ctx.proceed(); } catch (final Throwable e) { try { bm.fireEvent(new ExceptionToCatch(e)); } catch (Exception ex) { - if (ex.getClass().equals(ObserverException.class)) - throw ex.getCause(); + if (ex.getClass().equals(ObserverException.class)) { + if (ex.getCause() instanceof Exception) { + throw (Exception) ex.getCause(); + } else if (ex.getCause() instanceof Error) { + throw (Error) ex.getCause(); + } else { + throw new RuntimeException(ex.getCause()); + } + } } } if (ctx.getMethod().getReturnType().equals(Integer.TYPE) || ctx.getMethod().getReturnType().equals(Short.TYPE) || ctx.getMethod().getReturnType().equals(Long.TYPE) || ctx.getMethod().getReturnType().equals(Float.TYPE) || ctx.getMethod().getReturnType().equals(Byte.TYPE) || ctx.getMethod().getReturnType().equals(Double.TYPE)) return 0; if (ctx.getMethod().getReturnType().equals(Character.TYPE)) return '\u0000'; if (ctx.getMethod().getReturnType().equals(Boolean.TYPE)) return false; return result; } }
false
true
public Object passExceptionsToSolderCatch(final InvocationContext ctx) throws Throwable { Object result = null; try { result = ctx.proceed(); } catch (final Throwable e) { try { bm.fireEvent(new ExceptionToCatch(e)); } catch (Exception ex) { if (ex.getClass().equals(ObserverException.class)) throw ex.getCause(); } } if (ctx.getMethod().getReturnType().equals(Integer.TYPE) || ctx.getMethod().getReturnType().equals(Short.TYPE) || ctx.getMethod().getReturnType().equals(Long.TYPE) || ctx.getMethod().getReturnType().equals(Float.TYPE) || ctx.getMethod().getReturnType().equals(Byte.TYPE) || ctx.getMethod().getReturnType().equals(Double.TYPE)) return 0; if (ctx.getMethod().getReturnType().equals(Character.TYPE)) return '\u0000'; if (ctx.getMethod().getReturnType().equals(Boolean.TYPE)) return false; return result; }
public Object passExceptionsToSolderCatch(final InvocationContext ctx) throws Exception { Object result = null; try { result = ctx.proceed(); } catch (final Throwable e) { try { bm.fireEvent(new ExceptionToCatch(e)); } catch (Exception ex) { if (ex.getClass().equals(ObserverException.class)) { if (ex.getCause() instanceof Exception) { throw (Exception) ex.getCause(); } else if (ex.getCause() instanceof Error) { throw (Error) ex.getCause(); } else { throw new RuntimeException(ex.getCause()); } } } } if (ctx.getMethod().getReturnType().equals(Integer.TYPE) || ctx.getMethod().getReturnType().equals(Short.TYPE) || ctx.getMethod().getReturnType().equals(Long.TYPE) || ctx.getMethod().getReturnType().equals(Float.TYPE) || ctx.getMethod().getReturnType().equals(Byte.TYPE) || ctx.getMethod().getReturnType().equals(Double.TYPE)) return 0; if (ctx.getMethod().getReturnType().equals(Character.TYPE)) return '\u0000'; if (ctx.getMethod().getReturnType().equals(Boolean.TYPE)) return false; return result; }
diff --git a/basex-core/src/main/java/org/basex/gui/editor/Editor.java b/basex-core/src/main/java/org/basex/gui/editor/Editor.java index e131d5bc0..2c925b6d0 100644 --- a/basex-core/src/main/java/org/basex/gui/editor/Editor.java +++ b/basex-core/src/main/java/org/basex/gui/editor/Editor.java @@ -1,976 +1,977 @@ package org.basex.gui.editor; import static org.basex.core.Text.*; import static org.basex.gui.layout.BaseXKeys.*; import static org.basex.util.Token.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; import javax.swing.border.*; import org.basex.gui.*; import org.basex.gui.GUIConstants.Fill; import org.basex.gui.layout.*; import org.basex.io.*; import org.basex.util.*; /** * This class provides a text viewer and editor, using the * {@link Renderer} class to render the text. * * @author BaseX Team 2005-13, BSD License * @author Christian Gruen */ public class Editor extends BaseXPanel { /** Delay for highlighting an error. */ private static final int ERROR_DELAY = 500; /** Search direction. */ public enum SearchDir { /** Current hit. */ CURRENT, /** Next hit. */ FORWARD, /** Previous hit. */ BACKWARD, } /** Editor action. */ public enum Action { /** Check for changes; do nothing if input has not changed. */ CHECK, /** Enforce parsing of input. */ PARSE, /** Enforce execution of input. */ EXECUTE } /** Text array to be written. */ protected final transient EditorText text = new EditorText(EMPTY); /** Undo history. */ public transient History hist; /** Renderer reference. */ private final Renderer rend; /** Scrollbar reference. */ private final BaseXScrollBar scroll; /** Editable flag. */ private final boolean editable; /** Search bar. */ private SearchBar search; /** Link listener. */ private LinkListener linkListener; /** * Default constructor. * @param edit editable flag * @param win parent window */ public Editor(final boolean edit, final Window win) { this(edit, win, EMPTY); } /** * Default constructor. * @param edit editable flag * @param win parent window * @param txt initial text */ public Editor(final boolean edit, final Window win, final byte[] txt) { super(win); setFocusable(true); setFocusTraversalKeysEnabled(!edit); editable = edit; addMouseMotionListener(this); addMouseWheelListener(this); addComponentListener(this); addMouseListener(this); addKeyListener(this); addFocusListener(new FocusAdapter() { @Override public void focusGained(final FocusEvent e) { if(isEnabled()) cursor(true); } @Override public void focusLost(final FocusEvent e) { cursor(false); rend.cursor(false); } }); setFont(GUIConstants.dmfont); layout(new BorderLayout()); scroll = new BaseXScrollBar(this); rend = new Renderer(text, scroll, editable); add(rend, BorderLayout.CENTER); add(scroll, BorderLayout.EAST); setText(txt); hist = new History(edit ? text.text() : null); if(edit) { setBackground(Color.white); setBorder(new MatteBorder(1, 1, 0, 0, GUIConstants.color(6))); } else { mode(Fill.NONE); } new BaseXPopup(this, edit ? new GUICmd[] { new UndoCmd(), new RedoCmd(), null, new CutCmd(), new CopyCmd(), new PasteCmd(), new DelCmd(), null, new AllCmd() } : new GUICmd[] { new CopyCmd(), null, new AllCmd() }); } /** * Sets the output text. * @param t output text */ public void setText(final String t) { setText(token(t)); } /** * Sets the output text. * @param t output text */ public void setText(final byte[] t) { setText(t, t.length); resetError(); } /** * Returns the cursor coordinates. * @return line/column */ public final int[] pos() { return rend.pos(); } /** * Sets the output text. * @param t output text * @param s text size */ public final void setText(final byte[] t, final int s) { // remove invalid characters and compare old with new string int ns = 0; final int pc = text.getCaret(); final int ts = text.size(); final byte[] old = text.text(); boolean eq = true; for(int r = 0; r < s; ++r) { final byte b = t[r]; // ignore carriage return if(b != 0x0D) t[ns++] = t[r]; // support characters, highlighting codes, tabs and newlines eq &= ns < ts && ns < s && t[ns] == old[ns]; } eq &= ns == ts; // new text is different... if(!eq) text.text(Arrays.copyOf(t, ns)); if(hist != null) hist.store(t.length == ns ? t : Arrays.copyOf(t, ns), pc, 0); componentResized(null); } /** * Sets a syntax highlighter, based on the file format. * @param file file reference * @param opened indicates if file was opened from disk */ protected final void setSyntax(final IO file, final boolean opened) { setSyntax( !opened || file.hasSuffix(IO.XQSUFFIXES) ? new SyntaxXQuery() : file.hasSuffix(IO.JSONSUFFIX) ? new SyntaxJSON() : file.hasSuffix(IO.XMLSUFFIXES) || file.hasSuffix(IO.HTMLSUFFIXES) || file.hasSuffix(IO.XSLSUFFIXES) || file.hasSuffix(IO.BXSSUFFIX) ? new SyntaxXML() : Syntax.SIMPLE); } /** * Returns the editable flag. * @return boolean result */ public final boolean isEditable() { return editable; } /** * Sets a syntax highlighter. * @param s syntax reference */ public final void setSyntax(final Syntax s) { rend.setSyntax(s); } /** * Sets the text cursor to the specified position. A text selection will be removed. * @param p cursor position */ public final void setCaret(final int p) { text.setCaret(p); text.noSelect(); showCursor(1); cursor(true); } /** * Returns the current text cursor. * @return cursor position */ public final int getCaret() { return text.getCaret(); } /** * Jumps to the end of the text. */ public final void scrollToEnd() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { text.setCaret(text.size()); showCursor(2); } }); } /** * Returns the output text. * @return output text */ public final byte[] getText() { return text.text(); } /** * Tests if text has been selected. * @return result of check */ public final boolean selected() { return text.selected(); } @Override public final void setFont(final Font f) { super.setFont(f); if(rend != null) rend.setFont(f); } /** Thread counter. */ private int errorID; /** * Removes the error marker. */ public final void resetError() { ++errorID; text.error(-1); rend.repaint(); } /** * Sets the error marker. * @param pos start of optional error mark */ public final void error(final int pos) { final int eid = ++errorID; text.error(pos); new Thread() { @Override public void run() { Performance.sleep(ERROR_DELAY); if(eid == errorID) rend.repaint(); } }.start(); } @Override public final void setEnabled(final boolean e) { super.setEnabled(e); rend.setEnabled(e); scroll.setEnabled(e); cursor(e); } /** * Selects the whole text. */ final void selectAll() { final int s = text.size(); text.select(0, s); text.setCaret(s); rend.repaint(); } // SEARCH OPERATIONS ================================================================== /** * Installs a link listener. * @param ll link listener */ public final void setLinkListener(final LinkListener ll) { linkListener = ll; } /** * Installs a search bar. * @param s search bar */ final void setSearch(final SearchBar s) { search = s; } /** * Returns the search bar. * @return search bar */ public final SearchBar getSearch() { return search; } /** * Performs a search. * @param sc search context * @param jump jump to next hit */ final void search(final SearchContext sc, final boolean jump) { try { rend.search(sc); gui.status.setText(sc.search.isEmpty() ? OK : Util.info(STRINGS_FOUND_X, sc.nr())); if(jump) jump(SearchDir.CURRENT, false); } catch(final Exception ex) { final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", ""); gui.status.setError(REGULAR_EXPR + COLS + msg); } } /** * Replaces the text. * @param rc replace context */ final void replace(final ReplaceContext rc) { try { final int[] select = rend.replace(rc); if(rc.text != null) { final boolean sel = text.selected(); setText(rc.text); if(sel) text.select(select[0], select[1]); text.setCaret(select[0]); release(Action.CHECK); } gui.status.setText(Util.info(STRINGS_REPLACED)); } catch(final Exception ex) { final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", ""); gui.status.setError(REGULAR_EXPR + COLS + msg); } } /** * Jumps to a search string. * @param dir search direction * @param select select hit */ final void jump(final SearchDir dir, final boolean select) { // updates the visible area final int y = rend.jump(dir, select); final int h = getHeight(); final int p = scroll.pos(); final int m = y + rend.fontHeight() * 3 - h; if(y != -1 && (p < m || p > y)) scroll.pos(y - h / 2); rend.repaint(); } // MOUSE INTERACTIONS ================================================================= @Override public final void mouseEntered(final MouseEvent e) { gui.cursor(GUIConstants.CURSORTEXT); } @Override public final void mouseExited(final MouseEvent e) { gui.cursor(GUIConstants.CURSORARROW); } @Override public final void mouseMoved(final MouseEvent e) { if(linkListener == null) return; final boolean link = rend.link(scroll.pos(), e.getPoint()); gui.cursor(link ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW); } @Override public void mouseReleased(final MouseEvent e) { if(SwingUtilities.isLeftMouseButton(e)) { text.checkSelect(); // evaluate link if(!text.selected() && rend.link(scroll.pos(), e.getPoint())) linkListener.linkClicked(rend.link()); } } @Override public void mouseClicked(final MouseEvent e) { if(!SwingUtilities.isMiddleMouseButton(e)) return; new PasteCmd().execute(gui); } @Override public final void mouseDragged(final MouseEvent e) { if(!SwingUtilities.isLeftMouseButton(e)) return; // selection mode rend.select(scroll.pos(), e.getPoint(), false); final int y = Math.max(20, Math.min(e.getY(), getHeight() - 20)); if(y != e.getY()) scroll.pos(scroll.pos() + e.getY() - y); } @Override public final void mousePressed(final MouseEvent e) { if(!isEnabled() || !isFocusable()) return; requestFocusInWindow(); cursor(true); if(SwingUtilities.isMiddleMouseButton(e)) copy(); final boolean marking = e.isShiftDown(); final boolean nomark = !text.selecting(); if(SwingUtilities.isLeftMouseButton(e)) { final int c = e.getClickCount(); if(c == 1) { // selection mode if(marking && nomark) text.startSelect(); rend.select(scroll.pos(), e.getPoint(), !marking); } else if(c == 2) { text.selectWord(); } else { text.selectLine(); } } else if(nomark) { rend.select(scroll.pos(), e.getPoint(), true); } } // KEY INTERACTIONS ======================================================= @Override public void keyPressed(final KeyEvent e) { // handle search operations if(search != null) { if(ESCAPE.is(e)) { search.deactivate(true); return; } if(FIND.is(e)) { search.activate(text.copy(), true); return; } if(FINDNEXT.is(e) || FINDNEXT2.is(e) || FINDPREV.is(e) || FINDPREV2.is(e)) { final boolean vis = search.isVisible(); search.activate(text.copy(), false); jump(vis ? FINDNEXT.is(e) || FINDNEXT2.is(e) ? SearchDir.FORWARD : SearchDir.BACKWARD : SearchDir.CURRENT, true); return; } } // ignore modifier keys if(modifier(e)) return; if(PREVTAB.is(e)) { gui.editor.tab(false); e.consume(); } else if(NEXTTAB.is(e)) { gui.editor.tab(true); e.consume(); } else if(CLOSETAB.is(e)) { gui.editor.close(null); } // re-animate cursor cursor(true); // operations without cursor movement... final int fh = rend.fontHeight(); if(SCROLLDOWN.is(e)) { scroll.pos(scroll.pos() + fh); return; } if(SCROLLUP.is(e)) { scroll.pos(scroll.pos() - fh); return; } if(COPY1.is(e) || COPY2.is(e)) { copy(); return; } // set cursor position and reset last column final int pc = text.getCaret(); text.pos(pc); if(!PREVLINE.is(e) && !NEXTLINE.is(e)) lastCol = -1; if(SELECTALL.is(e)) { selectAll(); return; } // necessary on Macs as the shift button is pressed for REDO final boolean marking = e.isShiftDown() && !DELNEXT.is(e) && !DELPREV.is(e) && !PASTE2.is(e) && !COMMENT.is(e) && !DELLINE.is(e) && !REDOSTEP.is(e) && !PREVPAGE_RO.is(e); final boolean nomark = !text.selecting(); if(marking && nomark) text.startSelect(); boolean down = true; boolean consumed = true; // operations that consider the last text mark.. final byte[] txt = text.text(); if(NEXTWORD.is(e)) { text.nextToken(marking); } else if(PREVWORD.is(e)) { text.prevToken(marking); down = false; } else if(TEXTSTART.is(e)) { if(!marking) text.noSelect(); text.pos(0); down = false; } else if(TEXTEND.is(e)) { if(!marking) text.noSelect(); text.pos(text.size()); } else if(LINESTART.is(e)) { text.home(marking); down = false; } else if(LINEEND.is(e)) { text.eol(marking); } else if(PREVPAGE.is(e) || !hist.active() && PREVPAGE_RO.is(e)) { up(getHeight() / fh, marking); down = false; } else if(NEXTPAGE.is(e) || !hist.active() && NEXTPAGE_RO.is(e)) { down(getHeight() / fh, marking); } else if(NEXT.is(e)) { text.next(marking); } else if(PREV.is(e)) { text.prev(marking); down = false; } else if(PREVLINE.is(e)) { up(1, marking); down = false; } else if(NEXTLINE.is(e)) { down(1, marking); } else { consumed = false; } if(marking) { // refresh scroll position text.finishSelect(); } else if(hist.active()) { // edit operations... if(CUT1.is(e) || CUT2.is(e)) { if(copy()) text.delete(); } else if(PASTE1.is(e) || PASTE2.is(e)) { final String clip = clip(); if(clip != null) { if(text.selected()) text.delete(); text.add(clip); } } else if(UNDOSTEP.is(e)) { final byte[] t = hist.prev(); if(t != null) { text.text(t); text.pos(hist.cursor()); } } else if(REDOSTEP.is(e)) { final byte[] t = hist.next(); if(t != null) { text.text(t); text.pos(hist.cursor()); } } else if(COMMENT.is(e)) { text.comment(rend.getSyntax()); } else if(COMPLETE.is(e)) { text.complete(); } else if(DELLINE.is(e)) { text.deleteLine(); } else if(DELLINEEND.is(e) || DELNEXTWORD.is(e) || DELNEXT.is(e)) { if(nomark) { if(text.pos() == text.size()) return; text.startSelect(); if(DELNEXTWORD.is(e)) { text.nextToken(true); } else if(DELLINEEND.is(e)) { text.eol(true); } else { text.next(true); } text.finishSelect(); } text.delete(); } else if(DELLINESTART.is(e) || DELPREVWORD.is(e) || DELPREV.is(e)) { if(nomark) { if(text.pos() == 0) return; if(DELPREVWORD.is(e)) { text.startSelect(); text.prevToken(true); text.finishSelect(); } else if(DELLINESTART.is(e)) { text.startSelect(); text.bol(true); + text.finishSelect(); } else { text.backspace(); } } text.delete(); down = false; } else { consumed = false; } } if(consumed) e.consume(); text.setCaret(); final byte[] tmp = text.text(); if(txt == tmp) { showCursor(down ? 2 : 0); } else { hist.store(tmp, pc, text.getCaret()); calcCode.invokeLater(down); } } /** Thread counter. */ private final GUICode calcCode = new GUICode() { @Override public void eval(final Object arg) { rend.calc(); showCursor((Boolean) arg ? 2 : 0); } }; /** Thread counter. */ private final GUICode cursorCode = new GUICode() { @Override public void eval(final Object arg) { // updates the visible area final int p = scroll.pos(); final int y = rend.cursorY(); final int m = y + rend.fontHeight() * 3 - getHeight(); if(p < m || p > y) { final int align = (Integer) arg; scroll.pos(align == 0 ? y : align == 1 ? y - getHeight() / 2 : m); rend.repaint(); } } }; /** * Displays the currently edited text area. * @param align vertical alignment */ final void showCursor(final int align) { cursorCode.invokeLater(align); } /** * Moves the cursor down. The current column position is remembered in * {@link #lastCol} and, if possible, restored. * @param l number of lines to move cursor * @param mark mark flag */ private void down(final int l, final boolean mark) { if(!mark) text.noSelect(); final int x = text.bol(mark); if(lastCol == -1) lastCol = x; for(int i = 0; i < l; ++i) { text.eol(mark); text.next(mark); } text.forward(lastCol, mark); if(text.pos() == text.size()) lastCol = -1; } /** * Moves the cursor up. * @param l number of lines to move cursor * @param mark mark flag */ private void up(final int l, final boolean mark) { if(!mark) text.noSelect(); final int x = text.bol(mark); if(lastCol == -1) lastCol = x; if(text.pos() == 0) { lastCol = -1; return; } for(int i = 0; i < l; ++i) { text.prev(mark); text.bol(mark); } text.forward(lastCol, mark); } /** Last horizontal position. */ private int lastCol = -1; @Override public void keyTyped(final KeyEvent e) { if(!hist.active() || control(e) || DELNEXT.is(e) || DELPREV.is(e) || ESCAPE.is(e)) return; int pc = text.getCaret(); text.pos(pc); // remember if marked text is to be deleted final StringBuilder sb = new StringBuilder(1).append(e.getKeyChar()); final boolean indent = TAB.is(e) && text.indent(sb, e.isShiftDown()); // delete marked text final boolean selected = text.selected() && !indent; if(selected) text.delete(); final int ps = text.pos(); final int move = ENTER.is(e) ? text.enter(sb) : text.add(sb, selected); // refresh history and adjust cursor position hist.store(text.text(), pc, text.getCaret()); if(move != 0) text.setCaret(Math.min(text.size(), ps + move)); // adjust text height calcCode.invokeLater(true); e.consume(); } /** * Releases a key or mouse. Can be overwritten to react on events. * @param action action */ @SuppressWarnings("unused") protected void release(final Action action) { } // EDITOR COMMANDS ========================================================== /** * Copies the selected text to the clipboard. * @return true if text was copied */ final boolean copy() { final String txt = text.copy(); if(txt.isEmpty()) { text.noSelect(); return false; } // copy selection to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); clip.setContents(new StringSelection(txt), null); return true; } /** * Returns the clipboard text. * @return text */ private static String clip() { // copy selection to clipboard final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); final Transferable tr = clip.getContents(null); if(tr != null) for(final Object o : BaseXLayout.contents(tr)) return o.toString(); return null; } /** * Finishes a command. * @param old old cursor position; store entry to history if position != -1 */ void finish(final int old) { text.setCaret(); if(old != -1) hist.store(text.text(), old, text.getCaret()); calcCode.invokeLater(true); release(Action.CHECK); } /** Cursor. */ private final Timer cursor = new Timer(500, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { rend.cursor(!rend.cursor()); } }); /** * Stops an old cursor thread and, if requested, starts a new one. * @param start start/stop flag */ final void cursor(final boolean start) { cursor.stop(); if(start) cursor.start(); rend.cursor(start); } @Override public final void mouseWheelMoved(final MouseWheelEvent e) { scroll.pos(scroll.pos() + e.getUnitsToScroll() * 20); rend.repaint(); } /** Calculation counter. */ private final GUICode resizeCode = new GUICode() { @Override public void eval(final Object arg) { rend.calc(); // update scrollbar to display value within valid range scroll.pos(scroll.pos()); rend.repaint(); } }; @Override public final void componentResized(final ComponentEvent e) { resizeCode.invokeLater(); } /** Undo command. */ class UndoCmd extends GUIBaseCmd { @Override public void execute(final GUI main) { if(!hist.active()) return; final byte[] t = hist.prev(); if(t == null) return; text.text(t); text.pos(hist.cursor()); finish(-1); } @Override public boolean enabled(final GUI main) { return !hist.first(); } @Override public String label() { return UNDO; } } /** Redo command. */ class RedoCmd extends GUIBaseCmd { @Override public void execute(final GUI main) { if(!hist.active()) return; final byte[] t = hist.next(); if(t == null) return; text.text(t); text.pos(hist.cursor()); finish(-1); } @Override public boolean enabled(final GUI mein) { return !hist.last(); } @Override public String label() { return REDO; } } /** Cut command. */ class CutCmd extends GUIBaseCmd { @Override public void execute(final GUI main) { if(!hist.active()) return; final int tc = text.getCaret(); text.pos(tc); if(!copy()) return; text.delete(); text.setCaret(); finish(tc); } @Override public boolean enabled(final GUI main) { return text.selected(); } @Override public String label() { return CUT; } } /** Copy command. */ class CopyCmd extends GUIBaseCmd { @Override public void execute(final GUI main) { copy(); } @Override public boolean enabled(final GUI main) { return text.selected(); } @Override public String label() { return COPY; } } /** Paste command. */ class PasteCmd extends GUIBaseCmd { @Override public void execute(final GUI main) { if(!hist.active()) return; final int tc = text.getCaret(); text.pos(tc); final String clip = clip(); if(clip == null) return; if(text.selected()) text.delete(); text.add(clip); finish(tc); } @Override public boolean enabled(final GUI main) { return clip() != null; } @Override public String label() { return PASTE; } } /** Delete command. */ class DelCmd extends GUIBaseCmd { @Override public void execute(final GUI main) { if(!hist.active()) return; final int tc = text.getCaret(); text.pos(tc); text.delete(); finish(tc); } @Override public boolean enabled(final GUI main) { return text.selected(); } @Override public String label() { return DELETE; } } /** Select all command. */ class AllCmd extends GUIBaseCmd { @Override public void execute(final GUI main) { selectAll(); } @Override public String label() { return SELECT_ALL; } } }
true
true
public void keyPressed(final KeyEvent e) { // handle search operations if(search != null) { if(ESCAPE.is(e)) { search.deactivate(true); return; } if(FIND.is(e)) { search.activate(text.copy(), true); return; } if(FINDNEXT.is(e) || FINDNEXT2.is(e) || FINDPREV.is(e) || FINDPREV2.is(e)) { final boolean vis = search.isVisible(); search.activate(text.copy(), false); jump(vis ? FINDNEXT.is(e) || FINDNEXT2.is(e) ? SearchDir.FORWARD : SearchDir.BACKWARD : SearchDir.CURRENT, true); return; } } // ignore modifier keys if(modifier(e)) return; if(PREVTAB.is(e)) { gui.editor.tab(false); e.consume(); } else if(NEXTTAB.is(e)) { gui.editor.tab(true); e.consume(); } else if(CLOSETAB.is(e)) { gui.editor.close(null); } // re-animate cursor cursor(true); // operations without cursor movement... final int fh = rend.fontHeight(); if(SCROLLDOWN.is(e)) { scroll.pos(scroll.pos() + fh); return; } if(SCROLLUP.is(e)) { scroll.pos(scroll.pos() - fh); return; } if(COPY1.is(e) || COPY2.is(e)) { copy(); return; } // set cursor position and reset last column final int pc = text.getCaret(); text.pos(pc); if(!PREVLINE.is(e) && !NEXTLINE.is(e)) lastCol = -1; if(SELECTALL.is(e)) { selectAll(); return; } // necessary on Macs as the shift button is pressed for REDO final boolean marking = e.isShiftDown() && !DELNEXT.is(e) && !DELPREV.is(e) && !PASTE2.is(e) && !COMMENT.is(e) && !DELLINE.is(e) && !REDOSTEP.is(e) && !PREVPAGE_RO.is(e); final boolean nomark = !text.selecting(); if(marking && nomark) text.startSelect(); boolean down = true; boolean consumed = true; // operations that consider the last text mark.. final byte[] txt = text.text(); if(NEXTWORD.is(e)) { text.nextToken(marking); } else if(PREVWORD.is(e)) { text.prevToken(marking); down = false; } else if(TEXTSTART.is(e)) { if(!marking) text.noSelect(); text.pos(0); down = false; } else if(TEXTEND.is(e)) { if(!marking) text.noSelect(); text.pos(text.size()); } else if(LINESTART.is(e)) { text.home(marking); down = false; } else if(LINEEND.is(e)) { text.eol(marking); } else if(PREVPAGE.is(e) || !hist.active() && PREVPAGE_RO.is(e)) { up(getHeight() / fh, marking); down = false; } else if(NEXTPAGE.is(e) || !hist.active() && NEXTPAGE_RO.is(e)) { down(getHeight() / fh, marking); } else if(NEXT.is(e)) { text.next(marking); } else if(PREV.is(e)) { text.prev(marking); down = false; } else if(PREVLINE.is(e)) { up(1, marking); down = false; } else if(NEXTLINE.is(e)) { down(1, marking); } else { consumed = false; } if(marking) { // refresh scroll position text.finishSelect(); } else if(hist.active()) { // edit operations... if(CUT1.is(e) || CUT2.is(e)) { if(copy()) text.delete(); } else if(PASTE1.is(e) || PASTE2.is(e)) { final String clip = clip(); if(clip != null) { if(text.selected()) text.delete(); text.add(clip); } } else if(UNDOSTEP.is(e)) { final byte[] t = hist.prev(); if(t != null) { text.text(t); text.pos(hist.cursor()); } } else if(REDOSTEP.is(e)) { final byte[] t = hist.next(); if(t != null) { text.text(t); text.pos(hist.cursor()); } } else if(COMMENT.is(e)) { text.comment(rend.getSyntax()); } else if(COMPLETE.is(e)) { text.complete(); } else if(DELLINE.is(e)) { text.deleteLine(); } else if(DELLINEEND.is(e) || DELNEXTWORD.is(e) || DELNEXT.is(e)) { if(nomark) { if(text.pos() == text.size()) return; text.startSelect(); if(DELNEXTWORD.is(e)) { text.nextToken(true); } else if(DELLINEEND.is(e)) { text.eol(true); } else { text.next(true); } text.finishSelect(); } text.delete(); } else if(DELLINESTART.is(e) || DELPREVWORD.is(e) || DELPREV.is(e)) { if(nomark) { if(text.pos() == 0) return; if(DELPREVWORD.is(e)) { text.startSelect(); text.prevToken(true); text.finishSelect(); } else if(DELLINESTART.is(e)) { text.startSelect(); text.bol(true); } else { text.backspace(); } } text.delete(); down = false; } else { consumed = false; } } if(consumed) e.consume(); text.setCaret(); final byte[] tmp = text.text(); if(txt == tmp) { showCursor(down ? 2 : 0); } else { hist.store(tmp, pc, text.getCaret()); calcCode.invokeLater(down); } }
public void keyPressed(final KeyEvent e) { // handle search operations if(search != null) { if(ESCAPE.is(e)) { search.deactivate(true); return; } if(FIND.is(e)) { search.activate(text.copy(), true); return; } if(FINDNEXT.is(e) || FINDNEXT2.is(e) || FINDPREV.is(e) || FINDPREV2.is(e)) { final boolean vis = search.isVisible(); search.activate(text.copy(), false); jump(vis ? FINDNEXT.is(e) || FINDNEXT2.is(e) ? SearchDir.FORWARD : SearchDir.BACKWARD : SearchDir.CURRENT, true); return; } } // ignore modifier keys if(modifier(e)) return; if(PREVTAB.is(e)) { gui.editor.tab(false); e.consume(); } else if(NEXTTAB.is(e)) { gui.editor.tab(true); e.consume(); } else if(CLOSETAB.is(e)) { gui.editor.close(null); } // re-animate cursor cursor(true); // operations without cursor movement... final int fh = rend.fontHeight(); if(SCROLLDOWN.is(e)) { scroll.pos(scroll.pos() + fh); return; } if(SCROLLUP.is(e)) { scroll.pos(scroll.pos() - fh); return; } if(COPY1.is(e) || COPY2.is(e)) { copy(); return; } // set cursor position and reset last column final int pc = text.getCaret(); text.pos(pc); if(!PREVLINE.is(e) && !NEXTLINE.is(e)) lastCol = -1; if(SELECTALL.is(e)) { selectAll(); return; } // necessary on Macs as the shift button is pressed for REDO final boolean marking = e.isShiftDown() && !DELNEXT.is(e) && !DELPREV.is(e) && !PASTE2.is(e) && !COMMENT.is(e) && !DELLINE.is(e) && !REDOSTEP.is(e) && !PREVPAGE_RO.is(e); final boolean nomark = !text.selecting(); if(marking && nomark) text.startSelect(); boolean down = true; boolean consumed = true; // operations that consider the last text mark.. final byte[] txt = text.text(); if(NEXTWORD.is(e)) { text.nextToken(marking); } else if(PREVWORD.is(e)) { text.prevToken(marking); down = false; } else if(TEXTSTART.is(e)) { if(!marking) text.noSelect(); text.pos(0); down = false; } else if(TEXTEND.is(e)) { if(!marking) text.noSelect(); text.pos(text.size()); } else if(LINESTART.is(e)) { text.home(marking); down = false; } else if(LINEEND.is(e)) { text.eol(marking); } else if(PREVPAGE.is(e) || !hist.active() && PREVPAGE_RO.is(e)) { up(getHeight() / fh, marking); down = false; } else if(NEXTPAGE.is(e) || !hist.active() && NEXTPAGE_RO.is(e)) { down(getHeight() / fh, marking); } else if(NEXT.is(e)) { text.next(marking); } else if(PREV.is(e)) { text.prev(marking); down = false; } else if(PREVLINE.is(e)) { up(1, marking); down = false; } else if(NEXTLINE.is(e)) { down(1, marking); } else { consumed = false; } if(marking) { // refresh scroll position text.finishSelect(); } else if(hist.active()) { // edit operations... if(CUT1.is(e) || CUT2.is(e)) { if(copy()) text.delete(); } else if(PASTE1.is(e) || PASTE2.is(e)) { final String clip = clip(); if(clip != null) { if(text.selected()) text.delete(); text.add(clip); } } else if(UNDOSTEP.is(e)) { final byte[] t = hist.prev(); if(t != null) { text.text(t); text.pos(hist.cursor()); } } else if(REDOSTEP.is(e)) { final byte[] t = hist.next(); if(t != null) { text.text(t); text.pos(hist.cursor()); } } else if(COMMENT.is(e)) { text.comment(rend.getSyntax()); } else if(COMPLETE.is(e)) { text.complete(); } else if(DELLINE.is(e)) { text.deleteLine(); } else if(DELLINEEND.is(e) || DELNEXTWORD.is(e) || DELNEXT.is(e)) { if(nomark) { if(text.pos() == text.size()) return; text.startSelect(); if(DELNEXTWORD.is(e)) { text.nextToken(true); } else if(DELLINEEND.is(e)) { text.eol(true); } else { text.next(true); } text.finishSelect(); } text.delete(); } else if(DELLINESTART.is(e) || DELPREVWORD.is(e) || DELPREV.is(e)) { if(nomark) { if(text.pos() == 0) return; if(DELPREVWORD.is(e)) { text.startSelect(); text.prevToken(true); text.finishSelect(); } else if(DELLINESTART.is(e)) { text.startSelect(); text.bol(true); text.finishSelect(); } else { text.backspace(); } } text.delete(); down = false; } else { consumed = false; } } if(consumed) e.consume(); text.setCaret(); final byte[] tmp = text.text(); if(txt == tmp) { showCursor(down ? 2 : 0); } else { hist.store(tmp, pc, text.getCaret()); calcCode.invokeLater(down); } }
diff --git a/src/cz/dagblog/echo2blogger/Main.java b/src/cz/dagblog/echo2blogger/Main.java index 126c963..e295ec8 100644 --- a/src/cz/dagblog/echo2blogger/Main.java +++ b/src/cz/dagblog/echo2blogger/Main.java @@ -1,38 +1,38 @@ package cz.dagblog.echo2blogger; import java.util.List; import java.util.logging.Logger; public class Main { private static final Logger log = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws Exception { if(args.length != 4) { - System.out.println("Missing input arguments: username, password, blog id for access to Blogger and registered site name for access to Echo service.\n Example java -jar echo2blogger [email protected] secret 4053149 dagblog.cz"); + System.out.println("Missing input arguments: username, password, blog id for access to Blogger and registered site name for access to Echo service.\n Example java -jar echo-to-blogger.jar [email protected] secret 4053149 dagblog.cz"); System.exit(0); } log.info("Starting comments migration from Echo service for site " + args[3] + " to Blogger for blog " + args[0] + ". There is known limitation of Blogger API, a custom author for comments is currently not supported. All new comments will appear as if they were created by the currently authenticated user. An original author is preserved on first line of comment."); log.warning("Existing comments will be overwritten. Do you want to still continue? Please press any key for continue..."); System.in.read(); log.warning("Please temporary disable Blogger comments email notification otherwise your maibox will blow up? Please press any key for continue..."); System.in.read(); log.warning("Migration process may take serious amount of time regarding to count of comments. You may break this process anytime and start from the beginning."); Blogger blogger = new Blogger(args[0], args[1], args[2]); Echo echo = new Echo(args[3]); List<String> ids = blogger.fetchPostIds(); int commentsCounter = 0; for (String id : ids) { List<Echo.Comment> comments = echo.fetchComments(id); if(comments.size() > 0) { log.info("Transfering comments for post " + id); commentsCounter += comments.size(); log.info("Number of comments " + comments.size()); blogger.createOrUpdateComments(id, comments); } break; } log.info("Migration process finished. Totaly transfered " + commentsCounter + " comments"); } }
true
true
public static void main(String[] args) throws Exception { if(args.length != 4) { System.out.println("Missing input arguments: username, password, blog id for access to Blogger and registered site name for access to Echo service.\n Example java -jar echo2blogger [email protected] secret 4053149 dagblog.cz"); System.exit(0); } log.info("Starting comments migration from Echo service for site " + args[3] + " to Blogger for blog " + args[0] + ". There is known limitation of Blogger API, a custom author for comments is currently not supported. All new comments will appear as if they were created by the currently authenticated user. An original author is preserved on first line of comment."); log.warning("Existing comments will be overwritten. Do you want to still continue? Please press any key for continue..."); System.in.read(); log.warning("Please temporary disable Blogger comments email notification otherwise your maibox will blow up? Please press any key for continue..."); System.in.read(); log.warning("Migration process may take serious amount of time regarding to count of comments. You may break this process anytime and start from the beginning."); Blogger blogger = new Blogger(args[0], args[1], args[2]); Echo echo = new Echo(args[3]); List<String> ids = blogger.fetchPostIds(); int commentsCounter = 0; for (String id : ids) { List<Echo.Comment> comments = echo.fetchComments(id); if(comments.size() > 0) { log.info("Transfering comments for post " + id); commentsCounter += comments.size(); log.info("Number of comments " + comments.size()); blogger.createOrUpdateComments(id, comments); } break; } log.info("Migration process finished. Totaly transfered " + commentsCounter + " comments"); }
public static void main(String[] args) throws Exception { if(args.length != 4) { System.out.println("Missing input arguments: username, password, blog id for access to Blogger and registered site name for access to Echo service.\n Example java -jar echo-to-blogger.jar [email protected] secret 4053149 dagblog.cz"); System.exit(0); } log.info("Starting comments migration from Echo service for site " + args[3] + " to Blogger for blog " + args[0] + ". There is known limitation of Blogger API, a custom author for comments is currently not supported. All new comments will appear as if they were created by the currently authenticated user. An original author is preserved on first line of comment."); log.warning("Existing comments will be overwritten. Do you want to still continue? Please press any key for continue..."); System.in.read(); log.warning("Please temporary disable Blogger comments email notification otherwise your maibox will blow up? Please press any key for continue..."); System.in.read(); log.warning("Migration process may take serious amount of time regarding to count of comments. You may break this process anytime and start from the beginning."); Blogger blogger = new Blogger(args[0], args[1], args[2]); Echo echo = new Echo(args[3]); List<String> ids = blogger.fetchPostIds(); int commentsCounter = 0; for (String id : ids) { List<Echo.Comment> comments = echo.fetchComments(id); if(comments.size() > 0) { log.info("Transfering comments for post " + id); commentsCounter += comments.size(); log.info("Number of comments " + comments.size()); blogger.createOrUpdateComments(id, comments); } break; } log.info("Migration process finished. Totaly transfered " + commentsCounter + " comments"); }
diff --git a/plugins/org.eclipse.gmf.graphdef.codegen/src/org/eclipse/gmf/internal/graphdef/codegen/Activator.java b/plugins/org.eclipse.gmf.graphdef.codegen/src/org/eclipse/gmf/internal/graphdef/codegen/Activator.java index 9d1e83bb2..390b941a5 100644 --- a/plugins/org.eclipse.gmf.graphdef.codegen/src/org/eclipse/gmf/internal/graphdef/codegen/Activator.java +++ b/plugins/org.eclipse.gmf.graphdef.codegen/src/org/eclipse/gmf/internal/graphdef/codegen/Activator.java @@ -1,56 +1,56 @@ /* * Copyright (c) 2006, 2007 Borland Software Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Artem Tikhomirov (Borland) - initial API and implementation */ package org.eclipse.gmf.internal.graphdef.codegen; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.core.runtime.Plugin; import org.eclipse.gmf.graphdef.codegen.MapModeCodeGenStrategy; import org.eclipse.gmf.internal.xpand.ResourceManager; import org.eclipse.gmf.internal.xpand.util.BundleResourceManager; import org.osgi.framework.BundleContext; public class Activator extends Plugin { private static Activator instance; public Activator() { instance = this; } @Override public void stop(BundleContext context) throws Exception { instance = null; super.stop(context); } public static ResourceManager createResourceEngine(MapModeCodeGenStrategy strategy, URL... dynamicTemplates) { try { URL baseURL = instance.getBundle().getEntry("/templates.migrated/"); ArrayList<URL> urls = new ArrayList<URL>(3); if (dynamicTemplates != null) { // XXX perhaps, add strategy token to each url // to keep dynamic template structure similar to those bundled? urls.addAll(Arrays.asList(dynamicTemplates)); } if (strategy.getToken().length() > 0) { urls.add(new URL(baseURL, strategy.getToken() + '/')); } urls.add(baseURL); return new BundleResourceManager(urls.toArray(new URL[urls.size()])); } catch (MalformedURLException ex) { - throw new Error(); + throw new Error(ex); } } }
true
true
public static ResourceManager createResourceEngine(MapModeCodeGenStrategy strategy, URL... dynamicTemplates) { try { URL baseURL = instance.getBundle().getEntry("/templates.migrated/"); ArrayList<URL> urls = new ArrayList<URL>(3); if (dynamicTemplates != null) { // XXX perhaps, add strategy token to each url // to keep dynamic template structure similar to those bundled? urls.addAll(Arrays.asList(dynamicTemplates)); } if (strategy.getToken().length() > 0) { urls.add(new URL(baseURL, strategy.getToken() + '/')); } urls.add(baseURL); return new BundleResourceManager(urls.toArray(new URL[urls.size()])); } catch (MalformedURLException ex) { throw new Error(); } }
public static ResourceManager createResourceEngine(MapModeCodeGenStrategy strategy, URL... dynamicTemplates) { try { URL baseURL = instance.getBundle().getEntry("/templates.migrated/"); ArrayList<URL> urls = new ArrayList<URL>(3); if (dynamicTemplates != null) { // XXX perhaps, add strategy token to each url // to keep dynamic template structure similar to those bundled? urls.addAll(Arrays.asList(dynamicTemplates)); } if (strategy.getToken().length() > 0) { urls.add(new URL(baseURL, strategy.getToken() + '/')); } urls.add(baseURL); return new BundleResourceManager(urls.toArray(new URL[urls.size()])); } catch (MalformedURLException ex) { throw new Error(ex); } }
diff --git a/src/ImageMomentsGenerator.java b/src/ImageMomentsGenerator.java index e8a056e..9f94f75 100644 --- a/src/ImageMomentsGenerator.java +++ b/src/ImageMomentsGenerator.java @@ -1,143 +1,143 @@ import static java.lang.Math.min; import static java.lang.Math.*; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** * A {@link CS440Image} processor that considers the {@link CS440Image image} * as a binary image and generates its image moments and using which computes * the desired object's centroid, orientation and length and breadth of a rectangle * with the same moments. This class assumes that all images are of 640 x 480 resolution. * * @author Abhinay * */ public class ImageMomentsGenerator implements Sink<CS440Image>, Source<ImageMoments> { /** * The {@link Sink} subscribers to this * {@link ImageMomentsGenerator}. */ private List<Sink<ImageMoments>> subscribers = new ArrayList<Sink<ImageMoments>>(1); @Override public void receive(CS440Image frame) { momentsgenerator(frame); } /** * *Method that computes image moments and returns an *{@link ImageMoments} class with the results. * @return * @return */ public void momentsgenerator(CS440Image frame){ /** * * Variables to store the first and second order moments. */ double M00 = 0, M01 = 0, M10 = 0, M11 = 0, M20 = 0, M02 = 0; /** * * Variables to store the centroid location. */ double x = 0, y = 0; /** * *Intermediate variables required to calculate image properties. */ double a = 0, b = 0, c = 0; /** * *Variables to store the Length and Breadth of the rectangle with similar moments as those * of the {@link CS440Image image} being processed. */ double L1 = 0, L2 = 0; /** * *Variables to store the bounding box of the object in *the {@link CS440Image image} being processed. */ double x1 = 0, y1 = 0, x2 = 0, y2 = 0; /** * *Variable to store the orientation of the rectangle with similar moments as those * of the {@link CS440Image image} being processed. */ double theta; BufferedImage image = frame.getRawImage(); for(int w = 0; w < image.getWidth(); w++) { for (int h = 0; h < image.getHeight(); h++) { Color pixelint = new Color (image.getRGB(w, h)); int intensity = min(min(pixelint.getRed(), 1)+ min(pixelint.getBlue(), 1)+ min(pixelint.getGreen(), 1), 1); if(intensity != 0) { x1 = min(x1, w); x2 = max(x2, w); y1 = min(y1, h); y2 = max(y2, h); } M00 += intensity; M10 += w * intensity; M01 += h * intensity; M11 += w * h * intensity; M20 += w * w * intensity; M02 += h * h * intensity; } } - double m00 = M00 == 0 ? (double) M00 : 1.0D; + double m00 = M00 == 0 ? 1.0D : M00; - x = (int) Math.round(M10/m00); - y = (int) Math.round(M01/m00); + x = M10/m00; + y = M01/m00; a = (M20/m00) - (x * x); b = 2 * ((M11/m00) - x*y); c = (M02/m00) - (y * y); theta = atan(b/(a-c)) / 2; - L1 = Math.floor(Math.sqrt(6 * (a + c + Math.sqrt(b * b + Math.pow(a - c, 2))))); - L2 = Math.floor(Math.sqrt(6 * (a + c - Math.sqrt(b * b + Math.pow(a - c, 2))))); + L1 = Math.sqrt(6 * (a + c + Math.sqrt(b * b + Math.pow(a - c, 2)))); + L2 = Math.sqrt(6 * (a + c - Math.sqrt(b * b + Math.pow(a - c, 2)))); ImageMoments moments = new ImageMoments(); moments.theta = theta; moments.L1 = L1; moments.L2 = L2; moments.x = x; moments.y = y; moments.x1 = x1; moments.x2 = x2; moments.y1 = y1; moments.y2 = y2; moments.m00 = M00; moments.m01 = M01; moments.m02 = M02; moments.m10 = M10; moments.m11 = M11; moments.m20 = M20; // notify subscribers for (Sink<ImageMoments> subscriber : subscribers) { subscriber.receive(moments); } } @Override public void subscribe(Sink<ImageMoments> sink) { subscribers.add(sink); } }
false
true
public void momentsgenerator(CS440Image frame){ /** * * Variables to store the first and second order moments. */ double M00 = 0, M01 = 0, M10 = 0, M11 = 0, M20 = 0, M02 = 0; /** * * Variables to store the centroid location. */ double x = 0, y = 0; /** * *Intermediate variables required to calculate image properties. */ double a = 0, b = 0, c = 0; /** * *Variables to store the Length and Breadth of the rectangle with similar moments as those * of the {@link CS440Image image} being processed. */ double L1 = 0, L2 = 0; /** * *Variables to store the bounding box of the object in *the {@link CS440Image image} being processed. */ double x1 = 0, y1 = 0, x2 = 0, y2 = 0; /** * *Variable to store the orientation of the rectangle with similar moments as those * of the {@link CS440Image image} being processed. */ double theta; BufferedImage image = frame.getRawImage(); for(int w = 0; w < image.getWidth(); w++) { for (int h = 0; h < image.getHeight(); h++) { Color pixelint = new Color (image.getRGB(w, h)); int intensity = min(min(pixelint.getRed(), 1)+ min(pixelint.getBlue(), 1)+ min(pixelint.getGreen(), 1), 1); if(intensity != 0) { x1 = min(x1, w); x2 = max(x2, w); y1 = min(y1, h); y2 = max(y2, h); } M00 += intensity; M10 += w * intensity; M01 += h * intensity; M11 += w * h * intensity; M20 += w * w * intensity; M02 += h * h * intensity; } } double m00 = M00 == 0 ? (double) M00 : 1.0D; x = (int) Math.round(M10/m00); y = (int) Math.round(M01/m00); a = (M20/m00) - (x * x); b = 2 * ((M11/m00) - x*y); c = (M02/m00) - (y * y); theta = atan(b/(a-c)) / 2; L1 = Math.floor(Math.sqrt(6 * (a + c + Math.sqrt(b * b + Math.pow(a - c, 2))))); L2 = Math.floor(Math.sqrt(6 * (a + c - Math.sqrt(b * b + Math.pow(a - c, 2))))); ImageMoments moments = new ImageMoments(); moments.theta = theta; moments.L1 = L1; moments.L2 = L2; moments.x = x; moments.y = y; moments.x1 = x1; moments.x2 = x2; moments.y1 = y1; moments.y2 = y2; moments.m00 = M00; moments.m01 = M01; moments.m02 = M02; moments.m10 = M10; moments.m11 = M11; moments.m20 = M20; // notify subscribers for (Sink<ImageMoments> subscriber : subscribers) { subscriber.receive(moments); } }
public void momentsgenerator(CS440Image frame){ /** * * Variables to store the first and second order moments. */ double M00 = 0, M01 = 0, M10 = 0, M11 = 0, M20 = 0, M02 = 0; /** * * Variables to store the centroid location. */ double x = 0, y = 0; /** * *Intermediate variables required to calculate image properties. */ double a = 0, b = 0, c = 0; /** * *Variables to store the Length and Breadth of the rectangle with similar moments as those * of the {@link CS440Image image} being processed. */ double L1 = 0, L2 = 0; /** * *Variables to store the bounding box of the object in *the {@link CS440Image image} being processed. */ double x1 = 0, y1 = 0, x2 = 0, y2 = 0; /** * *Variable to store the orientation of the rectangle with similar moments as those * of the {@link CS440Image image} being processed. */ double theta; BufferedImage image = frame.getRawImage(); for(int w = 0; w < image.getWidth(); w++) { for (int h = 0; h < image.getHeight(); h++) { Color pixelint = new Color (image.getRGB(w, h)); int intensity = min(min(pixelint.getRed(), 1)+ min(pixelint.getBlue(), 1)+ min(pixelint.getGreen(), 1), 1); if(intensity != 0) { x1 = min(x1, w); x2 = max(x2, w); y1 = min(y1, h); y2 = max(y2, h); } M00 += intensity; M10 += w * intensity; M01 += h * intensity; M11 += w * h * intensity; M20 += w * w * intensity; M02 += h * h * intensity; } } double m00 = M00 == 0 ? 1.0D : M00; x = M10/m00; y = M01/m00; a = (M20/m00) - (x * x); b = 2 * ((M11/m00) - x*y); c = (M02/m00) - (y * y); theta = atan(b/(a-c)) / 2; L1 = Math.sqrt(6 * (a + c + Math.sqrt(b * b + Math.pow(a - c, 2)))); L2 = Math.sqrt(6 * (a + c - Math.sqrt(b * b + Math.pow(a - c, 2)))); ImageMoments moments = new ImageMoments(); moments.theta = theta; moments.L1 = L1; moments.L2 = L2; moments.x = x; moments.y = y; moments.x1 = x1; moments.x2 = x2; moments.y1 = y1; moments.y2 = y2; moments.m00 = M00; moments.m01 = M01; moments.m02 = M02; moments.m10 = M10; moments.m11 = M11; moments.m20 = M20; // notify subscribers for (Sink<ImageMoments> subscriber : subscribers) { subscriber.receive(moments); } }
diff --git a/src/tconstruct/common/TContent.java b/src/tconstruct/common/TContent.java index 1ae61aff5..09207985c 100644 --- a/src/tconstruct/common/TContent.java +++ b/src/tconstruct/common/TContent.java @@ -1,2274 +1,2275 @@ package tconstruct.common; import cpw.mods.fml.common.*; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.*; import java.lang.reflect.Field; import java.util.*; import net.minecraft.block.*; import net.minecraft.block.material.*; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.*; import net.minecraft.item.crafting.*; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.util.WeightedRandomChestContent; import net.minecraftforge.common.*; import net.minecraftforge.fluids.*; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.oredict.*; import tconstruct.TConstruct; import tconstruct.blocks.*; import tconstruct.blocks.logic.*; import tconstruct.blocks.slime.*; import tconstruct.blocks.traps.*; import tconstruct.client.StepSoundSlime; import tconstruct.entity.*; import tconstruct.entity.item.EntityLandmineFirework; import tconstruct.entity.projectile.*; import tconstruct.items.*; import tconstruct.items.armor.*; import tconstruct.items.blocks.*; import tconstruct.items.tools.*; import tconstruct.library.TConstructRegistry; import tconstruct.library.client.*; import tconstruct.library.client.FluidRenderProperties.Applications; import tconstruct.library.crafting.*; import tconstruct.library.tools.ToolCore; import tconstruct.library.util.IPattern; import tconstruct.modifiers.*; import tconstruct.util.*; import tconstruct.util.config.*; public class TContent implements IFuelHandler { //Patterns and other materials public static Item blankPattern; public static Item materials; public static Item toolRod; public static Item toolShard; public static Item woodPattern; public static Item metalPattern; public static Item armorPattern; public static Item manualBook; public static Item buckets; public static Item titleIcon; public static Item strangeFood; public static Item diamondApple; public static Item jerky; //public static Item stonePattern; //public static Item netherPattern; //Tools public static ToolCore pickaxe; public static ToolCore shovel; public static ToolCore hatchet; public static ToolCore broadsword; public static ToolCore longsword; public static ToolCore rapier; public static ToolCore dagger; public static ToolCore cutlass; public static ToolCore frypan; public static ToolCore battlesign; public static ToolCore chisel; public static ToolCore mattock; public static ToolCore scythe; public static ToolCore lumberaxe; public static ToolCore cleaver; public static ToolCore excavator; public static ToolCore hammer; public static ToolCore battleaxe; public static ToolCore shortbow; public static ToolCore arrow; public static Item potionLauncher; //Tool parts public static Item binding; public static Item toughBinding; public static Item toughRod; public static Item largePlate; public static Item pickaxeHead; public static Item shovelHead; public static Item hatchetHead; public static Item frypanHead; public static Item signHead; public static Item chiselHead; public static Item scytheBlade; public static Item broadAxeHead; public static Item excavatorHead; public static Item hammerHead; public static Item swordBlade; public static Item largeSwordBlade; public static Item knifeBlade; public static Item wideGuard; public static Item handGuard; public static Item crossbar; public static Item fullGuard; public static Item bowstring; public static Item arrowhead; public static Item fletching; //Crafting blocks public static Block toolStationWood; public static Block toolStationStone; public static Block toolForge; public static Block craftingStationWood; public static Block craftingSlabWood; public static Block heldItemBlock; public static Block craftedSoil; public static Block smeltery; public static Block lavaTank; public static Block searedBlock; public static Block castingChannel; public static Block metalBlock; public static Block tankAir; public static Block redstoneMachine; public static Block dryingRack; //Decoration public static Block stoneTorch; public static Block stoneLadder; public static Block multiBrick; public static Block multiBrickFancy; public static Block searedSlab; public static Block speedSlab; public static Block meatBlock; public static Block woolSlab1; public static Block woolSlab2; //Traps public static Block landmine; public static Block punji; public static Block barricadeOak; public static Block barricadeSpruce; public static Block barricadeBirch; public static Block barricadeJungle; //InfiBlocks public static Block speedBlock; public static Block clearGlass; //public static Block stainedGlass; public static Block stainedGlassClear; public static Block glassPane; //public static Block stainedGlassPane; public static Block stainedGlassClearPane; public static Block glassMagicSlab; public static Block stainedGlassMagicSlab; public static Block stainedGlassClearMagicSlab; //Crystalline public static Block essenceExtractor; public static Item essenceCrystal; //Liquids public static Material liquidMetal; public static Fluid moltenIronFluid; public static Fluid moltenGoldFluid; public static Fluid moltenCopperFluid; public static Fluid moltenTinFluid; public static Fluid moltenAluminumFluid; public static Fluid moltenCobaltFluid; public static Fluid moltenArditeFluid; public static Fluid moltenBronzeFluid; public static Fluid moltenAlubrassFluid; public static Fluid moltenManyullynFluid; public static Fluid moltenAlumiteFluid; public static Fluid moltenObsidianFluid; public static Fluid moltenSteelFluid; public static Fluid moltenGlassFluid; public static Fluid moltenStoneFluid; public static Fluid moltenEmeraldFluid; public static Fluid bloodFluid; public static Fluid moltenNickelFluid; public static Fluid moltenLeadFluid; public static Fluid moltenSilverFluid; public static Fluid moltenShinyFluid; public static Fluid moltenInvarFluid; public static Fluid moltenElectrumFluid; public static Fluid moltenEnderFluid; public static Fluid blueSlimeFluid; public static Block moltenIron; public static Block moltenGold; public static Block moltenCopper; public static Block moltenTin; public static Block moltenAluminum; public static Block moltenCobalt; public static Block moltenArdite; public static Block moltenBronze; public static Block moltenAlubrass; public static Block moltenManyullyn; public static Block moltenAlumite; public static Block moltenObsidian; public static Block moltenSteel; public static Block moltenGlass; public static Block moltenStone; public static Block moltenEmerald; public static Block blood; public static Block moltenNickel; public static Block moltenLead; public static Block moltenSilver; public static Block moltenShiny; public static Block moltenInvar; public static Block moltenElectrum; public static Block moltenEnder; //Slime public static StepSound slimeStep; public static Block slimePool; public static Block slimeGel; public static Block slimeGrass; public static Block slimeTallGrass; public static SlimeLeaves slimeLeaves; public static SlimeSapling slimeSapling; public static Block slimeChannel; public static Block slimePad; //Ores public static Block oreSlag; public static Block oreGravel; public static OreberryBush oreBerry; public static OreberryBush oreBerrySecond; public static Item oreBerries; //Tool modifiers public static ModElectric modE; public static ModLapis modL; //Wearables public static Item heavyHelmet; public static Item heavyChestplate; public static Item heavyPants; public static Item heavyBoots; public static Item glove; public static Item knapsack; public static Item heartCanister; public static Item goldHead; //Rail-related public static Block woodenRail; //Chest hooks public static ChestGenHooks tinkerHouseChest; public static ChestGenHooks tinkerHousePatterns; //Armor - basic public static Item helmetWood; public static Item chestplateWood; public static Item leggingsWood; public static Item bootsWood; public static EnumArmorMaterial materialWood; //Temporary items //public static Item armorTest = new ArmorStandard(2445, 4, EnumArmorPart.HELMET).setCreativeTab(CreativeTabs.tabAllSearch); public TContent() { registerItems(); registerBlocks(); registerMaterials(); addCraftingRecipes(); setupToolTabs(); addLoot(); } public void createEntities () { EntityRegistry.registerModEntity(FancyEntityItem.class, "Fancy Item", 0, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(DaggerEntity.class, "Dagger", 1, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(Crystal.class, "Crystal", 2, TConstruct.instance, 32, 3, true); EntityRegistry.registerModEntity(LaunchedPotion.class, "Launched Potion", 3, TConstruct.instance, 32, 3, true); EntityRegistry.registerModEntity(ArrowEntity.class, "Arrow", 4, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(EntityLandmineFirework.class, "LandmineFirework", 5, TConstruct.instance, 32, 5, true); //EntityRegistry.registerModEntity(CartEntity.class, "Small Wagon", 1, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(BlueSlime.class, "EdibleSlime", 12, TConstruct.instance, 64, 5, true); //EntityRegistry.registerModEntity(MetalSlime.class, "MetalSlime", 13, TConstruct.instance, 64, 5, true); /*BiomeGenBase[] plains = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.PLAINS); BiomeGenBase[] mountain = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.MOUNTAIN); BiomeGenBase[] hills = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.HILLS); BiomeGenBase[] swamp = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.SWAMP); BiomeGenBase[] desert = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.DESERT); BiomeGenBase[] frozen = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.FROZEN); BiomeGenBase[] jungle = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.JUNGLE); BiomeGenBase[] wasteland = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.WASTELAND); BiomeGenBase[] nether = BiomeDictionary.getBiomesForType(BiomeDictionary.Type.NETHER);*/ /*if (PHConstruct.blueSlime) { EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, plains); EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, mountain); EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, hills); EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, swamp); EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, desert); EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, frozen); EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, jungle); EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, wasteland); } try { Class.forName("extrabiomes.api.BiomeManager"); Collection<BiomeGenBase> ebxlCollection = BiomeManager.getBiomes(); BiomeGenBase[] ebxlBiomes = (BiomeGenBase[]) ebxlCollection.toArray(); EntityRegistry.addSpawn(BlueSlime.class, PHConstruct.blueSlimeWeight, 4, 4, EnumCreatureType.monster, ebxlBiomes); } catch (Exception e) { }*/ } public static Fluid[] fluids = new Fluid[25]; public static Block[] fluidBlocks = new Block[25]; void registerBlocks () { //Tool Station toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation"); GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock"); GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation"); GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter"); GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder"); GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper"); toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge"); GameRegistry.registerBlock(toolForge, ToolForgeItemBlock.class, "ToolForgeBlock"); GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge"); craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation"); GameRegistry.registerBlock(craftingStationWood, "CraftingStation"); GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation"); craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab"); GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab"); heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan"); GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock"); GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic"); craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil"); craftedSoil.stepSound = Block.soundGravelFootstep; GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil"); searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab"); searedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab"); speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab"); speedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab"); metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock"); metalBlock.stepSound = Block.soundMetalFootstep; GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock"); meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock"); GameRegistry.registerBlock(meatBlock, "MeatBlock"); OreDictionary.registerOre("hambone", new ItemStack(meatBlock)); LanguageRegistry.addName(meatBlock, "Hambone"); GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw)); woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth"); woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1"); woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth"); woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2"); //Smeltery smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery"); GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery"); GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain"); GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants"); lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setUnlocalizedName("LavaTank"); lavaTank.setStepSound(Block.soundGlassFootstep); GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank"); GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank"); searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock"); GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock"); GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable"); GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet"); GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin"); castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel"); GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel"); GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel"); tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air"); GameRegistry.registerBlock(tankAir, "TankAir"); GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air"); //Redstone machines redstoneMachine = new RedstoneMachine(PHConstruct.redstoneMachine).setUnlocalizedName("Redstone.Machine"); GameRegistry.registerBlock(redstoneMachine, RedstoneMachineItem.class, "Redstone.Machine"); GameRegistry.registerTileEntity(DrawbridgeLogic.class, "Drawbridge"); GameRegistry.registerTileEntity(FirestarterLogic.class, "Firestarter"); GameRegistry.registerTileEntity(AdvancedDrawbridgeLogic.class, "AdvDrawbridge"); //Traps landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone) .setUnlocalizedName("landmine"); GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine"); GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine"); punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji"); GameRegistry.registerBlock(punji, "trap.punji"); barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak"); GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak"); barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce"); GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce"); barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch"); GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch"); barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle"); GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle"); dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack"); GameRegistry.registerBlock(dryingRack, "Armor.DryingRack"); GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack"); //Liquids liquidMetal = new MaterialLiquid(MapColor.tntColor); moltenIronFluid = new Fluid("iron.molten"); if (!FluidRegistry.registerFluid(moltenIronFluid)) moltenIronFluid = FluidRegistry.getFluid("iron.molten"); moltenIron = new LiquidMetalFinite(PHConstruct.moltenIron, moltenIronFluid, "liquid_iron").setUnlocalizedName("metal.molten.iron"); GameRegistry.registerBlock(moltenIron, "metal.molten.iron"); fluids[0] = moltenIronFluid; fluidBlocks[0] = moltenIron; moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty))); moltenGoldFluid = new Fluid("gold.molten"); if (!FluidRegistry.registerFluid(moltenGoldFluid)) moltenGoldFluid = FluidRegistry.getFluid("gold.molten"); moltenGold = new LiquidMetalFinite(PHConstruct.moltenGold, moltenGoldFluid, "liquid_gold").setUnlocalizedName("metal.molten.gold"); GameRegistry.registerBlock(moltenGold, "metal.molten.gold"); fluids[1] = moltenGoldFluid; fluidBlocks[1] = moltenGold; moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty))); moltenCopperFluid = new Fluid("copper.molten"); if (!FluidRegistry.registerFluid(moltenCopperFluid)) moltenCopperFluid = FluidRegistry.getFluid("copper.molten"); moltenCopper = new LiquidMetalFinite(PHConstruct.moltenCopper, moltenCopperFluid, "liquid_copper").setUnlocalizedName("metal.molten.copper"); GameRegistry.registerBlock(moltenCopper, "metal.molten.copper"); fluids[2] = moltenCopperFluid; fluidBlocks[2] = moltenCopper; moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty))); moltenTinFluid = new Fluid("tin.molten"); if (!FluidRegistry.registerFluid(moltenTinFluid)) moltenTinFluid = FluidRegistry.getFluid("tin.molten"); moltenTin = new LiquidMetalFinite(PHConstruct.moltenTin, moltenTinFluid, "liquid_tin").setUnlocalizedName("metal.molten.tin"); GameRegistry.registerBlock(moltenTin, "metal.molten.tin"); fluids[3] = moltenTinFluid; fluidBlocks[3] = moltenTin; moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty))); moltenAluminumFluid = new Fluid("aluminum.molten"); if (!FluidRegistry.registerFluid(moltenAluminumFluid)) moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten"); moltenAluminum = new LiquidMetalFinite(PHConstruct.moltenAluminum, moltenAluminumFluid, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum"); GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum"); fluids[4] = moltenAluminumFluid; fluidBlocks[4] = moltenAluminum; moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty))); moltenCobaltFluid = new Fluid("cobalt.molten"); if (!FluidRegistry.registerFluid(moltenCobaltFluid)) moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten"); moltenCobalt = new LiquidMetalFinite(PHConstruct.moltenCobalt, moltenCobaltFluid, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt"); GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt"); fluids[5] = moltenCobaltFluid; fluidBlocks[5] = moltenCobalt; moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty))); moltenArditeFluid = new Fluid("ardite.molten"); if (!FluidRegistry.registerFluid(moltenArditeFluid)) moltenArditeFluid = FluidRegistry.getFluid("ardite.molten"); moltenArdite = new LiquidMetalFinite(PHConstruct.moltenArdite, moltenArditeFluid, "liquid_ardite").setUnlocalizedName("metal.molten.ardite"); GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite"); fluids[6] = moltenArditeFluid; fluidBlocks[6] = moltenArdite; moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty))); moltenBronzeFluid = new Fluid("bronze.molten"); if (!FluidRegistry.registerFluid(moltenBronzeFluid)) moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten"); moltenBronze = new LiquidMetalFinite(PHConstruct.moltenBronze, moltenBronzeFluid, "liquid_bronze").setUnlocalizedName("metal.molten.bronze"); GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze"); fluids[7] = moltenBronzeFluid; fluidBlocks[7] = moltenBronze; moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty))); moltenAlubrassFluid = new Fluid("aluminumbrass.molten"); if (!FluidRegistry.registerFluid(moltenAlubrassFluid)) moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten"); moltenAlubrass = new LiquidMetalFinite(PHConstruct.moltenAlubrass, moltenAlubrassFluid, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass"); GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass"); fluids[8] = moltenAlubrassFluid; fluidBlocks[8] = moltenAlubrass; moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty))); moltenManyullynFluid = new Fluid("manyullyn.molten"); if (!FluidRegistry.registerFluid(moltenManyullynFluid)) moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten"); moltenManyullyn = new LiquidMetalFinite(PHConstruct.moltenManyullyn, moltenManyullynFluid, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn"); GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn"); fluids[9] = moltenManyullynFluid; fluidBlocks[9] = moltenManyullyn; moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty))); moltenAlumiteFluid = new Fluid("alumite.molten"); if (!FluidRegistry.registerFluid(moltenAlumiteFluid)) moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten"); moltenAlumite = new LiquidMetalFinite(PHConstruct.moltenAlumite, moltenAlumiteFluid, "liquid_alumite").setUnlocalizedName("metal.molten.alumite"); GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite"); fluids[10] = moltenAlumiteFluid; fluidBlocks[10] = moltenAlumite; moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty))); moltenObsidianFluid = new Fluid("obsidian.molten"); if (!FluidRegistry.registerFluid(moltenObsidianFluid)) moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten"); moltenObsidian = new LiquidMetalFinite(PHConstruct.moltenObsidian, moltenObsidianFluid, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian"); GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian"); fluids[11] = moltenObsidianFluid; fluidBlocks[11] = moltenObsidian; moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty))); moltenSteelFluid = new Fluid("steel.molten"); if (!FluidRegistry.registerFluid(moltenSteelFluid)) moltenSteelFluid = FluidRegistry.getFluid("steel.molten"); moltenSteel = new LiquidMetalFinite(PHConstruct.moltenSteel, moltenSteelFluid, "liquid_steel").setUnlocalizedName("metal.molten.steel"); GameRegistry.registerBlock(moltenSteel, "metal.molten.steel"); fluids[12] = moltenSteelFluid; fluidBlocks[12] = moltenSteel; moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty))); moltenGlassFluid = new Fluid("glass.molten"); if (!FluidRegistry.registerFluid(moltenGlassFluid)) moltenGlassFluid = FluidRegistry.getFluid("glass.molten"); moltenGlass = new LiquidMetalFinite(PHConstruct.moltenGlass, moltenGlassFluid, "liquid_glass").setUnlocalizedName("metal.molten.glass"); GameRegistry.registerBlock(moltenGlass, "metal.molten.glass"); fluids[13] = moltenGlassFluid; fluidBlocks[13] = moltenGlass; moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty))); moltenStoneFluid = new Fluid("stone.seared"); if (!FluidRegistry.registerFluid(moltenStoneFluid)) moltenStoneFluid = FluidRegistry.getFluid("stone.seared"); moltenStone = new LiquidMetalFinite(PHConstruct.moltenStone, moltenStoneFluid, "liquid_stone").setUnlocalizedName("molten.stone"); GameRegistry.registerBlock(moltenStone, "molten.stone"); fluids[14] = moltenStoneFluid; fluidBlocks[14] = moltenStone; moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty))); moltenEmeraldFluid = new Fluid("emerald.liquid"); if (!FluidRegistry.registerFluid(moltenEmeraldFluid)) moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid"); moltenEmerald = new LiquidMetalFinite(PHConstruct.moltenEmerald, moltenEmeraldFluid, "liquid_villager").setUnlocalizedName("molten.emerald"); GameRegistry.registerBlock(moltenEmerald, "molten.emerald"); fluids[15] = moltenEmeraldFluid; fluidBlocks[15] = moltenEmerald; moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty))); bloodFluid = new Fluid("blood"); if (!FluidRegistry.registerFluid(bloodFluid)) bloodFluid = FluidRegistry.getFluid("blood"); blood = new LiquidMetalFinite(PHConstruct.blood, bloodFluid, "liquid_cow").setUnlocalizedName("liquid.blood"); GameRegistry.registerBlock(blood, "liquid.blood"); fluids[16] = bloodFluid; fluidBlocks[16] = blood; bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty))); moltenNickelFluid = new Fluid("nickel.molten"); if (!FluidRegistry.registerFluid(moltenNickelFluid)) moltenNickelFluid = FluidRegistry.getFluid("nickel.molten"); moltenNickel = new LiquidMetalFinite(PHConstruct.moltenNickel, moltenNickelFluid, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel"); GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel"); fluids[17] = moltenNickelFluid; fluidBlocks[17] = moltenNickel; moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty))); moltenLeadFluid = new Fluid("lead.molten"); if (!FluidRegistry.registerFluid(moltenLeadFluid)) moltenLeadFluid = FluidRegistry.getFluid("lead.molten"); moltenLead = new LiquidMetalFinite(PHConstruct.moltenLead, moltenLeadFluid, "liquid_lead").setUnlocalizedName("metal.molten.lead"); GameRegistry.registerBlock(moltenLead, "metal.molten.lead"); fluids[18] = moltenLeadFluid; fluidBlocks[18] = moltenLead; moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty))); moltenSilverFluid = new Fluid("silver.molten"); if (!FluidRegistry.registerFluid(moltenSilverFluid)) moltenSilverFluid = FluidRegistry.getFluid("silver.molten"); moltenSilver = new LiquidMetalFinite(PHConstruct.moltenSilver, moltenSilverFluid, "liquid_silver").setUnlocalizedName("metal.molten.silver"); GameRegistry.registerBlock(moltenSilver, "metal.molten.silver"); fluids[19] = moltenSilverFluid; fluidBlocks[19] = moltenSilver; moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty))); moltenShinyFluid = new Fluid("platinum.molten"); if (!FluidRegistry.registerFluid(moltenShinyFluid)) moltenShinyFluid = FluidRegistry.getFluid("platinum.molten"); moltenShiny = new LiquidMetalFinite(PHConstruct.moltenShiny, moltenShinyFluid, "liquid_shiny").setUnlocalizedName("metal.molten.shiny"); GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny"); fluids[20] = moltenLeadFluid; fluidBlocks[20] = moltenShiny; moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty))); moltenInvarFluid = new Fluid("invar.molten"); if (!FluidRegistry.registerFluid(moltenInvarFluid)) moltenInvarFluid = FluidRegistry.getFluid("invar.molten"); moltenInvar = new LiquidMetalFinite(PHConstruct.moltenInvar, moltenInvarFluid, "liquid_invar").setUnlocalizedName("metal.molten.invar"); GameRegistry.registerBlock(moltenInvar, "metal.molten.invar"); fluids[21] = moltenInvarFluid; fluidBlocks[21] = moltenInvar; moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty))); moltenElectrumFluid = new Fluid("electrum.molten"); if (!FluidRegistry.registerFluid(moltenElectrumFluid)) moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten"); moltenElectrum = new LiquidMetalFinite(PHConstruct.moltenElectrum, moltenElectrumFluid, "liquid_electrum").setUnlocalizedName("metal.molten.electrum"); GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum"); fluids[22] = moltenElectrumFluid; fluidBlocks[22] = moltenElectrum; moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty))); moltenEnderFluid = new Fluid("ender"); if (!FluidRegistry.registerFluid(moltenEnderFluid)) moltenEnderFluid = FluidRegistry.getFluid("ender"); moltenEnder = new LiquidMetalFinite(PHConstruct.moltenEnder, moltenEnderFluid, "liquid_ender").setUnlocalizedName("liquid.ender"); GameRegistry.registerBlock(moltenEnder, "liquid.ender"); fluids[23] = moltenEnderFluid; fluidBlocks[23] = moltenEnder; moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty))); //Slime slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f); blueSlimeFluid = new Fluid("slime.blue"); if (!FluidRegistry.registerFluid(blueSlimeFluid)) blueSlimeFluid = FluidRegistry.getFluid("slime.blue"); slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime"); GameRegistry.registerBlock(slimePool, "liquid.slime"); fluids[24] = blueSlimeFluid; fluidBlocks[24] = slimePool; blueSlimeFluid.setBlockID(slimePool); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty))); slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel"); GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel"); slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass"); GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass"); slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall"); GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall"); slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves"); GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves"); slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling"); GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling"); slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water).setStepSound(slimeStep).setUnlocalizedName("slime.channel"); GameRegistry.registerBlock(slimeChannel, "slime.channel"); TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1; slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setUnlocalizedName("slime.pad"); GameRegistry.registerBlock(slimePad, "slime.pad"); TConstructRegistry.drawbridgeState[slimePad.blockID] = 1; //Decoration stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch"); GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch"); stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder"); GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder"); multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick"); GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick"); multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy"); GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy"); //Ores String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" }; oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one"); GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one"); String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" }; oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two"); GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two"); String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" }; oreSlag = new MetalOre(PHConstruct.oreSlag, Material.iron, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore"); GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick"); MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1); oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore"); GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre"); MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2); MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4); speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock"); GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock"); //Glass clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock"); clearGlass.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock"); glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false); GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane"); stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear"); stainedGlassClear.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear"); stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane); GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained"); //Crystalline essenceExtractor = new EssenceExtractor(PHConstruct.essenceExtractor).setHardness(12f).setUnlocalizedName("extractor.essence"); GameRegistry.registerBlock(essenceExtractor, "extractor.essence"); GameRegistry.registerTileEntity(EssenceExtractorLogic.class, "extractor.essence"); //Rail woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood"); GameRegistry.registerBlock(woodenRail, "rail.wood"); } void registerItems () { titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon"); String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" }; blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern"); materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials"); toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod"); toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard"); woodPattern = new Pattern(PHConstruct.woodPattern, "WoodPattern", "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern"); metalPattern = new MetalPattern(PHConstruct.metalPattern, "MetalPattern", "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern"); armorPattern = new ArmorPattern(PHConstruct.armorPattern, "ArmorPattern", "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern"); TConstructRegistry.addItemToDirectory("blankPattern", blankPattern); TConstructRegistry.addItemToDirectory("woodPattern", woodPattern); TConstructRegistry.addItemToDirectory("metalPattern", metalPattern); TConstructRegistry.addItemToDirectory("armorPattern", armorPattern); String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead", "knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" }; for (int i = 1; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i)); } for (int i = 0; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i)); } String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" }; for (int i = 1; i < armorPartTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i)); } manualBook = new Manual(PHConstruct.manual); buckets = new FilledBucket(PHConstruct.buckets); pickaxe = new Pickaxe(PHConstruct.pickaxe); shovel = new Shovel(PHConstruct.shovel); hatchet = new Hatchet(PHConstruct.axe); broadsword = new Broadsword(PHConstruct.broadsword); longsword = new Longsword(PHConstruct.longsword); rapier = new Rapier(PHConstruct.rapier); dagger = new Dagger(PHConstruct.dagger); cutlass = new Cutlass(PHConstruct.cutlass); frypan = new FryingPan(PHConstruct.frypan); battlesign = new BattleSign(PHConstruct.battlesign); mattock = new Mattock(PHConstruct.mattock); chisel = new Chisel(PHConstruct.chisel); lumberaxe = new LumberAxe(PHConstruct.lumberaxe); cleaver = new Cleaver(PHConstruct.cleaver); scythe = new Scythe(PHConstruct.scythe); excavator = new Excavator(PHConstruct.excavator); hammer = new Hammer(PHConstruct.hammer); battleaxe = new Battleaxe(PHConstruct.battleaxe); shortbow = new Shortbow(PHConstruct.shortbow); arrow = new Arrow(PHConstruct.arrow); Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe }; String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe", "excavator", "hammer", "battleaxe" }; for (int i = 0; i < tools.length; i++) { TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]); } potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher"); pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead"); shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead"); hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead"); binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding"); toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding"); toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod"); largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate"); swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade"); wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard"); handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard"); crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar"); knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade"); fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard"); frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead"); signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead"); chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead"); scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade"); broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead"); excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead"); largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade"); hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead"); bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring"); arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead"); fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching"); Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard, frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead }; String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard", "crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring", "fletching", "arrowhead" }; for (int i = 0; i < toolParts.length; i++) { TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]); } diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond"); strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood"); oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry"); jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky"); //Wearables //heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet, 0).setUnlocalizedName("tconstruct.HeavyHelmet"); heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister"); //heavyBoots = new TArmorBase(PHConstruct.heavyBoots, 3).setUnlocalizedName("tconstruct.HeavyBoots"); //glove = new Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove"); knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage"); //Crystalline essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence"); goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead"); LiquidCasting basinCasting = TConstruct.getBasinCasting(); materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3); helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood"); chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood"); leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood"); bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood"); // essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence"); String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper", "ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper", "nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze", "nuggetAlumite", "nuggetSteel" }; for (int i = 0; i < materialStrings.length; i++) { TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i)); } String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" }; for (int i = 0; i < oreberries.length; i++) { TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i)); } TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0)); TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0)); TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0)); TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1)); TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2)); //Vanilla stack sizes Item.doorWood.setMaxStackSize(16); Item.doorIron.setMaxStackSize(16); Item.snowball.setMaxStackSize(64); Item.boat.setMaxStackSize(16); Item.minecartEmpty.setMaxStackSize(3); Item.minecartCrate.setMaxStackSize(3); Item.minecartPowered.setMaxStackSize(3); Item.itemsList[Block.cake.blockID].setMaxStackSize(16); //Block.torchWood.setTickRandomly(false); } void registerMaterials () { TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound"); TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", ""); TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", ""); TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged"); TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", ""); TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable"); TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", ""); TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", ""); TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", ""); TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", ""); TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", ""); TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", ""); TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime //Material ID, mass, fragility TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather for (int i = 0; i < 4; i++) TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime PatternBuilder pb = PatternBuilder.instance; if (PHConstruct.enableTWood) pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0); else pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0); if (PHConstruct.enableTStone) { pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1); pb.registerMaterial(Block.cobblestone, 2, "Stone"); } else pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0); pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2); if (PHConstruct.enableTFlint) pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); else pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); if (PHConstruct.enableTCactus) pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); else pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); if (PHConstruct.enableTBone) pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); else pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6); pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian"); if (PHConstruct.enableTNetherrack) pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); else pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); if (PHConstruct.enableTSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8); else pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8); if (PHConstruct.enableTPaper) pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9); else pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9); pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10); pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11); pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12); pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13); pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14); pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15); pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16); if (PHConstruct.enableTBlueSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17); else pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17); pb.addToolPattern((IPattern) woodPattern); } public static Item[] patternOutputs; public static FluidStack[] liquids; void addCraftingRecipes () { /* Tools */ patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod, toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead }; int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 17 }; if (PHConstruct.craftMetalTools) { for (int mat = 0; mat < 18; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat)); } } } else { for (int mat = 0; mat < nonMetals.length; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat])); } } } ToolBuilder tb = ToolBuilder.instance; tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding); tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard); tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod); tb.addNormalToolRecipe(shovel, shovelHead, toolRod); tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard); tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar); tb.addNormalToolRecipe(frypan, frypanHead, toolRod); tb.addNormalToolRecipe(battlesign, signHead, toolRod); tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead); tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar); tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard); tb.addNormalToolRecipe(chisel, chiselHead, toolRod); tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod); tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod); tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate); tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding); //tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod); BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow); tb.addCustomToolRecipe(recipe); tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching); ItemStack diamond = new ItemStack(Item.diamond); tb.registerToolMod(new ModRepair()); tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b")); tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72")); modE = new ModElectric(); tb.registerToolMod(modE); ItemStack redstoneItem = new ItemStack(Item.redstone); ItemStack redstoneBlock = new ItemStack(Block.blockRedstone); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem }, 2, 1)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneItem }, 2, 2)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock }, 2, 9)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneBlock }, 2, 10)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock, redstoneBlock }, 2, 18)); ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4); ItemStack lapisBlock = new ItemStack(Block.blockLapis); modL = new ModLapis(new ItemStack[] { lapisItem }, 10, 1); tb.registerToolMod(modL); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisItem }, 10, 2)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock }, 10, 9)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisBlock }, 10, 10)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock, lapisBlock }, 10, 18)); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair")); ItemStack blazePowder = new ItemStack(Item.blazePowder); tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder }, 7, 1)); tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder, blazePowder }, 7, 2)); tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt")); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal")); ItemStack quartzItem = new ItemStack(Item.netherQuartz); ItemStack quartzBlock = new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem }, 11, 1)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzItem }, 11, 2)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock }, 11, 4)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzBlock }, 11, 5)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock, quartzBlock }, 11, 8)); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free")); ItemStack silkyJewel = new ItemStack(materials, 1, 26); tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12)); ItemStack piston = new ItemStack(Block.pistonBase); tb.registerToolMod(new ModPiston(new ItemStack[] { piston }, 3, 1)); tb.registerToolMod(new ModPiston(new ItemStack[] { piston, piston }, 3, 2)); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading")); ItemStack holySoil = new ItemStack(craftedSoil, 1, 4); tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil }, 14, 1)); tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil, holySoil }, 14, 2)); ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye); tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball }, 15, 1)); tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball, spidereyeball }, 15, 2)); ItemStack obsidianPlate = new ItemStack(largePlate, 1, 6); tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1)); TConstructRegistry.registerActiveToolMod(new TActiveOmniMod()); /* Smeltery */ ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); ItemStack jewelCast = new ItemStack(metalPattern, 1, 23); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); //Blank tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80); tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80); //Ingots tableCasting.addCastingRecipe(new ItemStack(Item.ingotIron), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //Iron tableCasting.addCastingRecipe(new ItemStack(Item.ingotGold), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //gold tableCasting.addCastingRecipe(new ItemStack(materials, 1, 9), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //copper tableCasting.addCastingRecipe(new ItemStack(materials, 1, 10), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //tin tableCasting.addCastingRecipe(new ItemStack(materials, 1, 11), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //aluminum tableCasting.addCastingRecipe(new ItemStack(materials, 1, 3), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //cobalt tableCasting.addCastingRecipe(new ItemStack(materials, 1, 4), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //ardite tableCasting.addCastingRecipe(new ItemStack(materials, 1, 13), new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //bronze tableCasting.addCastingRecipe(new ItemStack(materials, 1, 14), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //albrass tableCasting.addCastingRecipe(new ItemStack(materials, 1, 5), new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //manyullyn tableCasting.addCastingRecipe(new ItemStack(materials, 1, 15), new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //alumite tableCasting.addCastingRecipe(new ItemStack(materials, 1, 18), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //obsidian tableCasting.addCastingRecipe(new ItemStack(materials, 1, 16), new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //steel tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //steel //Buckets ItemStack bucket = new ItemStack(Item.bucketEmpty); tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 0), new FluidStack(moltenIronFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //Iron tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 1), new FluidStack(moltenGoldFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //gold tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 2), new FluidStack(moltenCopperFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //copper tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 3), new FluidStack(moltenTinFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //tin tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 4), new FluidStack(moltenAluminumFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //aluminum tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 5), new FluidStack(moltenCobaltFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //cobalt tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 6), new FluidStack(moltenArditeFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //ardite tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 7), new FluidStack(moltenBronzeFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //bronze tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 8), new FluidStack(moltenAlubrassFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //alubrass tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 9), new FluidStack(moltenManyullynFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //manyullyn tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 10), new FluidStack(moltenAlumiteFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //alumite tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 11), new FluidStack(moltenObsidianFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10);// obsidian tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 12), new FluidStack(moltenSteelFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //steel tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 13), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //glass tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 14), new FluidStack(moltenStoneFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //seared stone tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 15), new FluidStack(moltenEmeraldFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //emerald tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80); liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1), new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1), new FluidStack(moltenSteelFluid, 1) }; int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16 }; for (int iter = 0; iter < patternOutputs.length; iter++) { if (patternOutputs[iter] != null) { ItemStack cast = new ItemStack(metalPattern, 1, iter + 1); tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++) { ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]); tableCasting.addCastingRecipe(metalCast, new FluidStack(liquids[iterTwo].getFluid(), ((IPattern) metalPattern).getPatternCost(metalCast) * TConstruct.ingotLiquidValue / 2), cast, 50); } } } ItemStack[] ingotShapes = { new ItemStack(Item.ingotIron), new ItemStack(Item.ingotGold), new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2) }; for (int i = 0; i < ingotShapes.length; i++) { TConstruct.tableCasting.addCastingRecipe(new ItemStack(TContent.metalPattern, 1, 0), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50); TConstruct.tableCasting.addCastingRecipe(new ItemStack(TContent.metalPattern, 1, 0), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50); } ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); LiquidCasting basinCasting = TConstructRegistry.getBasinCasting(); basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //Iron basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //gold basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //copper basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //tin basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //aluminum basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //cobalt basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //ardite basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //bronze basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //albrass basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //manyullyn basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //alumite basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2), null, true, 100);// obsidian basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //steel basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue / 9), new ItemStack(Block.gravel), true, 100); //brownstone basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, 25), new ItemStack(Block.obsidian), true, 100); //endstone basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, 1000), null, true, 100); //ender //Armor casts basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 0), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(helmetWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 0), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(helmetWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(chestplateWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(chestplateWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 2), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(leggingsWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(leggingsWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 3), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(bootsWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 3), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(bootsWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); //Ore Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); //Items Smeltery.addMelting(new ItemStack(Item.ingotIron, 4), Block.blockIron.blockID, 0, 500, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.ingotGold, 4), Block.blockGold.blockID, 0, 300, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.goldNugget, 4), Block.blockGold.blockID, 0, 150, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9)); Smeltery.addMelting(new ItemStack(materials, 1, 18), Block.obsidian.blockID, 0, 750, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue)); //Obsidian ingot Smeltery.addMelting(new ItemStack(blankPattern, 4, 1), metalBlock.blockID, 7, 150, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(blankPattern, 4, 2), metalBlock.blockID, 7, 150, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.enderPearl, 4), metalBlock.blockID, 10, 500, new FluidStack(moltenEnderFluid, 250)); Smeltery.addMelting(new ItemStack(metalBlock, 1, 10), metalBlock.blockID, 10, 500, new FluidStack(moltenEnderFluid, 1000)); //Blocks Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000)); Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250)); for (int i = 0; i < 16; i++) { Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250)); } //Alloys if (PHConstruct.harderBronze) Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 16), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze else Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 24), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, 16), new FluidStack(moltenAluminumFluid, 24), new FluidStack(moltenCopperFluid, 8)); //Aluminum Brass Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, 16), new FluidStack(moltenCobaltFluid, 32), new FluidStack(moltenArditeFluid, 32)); //Manyullyn Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, 48), new FluidStack(moltenAluminumFluid, 80), new FluidStack(moltenIronFluid, 32), new FluidStack(moltenObsidianFluid, 32)); //Alumite //Oreberries Smeltery.addMelting(new ItemStack(oreBerries, 4, 0), Block.blockIron.blockID, 0, 100, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue / 9)); //Iron Smeltery.addMelting(new ItemStack(oreBerries, 4, 1), Block.blockGold.blockID, 0, 100, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9)); //Gold Smeltery.addMelting(new ItemStack(oreBerries, 4, 2), metalBlock.blockID, 3, 100, new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue / 9)); //Copper Smeltery.addMelting(new ItemStack(oreBerries, 4, 3), metalBlock.blockID, 5, 100, new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue / 9)); //Tin Smeltery.addMelting(new ItemStack(oreBerries, 4, 4), metalBlock.blockID, 6, 100, new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue / 9)); //Aluminum //Vanilla Armor Smeltery.addMelting(new ItemStack(Item.helmetIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.plateIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 8)); Smeltery.addMelting(new ItemStack(Item.legsIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Item.bootsIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Item.helmetGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.plateGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8)); Smeltery.addMelting(new ItemStack(Item.legsGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Item.bootsGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Item.helmetChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.plateChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.legsChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.bootsChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue)); //Vanilla tools Smeltery.addMelting(new ItemStack(Item.hoeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.swordIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.shovelIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 1)); Smeltery.addMelting(new ItemStack(Item.pickaxeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.axeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.hoeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.swordGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.shovelGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 1)); Smeltery.addMelting(new ItemStack(Item.pickaxeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.axeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 3)); //Vanilla items Smeltery.addMelting(new ItemStack(Item.flintAndSteel, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.compass, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 4)); //Vanilla blocks Smeltery.addMelting(new ItemStack(Item.bucketEmpty), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.minecartEmpty), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.doorIron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6)); Smeltery.addMelting(new ItemStack(Block.fenceIron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6 / 16)); Smeltery.addMelting(new ItemStack(Block.pressurePlateIron), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Block.pressurePlateGold, 4), Block.blockGold.blockID, 0, 600, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Block.rail), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6 / 16)); Smeltery.addMelting(new ItemStack(Block.railPowered), Block.blockGold.blockID, 8, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.railDetector), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.railActivator), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.enchantmentTable), Block.obsidian.blockID, 0, 750, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Block.cauldron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 0), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 1), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 2), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); /* Detailing */ Detailing chiseling = TConstructRegistry.getChiselDetailing(); chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel); chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel); chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel); chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel); chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel); chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel); chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel); chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel); chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel); chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel); //chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel); //chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel); chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel); chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel); chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel); chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel); chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel); chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel); chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel); chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel); chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel); chiseling.addDetailing(materials, 18, multiBrick, 13, chisel); chiseling.addDetailing(multiBrick, 0, multiBrickFancy, 0, chisel); chiseling.addDetailing(multiBrick, 1, multiBrickFancy, 1, chisel); chiseling.addDetailing(multiBrick, 2, multiBrickFancy, 2, chisel); chiseling.addDetailing(multiBrick, 3, multiBrickFancy, 3, chisel); chiseling.addDetailing(multiBrick, 4, multiBrickFancy, 4, chisel); chiseling.addDetailing(multiBrick, 5, multiBrickFancy, 5, chisel); chiseling.addDetailing(multiBrick, 6, multiBrickFancy, 6, chisel); chiseling.addDetailing(multiBrick, 7, multiBrickFancy, 7, chisel); chiseling.addDetailing(multiBrick, 8, multiBrickFancy, 8, chisel); chiseling.addDetailing(multiBrick, 9, multiBrickFancy, 9, chisel); chiseling.addDetailing(multiBrick, 10, multiBrickFancy, 10, chisel); chiseling.addDetailing(multiBrick, 11, multiBrickFancy, 11, chisel); chiseling.addDetailing(multiBrick, 12, multiBrickFancy, 12, chisel); chiseling.addDetailing(multiBrick, 13, multiBrickFancy, 13, chisel); chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel); chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel); /*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/ chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel); chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel); chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel); chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel); chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel); chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 0), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockIron); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 1), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockGold); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 2), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockDiamond); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 3), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockEmerald); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 4), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockCobalt")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockArdite")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 6), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockManyullyn")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 7), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 8), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockBronze")); GameRegistry .addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 9), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockTin")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 10), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockNaturalAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 11), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockAluminumBrass")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 12), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockAlumite")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 13), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser))); //Drawbridge GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 1), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(largePlate, 1, 7), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Item.flintAndSteel))); //Igniter GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack( Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack( Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0))); /* Crafting */ GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.workbench); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood")); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest); if (PHConstruct.stencilTableCrafting) { GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3)); } GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood")); if (PHConstruct.stencilTableCrafting) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood")); GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern);//Vanilla books GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper); //Paper stack OreDictionary.registerOre("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1)); OreDictionary.registerOre("stoneMossy", new ItemStack(Block.cobblestoneMossy)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), "ppp", "ppp", "ppp", 'p', "stoneMossy")); //Moss ball GameRegistry.addRecipe(new ItemStack(materials, 1, 6), "ppp", "ppp", "ppp", 'p', new ItemStack(Block.stoneBrick, 1, 1)); //Moss ball GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod); //Auto-smelt GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod); //Auto-smelt GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt); //Slimy sand GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt); //Slimy sand GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel); //Grout GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 8, 1), Block.blockClay, Block.sand, Block.gravel, Block.sand, Block.gravel, Block.sand, Block.gravel, Block.sand, Block.gravel); //Grout GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15)); //Graveyard Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime //GameRegistry.addRecipe(new ItemStack(oreSlag, 1, 0), "pp", "pp", 'p', new ItemStack(materials, 1, 2)); //Seared brick block GameRegistry.addRecipe(new ItemStack(materials, 1, 25), "sss", "sns", "sss", 'n', new ItemStack(materials, 1, 24), 's', new ItemStack(Item.silk)); //Silky Cloth GameRegistry.addRecipe(new ItemStack(materials, 1, 25), "sss", "sns", "sss", 'n', new ItemStack(Item.goldNugget), 's', new ItemStack(Item.silk)); GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald)); //Silky Jewel GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, new Object[] { "www", "w w", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, new Object[] { "w w", "www", "www", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, new Object[] { "www", "w w", "w w", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, new Object[] { "w w", "w w", 'w', "logWood" })); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 12), 0.5f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f); //FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 12), 0.2f); FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f); //Metal conversion GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 12), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel GameRegistry.addRecipe(new ItemStack(Item.ingotIron), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 19)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 1, 9), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 20)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 1, 10), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 21)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 1, 12), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 22)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 1, 14), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 24)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 1, 18), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 27)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 1, 3), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 28)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 1, 4), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 29)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 1, 5), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 30)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 1, 13), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 31)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 1, 15), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 32)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 1, 16), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 33)); //Steel GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel //Dyes String[] pattern = { "###", "#m#", "###" }; String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite" }; for (int i = 0; i < 16; i++) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), pattern, 'm', dyeTypes[15 - i], '#', clearGlass)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), dyeTypes[15 - i], clearGlass)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), dyeTypes[15 - i], new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), pattern, 'm', dyeTypes[15 - i], '#', glassPane)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), dyeTypes[15 - i], glassPane)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), dyeTypes[15 - i], new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); } //Glass GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass }); GameRegistry.addRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', Block.glass, 'Q', Item.netherQuartz, 'W', Block.woodSingleSlab }); GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian }); //Smeltery ItemStack searedBrick = new ItemStack(materials, 1, 2); GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 0), "bbb", "bgb", "bbb", 'b', searedBrick, 'g', Block.glass); //Tank GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', Block.glass); //Glass GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', Block.glass); //Window GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 0), "bbb", "bgb", "bbb", 'b', searedBrick, 'g', clearGlass); //Tank GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', clearGlass); //Glass GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', clearGlass); //Window GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 'w', new ItemStack(stoneTorch)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod")); + GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(woodenRail, 4, 0), "b b", "bxb", "b b", 'b', "plankWood", 'x', "stickWood")); GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone)); GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone)); ItemStack aluBrass = new ItemStack(materials, 1, 14); GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass); ItemStack necroticBone = new ItemStack(materials, 1, 8); //Accessories GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum")); GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed)); GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), necroticBone, new ItemStack(heartCanister, 1, 0), new ItemStack(heartCanister, 1, 1)); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', new ItemStack(Item.ingotGold)); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', new ItemStack(materials, 1, 14)); //Armor GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood")); //Landmine GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); //Ultra hardcore recipes String[] surround = { "###", "#m#", "###" }; if (PHConstruct.goldAppleRecipe) { RecipeRemover.removeShapedRecipe(new ItemStack(Item.appleGold)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.goldenCarrot)); RecipeRemover.removeShapelessRecipe(new ItemStack(Item.speckledMelon)); GameRegistry.addRecipe(new ItemStack(Item.appleGold), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(Item.goldenCarrot), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.carrot)); GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3)); GameRegistry.addShapelessRecipe(new ItemStack(Item.speckledMelon), new ItemStack(Block.blockGold), new ItemStack(Item.melon)); tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8), new ItemStack(Item.appleRed), true, 50); } else { GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(Item.goldNugget), 'm', new ItemStack(Item.skull, 1, 3)); GameRegistry.addRecipe(new ItemStack(Item.appleGold), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(Item.goldenCarrot), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9 * 8), new ItemStack(Item.appleRed), true, 50); } tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8 * 9), new ItemStack(Item.appleRed), true, 50); //Drying rack DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0)); DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1)); DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2)); //DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3)); DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4)); DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5)); //DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather); //Slabs for (int i = 0; i < 7; i++) { GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i)); } GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11)); //Traps GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed)); GameRegistry.addRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 0)); GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood")); GameRegistry.addRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood")); //Slab crafters GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); GameRegistry.addRecipe(new ItemStack(essenceExtractor, 1, 0), " b ", "eme", "mmm", 'b', Item.book, 'e', Item.emerald, 'm', Block.whiteStone); //Slime GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood); GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0)); GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall); GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, new ItemStack(slimeGel, 1, Short.MAX_VALUE), "slimeBall")); //Slab crafters GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); } void setupToolTabs () { TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255)); TConstructRegistry.blockTab.init(new ItemStack(toolStationWood)); ItemStack tool = new ItemStack(longsword, 1, 0); NBTTagCompound compound = new NBTTagCompound(); compound.setCompoundTag("InfiTool", new NBTTagCompound()); compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2); compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0); compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10); tool.setTagCompound(compound); //TConstruct. TConstructRegistry.toolTab.init(tool); } public void addLoot () { //Item, min, max, weight ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27); tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1)); int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 }; Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead }; for (int partIter = 0; partIter < partTypes.length; partIter++) { for (int typeIter = 0; typeIter < validTypes.length; typeIter++) { tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15)); } } tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30); for (int i = 0; i < 13; i++) { tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20)); } tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40)); } public static String[] liquidNames; public void oreRegistry () { OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1)); OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2)); OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3)); OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4)); OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0)); OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1)); OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5)); OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2)); OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3)); OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3)); OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4)); OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5)); OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9)); OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10)); OreDictionary.registerOre("ingotNaturalAluminum", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("naturalAluminum", new ItemStack(materials, 1, 12)); OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13)); OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15)); OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16)); OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0)); OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1)); OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2)); OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3)); OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4)); OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5)); OreDictionary.registerOre("blockNaturalAluminum", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8)); OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9)); OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19)); OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20)); OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21)); OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27)); OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28)); OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29)); OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30)); OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31)); OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32)); OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33)); String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel", "blueslime" }; for (int i = 0; i < matNames.length; i++) OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i)); OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31)); String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow", "glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" }; for (int i = 0; i < 16; i++) { OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i)); } BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg()); BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow()); //Vanilla stuff OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0)); OreDictionary.registerOre("glass", new ItemStack(clearGlass)); RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder)); } public static boolean thaumcraftAvailable; public void intermodCommunication () { if (Loader.isModLoaded("Thaumcraft")) { FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13)); } if (Loader.isModLoaded("Mystcraft")) { MystImcHandler.blacklistFluids(); } if (Loader.isModLoaded("BuildCraft|Transport")) { BCImcHandler.registerFacades(); } /* FORESTRY * Edit these strings to change what items are added to the backpacks * Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on * Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder * May add more backpack items later - Spyboticsguy */ if (Loader.isModLoaded("Forestry")) { String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*"; FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems); } if (!Loader.isModLoaded("AppliedEnergistics")) { AEImcHandler.registerForSpatialIO(); } } private static boolean initRecipes; public static void modRecipes () { if (!initRecipes) { initRecipes = true; if (PHConstruct.removeVanillaToolRecipes) { RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold)); } } } public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray) { String var3 = ""; int var4 = 0; int var5 = 0; int var6 = 0; if (objArray[var4] instanceof String[]) { String[] var7 = (String[]) ((String[]) objArray[var4++]); for (int var8 = 0; var8 < var7.length; ++var8) { String var9 = var7[var8]; ++var6; var5 = var9.length(); var3 = var3 + var9; } } else { while (objArray[var4] instanceof String) { String var11 = (String) objArray[var4++]; ++var6; var5 = var11.length(); var3 = var3 + var11; } } HashMap var12; for (var12 = new HashMap(); var4 < objArray.length; var4 += 2) { Character var13 = (Character) objArray[var4]; ItemStack var14 = null; if (objArray[var4 + 1] instanceof Item) { var14 = new ItemStack((Item) objArray[var4 + 1]); } else if (objArray[var4 + 1] instanceof Block) { var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE); } else if (objArray[var4 + 1] instanceof ItemStack) { var14 = (ItemStack) objArray[var4 + 1]; } var12.put(var13, var14); } ItemStack[] var15 = new ItemStack[var5 * var6]; for (int var16 = 0; var16 < var5 * var6; ++var16) { char var10 = var3.charAt(var16); if (var12.containsKey(Character.valueOf(var10))) { var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy(); } else { var15[var16] = null; } } ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack); recipeList.add(0, var17); } public void modIntegration () { ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), ""); /* IC2 */ //ItemStack reBattery = ic2.api.item.Items.getItem("reBattery"); Object reBattery = getStaticItem("reBattery", "ic2.core.Ic2Items"); if (reBattery != null) { modE.batteries.add((ItemStack) reBattery); } //ItemStack chargedReBattery = ic2.api.item.Items.getItem("chargedReBattery"); Object chargedReBattery = getStaticItem("chargedReBattery", "ic2.core.Ic2Items"); if (chargedReBattery != null) { modE.batteries.add((ItemStack) chargedReBattery); } //ItemStack electronicCircuit = ic2.api.item.Items.getItem("electronicCircuit"); Object electronicCircuit = getStaticItem("electronicCircuit", "ic2.core.Ic2Items"); if (electronicCircuit != null) modE.circuits.add((ItemStack) electronicCircuit); if (chargedReBattery != null && electronicCircuit != null) TConstructClientRegistry.registerManualModifier("electricmod", ironpick.copy(), (ItemStack) chargedReBattery, (ItemStack) electronicCircuit); /* Thaumcraft */ Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems"); if (obj != null) { TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools."); thaumcraftAvailable = true; TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true); TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic"); PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31); for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31)); } TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f); TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f); TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F); } else { TConstruct.logger.warning("Thaumcraft not detected."); } if (Loader.isModLoaded("Natura")) { try { Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent"); TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f); } catch (Exception e) { } //No need to handle } ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting(); /* Thermal Expansion */ ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotLead"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotSilver"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotPlatinum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotInvar"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar } ores = OreDictionary.getOres("ingotElectrum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum } ores = OreDictionary.getOres("blockNickel"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockLead"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockSilver"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockPlatinum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockInvar"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockElectrum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue * 9), null, 100); } } public static Object getStaticItem (String name, String classPackage) { try { Class clazz = Class.forName(classPackage); Field field = clazz.getDeclaredField(name); Object ret = field.get(null); if (ret != null && (ret instanceof ItemStack || ret instanceof Item)) return ret; return null; } catch (Exception e) { TConstruct.logger.warning("Could not find " + name); return null; } } @Override public int getBurnTime (ItemStack fuel) { if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7) return 26400; return 0; } }
true
true
void registerBlocks () { //Tool Station toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation"); GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock"); GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation"); GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter"); GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder"); GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper"); toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge"); GameRegistry.registerBlock(toolForge, ToolForgeItemBlock.class, "ToolForgeBlock"); GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge"); craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation"); GameRegistry.registerBlock(craftingStationWood, "CraftingStation"); GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation"); craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab"); GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab"); heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan"); GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock"); GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic"); craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil"); craftedSoil.stepSound = Block.soundGravelFootstep; GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil"); searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab"); searedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab"); speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab"); speedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab"); metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock"); metalBlock.stepSound = Block.soundMetalFootstep; GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock"); meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock"); GameRegistry.registerBlock(meatBlock, "MeatBlock"); OreDictionary.registerOre("hambone", new ItemStack(meatBlock)); LanguageRegistry.addName(meatBlock, "Hambone"); GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw)); woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth"); woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1"); woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth"); woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2"); //Smeltery smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery"); GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery"); GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain"); GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants"); lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setUnlocalizedName("LavaTank"); lavaTank.setStepSound(Block.soundGlassFootstep); GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank"); GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank"); searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock"); GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock"); GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable"); GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet"); GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin"); castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel"); GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel"); GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel"); tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air"); GameRegistry.registerBlock(tankAir, "TankAir"); GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air"); //Redstone machines redstoneMachine = new RedstoneMachine(PHConstruct.redstoneMachine).setUnlocalizedName("Redstone.Machine"); GameRegistry.registerBlock(redstoneMachine, RedstoneMachineItem.class, "Redstone.Machine"); GameRegistry.registerTileEntity(DrawbridgeLogic.class, "Drawbridge"); GameRegistry.registerTileEntity(FirestarterLogic.class, "Firestarter"); GameRegistry.registerTileEntity(AdvancedDrawbridgeLogic.class, "AdvDrawbridge"); //Traps landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone) .setUnlocalizedName("landmine"); GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine"); GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine"); punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji"); GameRegistry.registerBlock(punji, "trap.punji"); barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak"); GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak"); barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce"); GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce"); barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch"); GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch"); barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle"); GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle"); dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack"); GameRegistry.registerBlock(dryingRack, "Armor.DryingRack"); GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack"); //Liquids liquidMetal = new MaterialLiquid(MapColor.tntColor); moltenIronFluid = new Fluid("iron.molten"); if (!FluidRegistry.registerFluid(moltenIronFluid)) moltenIronFluid = FluidRegistry.getFluid("iron.molten"); moltenIron = new LiquidMetalFinite(PHConstruct.moltenIron, moltenIronFluid, "liquid_iron").setUnlocalizedName("metal.molten.iron"); GameRegistry.registerBlock(moltenIron, "metal.molten.iron"); fluids[0] = moltenIronFluid; fluidBlocks[0] = moltenIron; moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty))); moltenGoldFluid = new Fluid("gold.molten"); if (!FluidRegistry.registerFluid(moltenGoldFluid)) moltenGoldFluid = FluidRegistry.getFluid("gold.molten"); moltenGold = new LiquidMetalFinite(PHConstruct.moltenGold, moltenGoldFluid, "liquid_gold").setUnlocalizedName("metal.molten.gold"); GameRegistry.registerBlock(moltenGold, "metal.molten.gold"); fluids[1] = moltenGoldFluid; fluidBlocks[1] = moltenGold; moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty))); moltenCopperFluid = new Fluid("copper.molten"); if (!FluidRegistry.registerFluid(moltenCopperFluid)) moltenCopperFluid = FluidRegistry.getFluid("copper.molten"); moltenCopper = new LiquidMetalFinite(PHConstruct.moltenCopper, moltenCopperFluid, "liquid_copper").setUnlocalizedName("metal.molten.copper"); GameRegistry.registerBlock(moltenCopper, "metal.molten.copper"); fluids[2] = moltenCopperFluid; fluidBlocks[2] = moltenCopper; moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty))); moltenTinFluid = new Fluid("tin.molten"); if (!FluidRegistry.registerFluid(moltenTinFluid)) moltenTinFluid = FluidRegistry.getFluid("tin.molten"); moltenTin = new LiquidMetalFinite(PHConstruct.moltenTin, moltenTinFluid, "liquid_tin").setUnlocalizedName("metal.molten.tin"); GameRegistry.registerBlock(moltenTin, "metal.molten.tin"); fluids[3] = moltenTinFluid; fluidBlocks[3] = moltenTin; moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty))); moltenAluminumFluid = new Fluid("aluminum.molten"); if (!FluidRegistry.registerFluid(moltenAluminumFluid)) moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten"); moltenAluminum = new LiquidMetalFinite(PHConstruct.moltenAluminum, moltenAluminumFluid, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum"); GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum"); fluids[4] = moltenAluminumFluid; fluidBlocks[4] = moltenAluminum; moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty))); moltenCobaltFluid = new Fluid("cobalt.molten"); if (!FluidRegistry.registerFluid(moltenCobaltFluid)) moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten"); moltenCobalt = new LiquidMetalFinite(PHConstruct.moltenCobalt, moltenCobaltFluid, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt"); GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt"); fluids[5] = moltenCobaltFluid; fluidBlocks[5] = moltenCobalt; moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty))); moltenArditeFluid = new Fluid("ardite.molten"); if (!FluidRegistry.registerFluid(moltenArditeFluid)) moltenArditeFluid = FluidRegistry.getFluid("ardite.molten"); moltenArdite = new LiquidMetalFinite(PHConstruct.moltenArdite, moltenArditeFluid, "liquid_ardite").setUnlocalizedName("metal.molten.ardite"); GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite"); fluids[6] = moltenArditeFluid; fluidBlocks[6] = moltenArdite; moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty))); moltenBronzeFluid = new Fluid("bronze.molten"); if (!FluidRegistry.registerFluid(moltenBronzeFluid)) moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten"); moltenBronze = new LiquidMetalFinite(PHConstruct.moltenBronze, moltenBronzeFluid, "liquid_bronze").setUnlocalizedName("metal.molten.bronze"); GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze"); fluids[7] = moltenBronzeFluid; fluidBlocks[7] = moltenBronze; moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty))); moltenAlubrassFluid = new Fluid("aluminumbrass.molten"); if (!FluidRegistry.registerFluid(moltenAlubrassFluid)) moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten"); moltenAlubrass = new LiquidMetalFinite(PHConstruct.moltenAlubrass, moltenAlubrassFluid, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass"); GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass"); fluids[8] = moltenAlubrassFluid; fluidBlocks[8] = moltenAlubrass; moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty))); moltenManyullynFluid = new Fluid("manyullyn.molten"); if (!FluidRegistry.registerFluid(moltenManyullynFluid)) moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten"); moltenManyullyn = new LiquidMetalFinite(PHConstruct.moltenManyullyn, moltenManyullynFluid, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn"); GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn"); fluids[9] = moltenManyullynFluid; fluidBlocks[9] = moltenManyullyn; moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty))); moltenAlumiteFluid = new Fluid("alumite.molten"); if (!FluidRegistry.registerFluid(moltenAlumiteFluid)) moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten"); moltenAlumite = new LiquidMetalFinite(PHConstruct.moltenAlumite, moltenAlumiteFluid, "liquid_alumite").setUnlocalizedName("metal.molten.alumite"); GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite"); fluids[10] = moltenAlumiteFluid; fluidBlocks[10] = moltenAlumite; moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty))); moltenObsidianFluid = new Fluid("obsidian.molten"); if (!FluidRegistry.registerFluid(moltenObsidianFluid)) moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten"); moltenObsidian = new LiquidMetalFinite(PHConstruct.moltenObsidian, moltenObsidianFluid, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian"); GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian"); fluids[11] = moltenObsidianFluid; fluidBlocks[11] = moltenObsidian; moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty))); moltenSteelFluid = new Fluid("steel.molten"); if (!FluidRegistry.registerFluid(moltenSteelFluid)) moltenSteelFluid = FluidRegistry.getFluid("steel.molten"); moltenSteel = new LiquidMetalFinite(PHConstruct.moltenSteel, moltenSteelFluid, "liquid_steel").setUnlocalizedName("metal.molten.steel"); GameRegistry.registerBlock(moltenSteel, "metal.molten.steel"); fluids[12] = moltenSteelFluid; fluidBlocks[12] = moltenSteel; moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty))); moltenGlassFluid = new Fluid("glass.molten"); if (!FluidRegistry.registerFluid(moltenGlassFluid)) moltenGlassFluid = FluidRegistry.getFluid("glass.molten"); moltenGlass = new LiquidMetalFinite(PHConstruct.moltenGlass, moltenGlassFluid, "liquid_glass").setUnlocalizedName("metal.molten.glass"); GameRegistry.registerBlock(moltenGlass, "metal.molten.glass"); fluids[13] = moltenGlassFluid; fluidBlocks[13] = moltenGlass; moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty))); moltenStoneFluid = new Fluid("stone.seared"); if (!FluidRegistry.registerFluid(moltenStoneFluid)) moltenStoneFluid = FluidRegistry.getFluid("stone.seared"); moltenStone = new LiquidMetalFinite(PHConstruct.moltenStone, moltenStoneFluid, "liquid_stone").setUnlocalizedName("molten.stone"); GameRegistry.registerBlock(moltenStone, "molten.stone"); fluids[14] = moltenStoneFluid; fluidBlocks[14] = moltenStone; moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty))); moltenEmeraldFluid = new Fluid("emerald.liquid"); if (!FluidRegistry.registerFluid(moltenEmeraldFluid)) moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid"); moltenEmerald = new LiquidMetalFinite(PHConstruct.moltenEmerald, moltenEmeraldFluid, "liquid_villager").setUnlocalizedName("molten.emerald"); GameRegistry.registerBlock(moltenEmerald, "molten.emerald"); fluids[15] = moltenEmeraldFluid; fluidBlocks[15] = moltenEmerald; moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty))); bloodFluid = new Fluid("blood"); if (!FluidRegistry.registerFluid(bloodFluid)) bloodFluid = FluidRegistry.getFluid("blood"); blood = new LiquidMetalFinite(PHConstruct.blood, bloodFluid, "liquid_cow").setUnlocalizedName("liquid.blood"); GameRegistry.registerBlock(blood, "liquid.blood"); fluids[16] = bloodFluid; fluidBlocks[16] = blood; bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty))); moltenNickelFluid = new Fluid("nickel.molten"); if (!FluidRegistry.registerFluid(moltenNickelFluid)) moltenNickelFluid = FluidRegistry.getFluid("nickel.molten"); moltenNickel = new LiquidMetalFinite(PHConstruct.moltenNickel, moltenNickelFluid, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel"); GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel"); fluids[17] = moltenNickelFluid; fluidBlocks[17] = moltenNickel; moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty))); moltenLeadFluid = new Fluid("lead.molten"); if (!FluidRegistry.registerFluid(moltenLeadFluid)) moltenLeadFluid = FluidRegistry.getFluid("lead.molten"); moltenLead = new LiquidMetalFinite(PHConstruct.moltenLead, moltenLeadFluid, "liquid_lead").setUnlocalizedName("metal.molten.lead"); GameRegistry.registerBlock(moltenLead, "metal.molten.lead"); fluids[18] = moltenLeadFluid; fluidBlocks[18] = moltenLead; moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty))); moltenSilverFluid = new Fluid("silver.molten"); if (!FluidRegistry.registerFluid(moltenSilverFluid)) moltenSilverFluid = FluidRegistry.getFluid("silver.molten"); moltenSilver = new LiquidMetalFinite(PHConstruct.moltenSilver, moltenSilverFluid, "liquid_silver").setUnlocalizedName("metal.molten.silver"); GameRegistry.registerBlock(moltenSilver, "metal.molten.silver"); fluids[19] = moltenSilverFluid; fluidBlocks[19] = moltenSilver; moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty))); moltenShinyFluid = new Fluid("platinum.molten"); if (!FluidRegistry.registerFluid(moltenShinyFluid)) moltenShinyFluid = FluidRegistry.getFluid("platinum.molten"); moltenShiny = new LiquidMetalFinite(PHConstruct.moltenShiny, moltenShinyFluid, "liquid_shiny").setUnlocalizedName("metal.molten.shiny"); GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny"); fluids[20] = moltenLeadFluid; fluidBlocks[20] = moltenShiny; moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty))); moltenInvarFluid = new Fluid("invar.molten"); if (!FluidRegistry.registerFluid(moltenInvarFluid)) moltenInvarFluid = FluidRegistry.getFluid("invar.molten"); moltenInvar = new LiquidMetalFinite(PHConstruct.moltenInvar, moltenInvarFluid, "liquid_invar").setUnlocalizedName("metal.molten.invar"); GameRegistry.registerBlock(moltenInvar, "metal.molten.invar"); fluids[21] = moltenInvarFluid; fluidBlocks[21] = moltenInvar; moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty))); moltenElectrumFluid = new Fluid("electrum.molten"); if (!FluidRegistry.registerFluid(moltenElectrumFluid)) moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten"); moltenElectrum = new LiquidMetalFinite(PHConstruct.moltenElectrum, moltenElectrumFluid, "liquid_electrum").setUnlocalizedName("metal.molten.electrum"); GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum"); fluids[22] = moltenElectrumFluid; fluidBlocks[22] = moltenElectrum; moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty))); moltenEnderFluid = new Fluid("ender"); if (!FluidRegistry.registerFluid(moltenEnderFluid)) moltenEnderFluid = FluidRegistry.getFluid("ender"); moltenEnder = new LiquidMetalFinite(PHConstruct.moltenEnder, moltenEnderFluid, "liquid_ender").setUnlocalizedName("liquid.ender"); GameRegistry.registerBlock(moltenEnder, "liquid.ender"); fluids[23] = moltenEnderFluid; fluidBlocks[23] = moltenEnder; moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty))); //Slime slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f); blueSlimeFluid = new Fluid("slime.blue"); if (!FluidRegistry.registerFluid(blueSlimeFluid)) blueSlimeFluid = FluidRegistry.getFluid("slime.blue"); slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime"); GameRegistry.registerBlock(slimePool, "liquid.slime"); fluids[24] = blueSlimeFluid; fluidBlocks[24] = slimePool; blueSlimeFluid.setBlockID(slimePool); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty))); slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel"); GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel"); slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass"); GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass"); slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall"); GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall"); slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves"); GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves"); slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling"); GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling"); slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water).setStepSound(slimeStep).setUnlocalizedName("slime.channel"); GameRegistry.registerBlock(slimeChannel, "slime.channel"); TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1; slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setUnlocalizedName("slime.pad"); GameRegistry.registerBlock(slimePad, "slime.pad"); TConstructRegistry.drawbridgeState[slimePad.blockID] = 1; //Decoration stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch"); GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch"); stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder"); GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder"); multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick"); GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick"); multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy"); GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy"); //Ores String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" }; oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one"); GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one"); String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" }; oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two"); GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two"); String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" }; oreSlag = new MetalOre(PHConstruct.oreSlag, Material.iron, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore"); GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick"); MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1); oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore"); GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre"); MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2); MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4); speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock"); GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock"); //Glass clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock"); clearGlass.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock"); glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false); GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane"); stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear"); stainedGlassClear.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear"); stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane); GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained"); //Crystalline essenceExtractor = new EssenceExtractor(PHConstruct.essenceExtractor).setHardness(12f).setUnlocalizedName("extractor.essence"); GameRegistry.registerBlock(essenceExtractor, "extractor.essence"); GameRegistry.registerTileEntity(EssenceExtractorLogic.class, "extractor.essence"); //Rail woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood"); GameRegistry.registerBlock(woodenRail, "rail.wood"); } void registerItems () { titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon"); String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" }; blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern"); materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials"); toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod"); toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard"); woodPattern = new Pattern(PHConstruct.woodPattern, "WoodPattern", "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern"); metalPattern = new MetalPattern(PHConstruct.metalPattern, "MetalPattern", "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern"); armorPattern = new ArmorPattern(PHConstruct.armorPattern, "ArmorPattern", "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern"); TConstructRegistry.addItemToDirectory("blankPattern", blankPattern); TConstructRegistry.addItemToDirectory("woodPattern", woodPattern); TConstructRegistry.addItemToDirectory("metalPattern", metalPattern); TConstructRegistry.addItemToDirectory("armorPattern", armorPattern); String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead", "knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" }; for (int i = 1; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i)); } for (int i = 0; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i)); } String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" }; for (int i = 1; i < armorPartTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i)); } manualBook = new Manual(PHConstruct.manual); buckets = new FilledBucket(PHConstruct.buckets); pickaxe = new Pickaxe(PHConstruct.pickaxe); shovel = new Shovel(PHConstruct.shovel); hatchet = new Hatchet(PHConstruct.axe); broadsword = new Broadsword(PHConstruct.broadsword); longsword = new Longsword(PHConstruct.longsword); rapier = new Rapier(PHConstruct.rapier); dagger = new Dagger(PHConstruct.dagger); cutlass = new Cutlass(PHConstruct.cutlass); frypan = new FryingPan(PHConstruct.frypan); battlesign = new BattleSign(PHConstruct.battlesign); mattock = new Mattock(PHConstruct.mattock); chisel = new Chisel(PHConstruct.chisel); lumberaxe = new LumberAxe(PHConstruct.lumberaxe); cleaver = new Cleaver(PHConstruct.cleaver); scythe = new Scythe(PHConstruct.scythe); excavator = new Excavator(PHConstruct.excavator); hammer = new Hammer(PHConstruct.hammer); battleaxe = new Battleaxe(PHConstruct.battleaxe); shortbow = new Shortbow(PHConstruct.shortbow); arrow = new Arrow(PHConstruct.arrow); Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe }; String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe", "excavator", "hammer", "battleaxe" }; for (int i = 0; i < tools.length; i++) { TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]); } potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher"); pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead"); shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead"); hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead"); binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding"); toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding"); toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod"); largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate"); swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade"); wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard"); handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard"); crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar"); knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade"); fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard"); frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead"); signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead"); chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead"); scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade"); broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead"); excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead"); largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade"); hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead"); bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring"); arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead"); fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching"); Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard, frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead }; String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard", "crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring", "fletching", "arrowhead" }; for (int i = 0; i < toolParts.length; i++) { TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]); } diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond"); strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood"); oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry"); jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky"); //Wearables //heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet, 0).setUnlocalizedName("tconstruct.HeavyHelmet"); heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister"); //heavyBoots = new TArmorBase(PHConstruct.heavyBoots, 3).setUnlocalizedName("tconstruct.HeavyBoots"); //glove = new Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove"); knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage"); //Crystalline essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence"); goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead"); LiquidCasting basinCasting = TConstruct.getBasinCasting(); materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3); helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood"); chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood"); leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood"); bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood"); // essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence"); String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper", "ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper", "nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze", "nuggetAlumite", "nuggetSteel" }; for (int i = 0; i < materialStrings.length; i++) { TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i)); } String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" }; for (int i = 0; i < oreberries.length; i++) { TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i)); } TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0)); TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0)); TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0)); TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1)); TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2)); //Vanilla stack sizes Item.doorWood.setMaxStackSize(16); Item.doorIron.setMaxStackSize(16); Item.snowball.setMaxStackSize(64); Item.boat.setMaxStackSize(16); Item.minecartEmpty.setMaxStackSize(3); Item.minecartCrate.setMaxStackSize(3); Item.minecartPowered.setMaxStackSize(3); Item.itemsList[Block.cake.blockID].setMaxStackSize(16); //Block.torchWood.setTickRandomly(false); } void registerMaterials () { TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound"); TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", ""); TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", ""); TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged"); TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", ""); TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable"); TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", ""); TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", ""); TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", ""); TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", ""); TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", ""); TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", ""); TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime //Material ID, mass, fragility TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather for (int i = 0; i < 4; i++) TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime PatternBuilder pb = PatternBuilder.instance; if (PHConstruct.enableTWood) pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0); else pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0); if (PHConstruct.enableTStone) { pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1); pb.registerMaterial(Block.cobblestone, 2, "Stone"); } else pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0); pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2); if (PHConstruct.enableTFlint) pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); else pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); if (PHConstruct.enableTCactus) pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); else pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); if (PHConstruct.enableTBone) pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); else pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6); pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian"); if (PHConstruct.enableTNetherrack) pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); else pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); if (PHConstruct.enableTSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8); else pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8); if (PHConstruct.enableTPaper) pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9); else pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9); pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10); pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11); pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12); pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13); pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14); pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15); pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16); if (PHConstruct.enableTBlueSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17); else pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17); pb.addToolPattern((IPattern) woodPattern); } public static Item[] patternOutputs; public static FluidStack[] liquids; void addCraftingRecipes () { /* Tools */ patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod, toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead }; int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 17 }; if (PHConstruct.craftMetalTools) { for (int mat = 0; mat < 18; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat)); } } } else { for (int mat = 0; mat < nonMetals.length; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat])); } } } ToolBuilder tb = ToolBuilder.instance; tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding); tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard); tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod); tb.addNormalToolRecipe(shovel, shovelHead, toolRod); tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard); tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar); tb.addNormalToolRecipe(frypan, frypanHead, toolRod); tb.addNormalToolRecipe(battlesign, signHead, toolRod); tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead); tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar); tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard); tb.addNormalToolRecipe(chisel, chiselHead, toolRod); tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod); tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod); tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate); tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding); //tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod); BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow); tb.addCustomToolRecipe(recipe); tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching); ItemStack diamond = new ItemStack(Item.diamond); tb.registerToolMod(new ModRepair()); tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b")); tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72")); modE = new ModElectric(); tb.registerToolMod(modE); ItemStack redstoneItem = new ItemStack(Item.redstone); ItemStack redstoneBlock = new ItemStack(Block.blockRedstone); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem }, 2, 1)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneItem }, 2, 2)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock }, 2, 9)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneBlock }, 2, 10)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock, redstoneBlock }, 2, 18)); ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4); ItemStack lapisBlock = new ItemStack(Block.blockLapis); modL = new ModLapis(new ItemStack[] { lapisItem }, 10, 1); tb.registerToolMod(modL); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisItem }, 10, 2)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock }, 10, 9)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisBlock }, 10, 10)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock, lapisBlock }, 10, 18)); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair")); ItemStack blazePowder = new ItemStack(Item.blazePowder); tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder }, 7, 1)); tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder, blazePowder }, 7, 2)); tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt")); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal")); ItemStack quartzItem = new ItemStack(Item.netherQuartz); ItemStack quartzBlock = new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem }, 11, 1)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzItem }, 11, 2)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock }, 11, 4)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzBlock }, 11, 5)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock, quartzBlock }, 11, 8)); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free")); ItemStack silkyJewel = new ItemStack(materials, 1, 26); tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12)); ItemStack piston = new ItemStack(Block.pistonBase); tb.registerToolMod(new ModPiston(new ItemStack[] { piston }, 3, 1)); tb.registerToolMod(new ModPiston(new ItemStack[] { piston, piston }, 3, 2)); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading")); ItemStack holySoil = new ItemStack(craftedSoil, 1, 4); tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil }, 14, 1)); tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil, holySoil }, 14, 2)); ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye); tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball }, 15, 1)); tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball, spidereyeball }, 15, 2)); ItemStack obsidianPlate = new ItemStack(largePlate, 1, 6); tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1)); TConstructRegistry.registerActiveToolMod(new TActiveOmniMod()); /* Smeltery */ ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); ItemStack jewelCast = new ItemStack(metalPattern, 1, 23); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); //Blank tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80); tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80); //Ingots tableCasting.addCastingRecipe(new ItemStack(Item.ingotIron), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //Iron tableCasting.addCastingRecipe(new ItemStack(Item.ingotGold), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //gold tableCasting.addCastingRecipe(new ItemStack(materials, 1, 9), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //copper tableCasting.addCastingRecipe(new ItemStack(materials, 1, 10), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //tin tableCasting.addCastingRecipe(new ItemStack(materials, 1, 11), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //aluminum tableCasting.addCastingRecipe(new ItemStack(materials, 1, 3), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //cobalt tableCasting.addCastingRecipe(new ItemStack(materials, 1, 4), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //ardite tableCasting.addCastingRecipe(new ItemStack(materials, 1, 13), new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //bronze tableCasting.addCastingRecipe(new ItemStack(materials, 1, 14), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //albrass tableCasting.addCastingRecipe(new ItemStack(materials, 1, 5), new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //manyullyn tableCasting.addCastingRecipe(new ItemStack(materials, 1, 15), new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //alumite tableCasting.addCastingRecipe(new ItemStack(materials, 1, 18), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //obsidian tableCasting.addCastingRecipe(new ItemStack(materials, 1, 16), new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //steel tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //steel //Buckets ItemStack bucket = new ItemStack(Item.bucketEmpty); tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 0), new FluidStack(moltenIronFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //Iron tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 1), new FluidStack(moltenGoldFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //gold tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 2), new FluidStack(moltenCopperFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //copper tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 3), new FluidStack(moltenTinFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //tin tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 4), new FluidStack(moltenAluminumFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //aluminum tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 5), new FluidStack(moltenCobaltFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //cobalt tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 6), new FluidStack(moltenArditeFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //ardite tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 7), new FluidStack(moltenBronzeFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //bronze tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 8), new FluidStack(moltenAlubrassFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //alubrass tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 9), new FluidStack(moltenManyullynFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //manyullyn tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 10), new FluidStack(moltenAlumiteFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //alumite tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 11), new FluidStack(moltenObsidianFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10);// obsidian tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 12), new FluidStack(moltenSteelFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //steel tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 13), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //glass tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 14), new FluidStack(moltenStoneFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //seared stone tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 15), new FluidStack(moltenEmeraldFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //emerald tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80); liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1), new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1), new FluidStack(moltenSteelFluid, 1) }; int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16 }; for (int iter = 0; iter < patternOutputs.length; iter++) { if (patternOutputs[iter] != null) { ItemStack cast = new ItemStack(metalPattern, 1, iter + 1); tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++) { ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]); tableCasting.addCastingRecipe(metalCast, new FluidStack(liquids[iterTwo].getFluid(), ((IPattern) metalPattern).getPatternCost(metalCast) * TConstruct.ingotLiquidValue / 2), cast, 50); } } } ItemStack[] ingotShapes = { new ItemStack(Item.ingotIron), new ItemStack(Item.ingotGold), new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2) }; for (int i = 0; i < ingotShapes.length; i++) { TConstruct.tableCasting.addCastingRecipe(new ItemStack(TContent.metalPattern, 1, 0), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50); TConstruct.tableCasting.addCastingRecipe(new ItemStack(TContent.metalPattern, 1, 0), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50); } ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); LiquidCasting basinCasting = TConstructRegistry.getBasinCasting(); basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //Iron basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //gold basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //copper basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //tin basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //aluminum basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //cobalt basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //ardite basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //bronze basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //albrass basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //manyullyn basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //alumite basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2), null, true, 100);// obsidian basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //steel basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue / 9), new ItemStack(Block.gravel), true, 100); //brownstone basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, 25), new ItemStack(Block.obsidian), true, 100); //endstone basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, 1000), null, true, 100); //ender //Armor casts basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 0), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(helmetWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 0), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(helmetWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(chestplateWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(chestplateWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 2), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(leggingsWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(leggingsWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 3), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(bootsWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 3), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(bootsWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); //Ore Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); //Items Smeltery.addMelting(new ItemStack(Item.ingotIron, 4), Block.blockIron.blockID, 0, 500, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.ingotGold, 4), Block.blockGold.blockID, 0, 300, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.goldNugget, 4), Block.blockGold.blockID, 0, 150, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9)); Smeltery.addMelting(new ItemStack(materials, 1, 18), Block.obsidian.blockID, 0, 750, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue)); //Obsidian ingot Smeltery.addMelting(new ItemStack(blankPattern, 4, 1), metalBlock.blockID, 7, 150, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(blankPattern, 4, 2), metalBlock.blockID, 7, 150, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.enderPearl, 4), metalBlock.blockID, 10, 500, new FluidStack(moltenEnderFluid, 250)); Smeltery.addMelting(new ItemStack(metalBlock, 1, 10), metalBlock.blockID, 10, 500, new FluidStack(moltenEnderFluid, 1000)); //Blocks Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000)); Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250)); for (int i = 0; i < 16; i++) { Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250)); } //Alloys if (PHConstruct.harderBronze) Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 16), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze else Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 24), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, 16), new FluidStack(moltenAluminumFluid, 24), new FluidStack(moltenCopperFluid, 8)); //Aluminum Brass Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, 16), new FluidStack(moltenCobaltFluid, 32), new FluidStack(moltenArditeFluid, 32)); //Manyullyn Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, 48), new FluidStack(moltenAluminumFluid, 80), new FluidStack(moltenIronFluid, 32), new FluidStack(moltenObsidianFluid, 32)); //Alumite //Oreberries Smeltery.addMelting(new ItemStack(oreBerries, 4, 0), Block.blockIron.blockID, 0, 100, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue / 9)); //Iron Smeltery.addMelting(new ItemStack(oreBerries, 4, 1), Block.blockGold.blockID, 0, 100, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9)); //Gold Smeltery.addMelting(new ItemStack(oreBerries, 4, 2), metalBlock.blockID, 3, 100, new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue / 9)); //Copper Smeltery.addMelting(new ItemStack(oreBerries, 4, 3), metalBlock.blockID, 5, 100, new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue / 9)); //Tin Smeltery.addMelting(new ItemStack(oreBerries, 4, 4), metalBlock.blockID, 6, 100, new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue / 9)); //Aluminum //Vanilla Armor Smeltery.addMelting(new ItemStack(Item.helmetIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.plateIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 8)); Smeltery.addMelting(new ItemStack(Item.legsIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Item.bootsIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Item.helmetGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.plateGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8)); Smeltery.addMelting(new ItemStack(Item.legsGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Item.bootsGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Item.helmetChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.plateChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.legsChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.bootsChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue)); //Vanilla tools Smeltery.addMelting(new ItemStack(Item.hoeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.swordIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.shovelIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 1)); Smeltery.addMelting(new ItemStack(Item.pickaxeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.axeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.hoeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.swordGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.shovelGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 1)); Smeltery.addMelting(new ItemStack(Item.pickaxeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.axeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 3)); //Vanilla items Smeltery.addMelting(new ItemStack(Item.flintAndSteel, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.compass, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 4)); //Vanilla blocks Smeltery.addMelting(new ItemStack(Item.bucketEmpty), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.minecartEmpty), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.doorIron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6)); Smeltery.addMelting(new ItemStack(Block.fenceIron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6 / 16)); Smeltery.addMelting(new ItemStack(Block.pressurePlateIron), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Block.pressurePlateGold, 4), Block.blockGold.blockID, 0, 600, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Block.rail), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6 / 16)); Smeltery.addMelting(new ItemStack(Block.railPowered), Block.blockGold.blockID, 8, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.railDetector), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.railActivator), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.enchantmentTable), Block.obsidian.blockID, 0, 750, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Block.cauldron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 0), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 1), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 2), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); /* Detailing */ Detailing chiseling = TConstructRegistry.getChiselDetailing(); chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel); chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel); chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel); chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel); chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel); chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel); chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel); chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel); chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel); chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel); //chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel); //chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel); chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel); chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel); chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel); chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel); chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel); chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel); chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel); chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel); chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel); chiseling.addDetailing(materials, 18, multiBrick, 13, chisel); chiseling.addDetailing(multiBrick, 0, multiBrickFancy, 0, chisel); chiseling.addDetailing(multiBrick, 1, multiBrickFancy, 1, chisel); chiseling.addDetailing(multiBrick, 2, multiBrickFancy, 2, chisel); chiseling.addDetailing(multiBrick, 3, multiBrickFancy, 3, chisel); chiseling.addDetailing(multiBrick, 4, multiBrickFancy, 4, chisel); chiseling.addDetailing(multiBrick, 5, multiBrickFancy, 5, chisel); chiseling.addDetailing(multiBrick, 6, multiBrickFancy, 6, chisel); chiseling.addDetailing(multiBrick, 7, multiBrickFancy, 7, chisel); chiseling.addDetailing(multiBrick, 8, multiBrickFancy, 8, chisel); chiseling.addDetailing(multiBrick, 9, multiBrickFancy, 9, chisel); chiseling.addDetailing(multiBrick, 10, multiBrickFancy, 10, chisel); chiseling.addDetailing(multiBrick, 11, multiBrickFancy, 11, chisel); chiseling.addDetailing(multiBrick, 12, multiBrickFancy, 12, chisel); chiseling.addDetailing(multiBrick, 13, multiBrickFancy, 13, chisel); chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel); chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel); /*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/ chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel); chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel); chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel); chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel); chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel); chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 0), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockIron); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 1), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockGold); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 2), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockDiamond); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 3), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockEmerald); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 4), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockCobalt")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockArdite")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 6), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockManyullyn")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 7), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 8), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockBronze")); GameRegistry .addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 9), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockTin")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 10), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockNaturalAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 11), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockAluminumBrass")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 12), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockAlumite")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 13), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser))); //Drawbridge GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 1), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(largePlate, 1, 7), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Item.flintAndSteel))); //Igniter GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack( Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack( Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0))); /* Crafting */ GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.workbench); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood")); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest); if (PHConstruct.stencilTableCrafting) { GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3)); } GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood")); if (PHConstruct.stencilTableCrafting) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood")); GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern);//Vanilla books GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper); //Paper stack OreDictionary.registerOre("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1)); OreDictionary.registerOre("stoneMossy", new ItemStack(Block.cobblestoneMossy)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), "ppp", "ppp", "ppp", 'p', "stoneMossy")); //Moss ball GameRegistry.addRecipe(new ItemStack(materials, 1, 6), "ppp", "ppp", "ppp", 'p', new ItemStack(Block.stoneBrick, 1, 1)); //Moss ball GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod); //Auto-smelt GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod); //Auto-smelt GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt); //Slimy sand GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt); //Slimy sand GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel); //Grout GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 8, 1), Block.blockClay, Block.sand, Block.gravel, Block.sand, Block.gravel, Block.sand, Block.gravel, Block.sand, Block.gravel); //Grout GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15)); //Graveyard Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime //GameRegistry.addRecipe(new ItemStack(oreSlag, 1, 0), "pp", "pp", 'p', new ItemStack(materials, 1, 2)); //Seared brick block GameRegistry.addRecipe(new ItemStack(materials, 1, 25), "sss", "sns", "sss", 'n', new ItemStack(materials, 1, 24), 's', new ItemStack(Item.silk)); //Silky Cloth GameRegistry.addRecipe(new ItemStack(materials, 1, 25), "sss", "sns", "sss", 'n', new ItemStack(Item.goldNugget), 's', new ItemStack(Item.silk)); GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald)); //Silky Jewel GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, new Object[] { "www", "w w", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, new Object[] { "w w", "www", "www", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, new Object[] { "www", "w w", "w w", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, new Object[] { "w w", "w w", 'w', "logWood" })); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 12), 0.5f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f); //FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 12), 0.2f); FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f); //Metal conversion GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 12), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel GameRegistry.addRecipe(new ItemStack(Item.ingotIron), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 19)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 1, 9), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 20)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 1, 10), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 21)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 1, 12), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 22)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 1, 14), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 24)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 1, 18), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 27)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 1, 3), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 28)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 1, 4), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 29)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 1, 5), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 30)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 1, 13), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 31)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 1, 15), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 32)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 1, 16), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 33)); //Steel GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel //Dyes String[] pattern = { "###", "#m#", "###" }; String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite" }; for (int i = 0; i < 16; i++) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), pattern, 'm', dyeTypes[15 - i], '#', clearGlass)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), dyeTypes[15 - i], clearGlass)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), dyeTypes[15 - i], new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), pattern, 'm', dyeTypes[15 - i], '#', glassPane)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), dyeTypes[15 - i], glassPane)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), dyeTypes[15 - i], new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); } //Glass GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass }); GameRegistry.addRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', Block.glass, 'Q', Item.netherQuartz, 'W', Block.woodSingleSlab }); GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian }); //Smeltery ItemStack searedBrick = new ItemStack(materials, 1, 2); GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 0), "bbb", "bgb", "bbb", 'b', searedBrick, 'g', Block.glass); //Tank GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', Block.glass); //Glass GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', Block.glass); //Window GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 0), "bbb", "bgb", "bbb", 'b', searedBrick, 'g', clearGlass); //Tank GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', clearGlass); //Glass GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', clearGlass); //Window GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 'w', new ItemStack(stoneTorch)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod")); GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone)); GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone)); ItemStack aluBrass = new ItemStack(materials, 1, 14); GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass); ItemStack necroticBone = new ItemStack(materials, 1, 8); //Accessories GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum")); GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed)); GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), necroticBone, new ItemStack(heartCanister, 1, 0), new ItemStack(heartCanister, 1, 1)); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', new ItemStack(Item.ingotGold)); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', new ItemStack(materials, 1, 14)); //Armor GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood")); //Landmine GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); //Ultra hardcore recipes String[] surround = { "###", "#m#", "###" }; if (PHConstruct.goldAppleRecipe) { RecipeRemover.removeShapedRecipe(new ItemStack(Item.appleGold)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.goldenCarrot)); RecipeRemover.removeShapelessRecipe(new ItemStack(Item.speckledMelon)); GameRegistry.addRecipe(new ItemStack(Item.appleGold), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(Item.goldenCarrot), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.carrot)); GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3)); GameRegistry.addShapelessRecipe(new ItemStack(Item.speckledMelon), new ItemStack(Block.blockGold), new ItemStack(Item.melon)); tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8), new ItemStack(Item.appleRed), true, 50); } else { GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(Item.goldNugget), 'm', new ItemStack(Item.skull, 1, 3)); GameRegistry.addRecipe(new ItemStack(Item.appleGold), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(Item.goldenCarrot), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9 * 8), new ItemStack(Item.appleRed), true, 50); } tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8 * 9), new ItemStack(Item.appleRed), true, 50); //Drying rack DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0)); DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1)); DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2)); //DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3)); DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4)); DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5)); //DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather); //Slabs for (int i = 0; i < 7; i++) { GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i)); } GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11)); //Traps GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed)); GameRegistry.addRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 0)); GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood")); GameRegistry.addRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood")); //Slab crafters GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); GameRegistry.addRecipe(new ItemStack(essenceExtractor, 1, 0), " b ", "eme", "mmm", 'b', Item.book, 'e', Item.emerald, 'm', Block.whiteStone); //Slime GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood); GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0)); GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall); GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, new ItemStack(slimeGel, 1, Short.MAX_VALUE), "slimeBall")); //Slab crafters GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); } void setupToolTabs () { TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255)); TConstructRegistry.blockTab.init(new ItemStack(toolStationWood)); ItemStack tool = new ItemStack(longsword, 1, 0); NBTTagCompound compound = new NBTTagCompound(); compound.setCompoundTag("InfiTool", new NBTTagCompound()); compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2); compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0); compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10); tool.setTagCompound(compound); //TConstruct. TConstructRegistry.toolTab.init(tool); } public void addLoot () { //Item, min, max, weight ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27); tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1)); int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 }; Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead }; for (int partIter = 0; partIter < partTypes.length; partIter++) { for (int typeIter = 0; typeIter < validTypes.length; typeIter++) { tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15)); } } tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30); for (int i = 0; i < 13; i++) { tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20)); } tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40)); } public static String[] liquidNames; public void oreRegistry () { OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1)); OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2)); OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3)); OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4)); OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0)); OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1)); OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5)); OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2)); OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3)); OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3)); OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4)); OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5)); OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9)); OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10)); OreDictionary.registerOre("ingotNaturalAluminum", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("naturalAluminum", new ItemStack(materials, 1, 12)); OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13)); OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15)); OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16)); OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0)); OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1)); OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2)); OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3)); OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4)); OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5)); OreDictionary.registerOre("blockNaturalAluminum", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8)); OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9)); OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19)); OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20)); OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21)); OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27)); OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28)); OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29)); OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30)); OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31)); OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32)); OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33)); String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel", "blueslime" }; for (int i = 0; i < matNames.length; i++) OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i)); OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31)); String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow", "glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" }; for (int i = 0; i < 16; i++) { OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i)); } BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg()); BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow()); //Vanilla stuff OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0)); OreDictionary.registerOre("glass", new ItemStack(clearGlass)); RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder)); } public static boolean thaumcraftAvailable; public void intermodCommunication () { if (Loader.isModLoaded("Thaumcraft")) { FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13)); } if (Loader.isModLoaded("Mystcraft")) { MystImcHandler.blacklistFluids(); } if (Loader.isModLoaded("BuildCraft|Transport")) { BCImcHandler.registerFacades(); } /* FORESTRY * Edit these strings to change what items are added to the backpacks * Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on * Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder * May add more backpack items later - Spyboticsguy */ if (Loader.isModLoaded("Forestry")) { String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*"; FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems); } if (!Loader.isModLoaded("AppliedEnergistics")) { AEImcHandler.registerForSpatialIO(); } } private static boolean initRecipes; public static void modRecipes () { if (!initRecipes) { initRecipes = true; if (PHConstruct.removeVanillaToolRecipes) { RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold)); } } } public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray) { String var3 = ""; int var4 = 0; int var5 = 0; int var6 = 0; if (objArray[var4] instanceof String[]) { String[] var7 = (String[]) ((String[]) objArray[var4++]); for (int var8 = 0; var8 < var7.length; ++var8) { String var9 = var7[var8]; ++var6; var5 = var9.length(); var3 = var3 + var9; } } else { while (objArray[var4] instanceof String) { String var11 = (String) objArray[var4++]; ++var6; var5 = var11.length(); var3 = var3 + var11; } } HashMap var12; for (var12 = new HashMap(); var4 < objArray.length; var4 += 2) { Character var13 = (Character) objArray[var4]; ItemStack var14 = null; if (objArray[var4 + 1] instanceof Item) { var14 = new ItemStack((Item) objArray[var4 + 1]); } else if (objArray[var4 + 1] instanceof Block) { var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE); } else if (objArray[var4 + 1] instanceof ItemStack) { var14 = (ItemStack) objArray[var4 + 1]; } var12.put(var13, var14); } ItemStack[] var15 = new ItemStack[var5 * var6]; for (int var16 = 0; var16 < var5 * var6; ++var16) { char var10 = var3.charAt(var16); if (var12.containsKey(Character.valueOf(var10))) { var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy(); } else { var15[var16] = null; } } ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack); recipeList.add(0, var17); } public void modIntegration () { ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), ""); /* IC2 */ //ItemStack reBattery = ic2.api.item.Items.getItem("reBattery"); Object reBattery = getStaticItem("reBattery", "ic2.core.Ic2Items"); if (reBattery != null) { modE.batteries.add((ItemStack) reBattery); } //ItemStack chargedReBattery = ic2.api.item.Items.getItem("chargedReBattery"); Object chargedReBattery = getStaticItem("chargedReBattery", "ic2.core.Ic2Items"); if (chargedReBattery != null) { modE.batteries.add((ItemStack) chargedReBattery); } //ItemStack electronicCircuit = ic2.api.item.Items.getItem("electronicCircuit"); Object electronicCircuit = getStaticItem("electronicCircuit", "ic2.core.Ic2Items"); if (electronicCircuit != null) modE.circuits.add((ItemStack) electronicCircuit); if (chargedReBattery != null && electronicCircuit != null) TConstructClientRegistry.registerManualModifier("electricmod", ironpick.copy(), (ItemStack) chargedReBattery, (ItemStack) electronicCircuit); /* Thaumcraft */ Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems"); if (obj != null) { TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools."); thaumcraftAvailable = true; TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true); TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic"); PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31); for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31)); } TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f); TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f); TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F); } else { TConstruct.logger.warning("Thaumcraft not detected."); } if (Loader.isModLoaded("Natura")) { try { Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent"); TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f); } catch (Exception e) { } //No need to handle } ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting(); /* Thermal Expansion */ ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotLead"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotSilver"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotPlatinum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotInvar"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar } ores = OreDictionary.getOres("ingotElectrum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum } ores = OreDictionary.getOres("blockNickel"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockLead"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockSilver"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockPlatinum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockInvar"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockElectrum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue * 9), null, 100); } } public static Object getStaticItem (String name, String classPackage) { try { Class clazz = Class.forName(classPackage); Field field = clazz.getDeclaredField(name); Object ret = field.get(null); if (ret != null && (ret instanceof ItemStack || ret instanceof Item)) return ret; return null; } catch (Exception e) { TConstruct.logger.warning("Could not find " + name); return null; } } @Override public int getBurnTime (ItemStack fuel) { if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7) return 26400; return 0; } }
void registerBlocks () { //Tool Station toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation"); GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock"); GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation"); GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter"); GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder"); GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper"); toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge"); GameRegistry.registerBlock(toolForge, ToolForgeItemBlock.class, "ToolForgeBlock"); GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge"); craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation"); GameRegistry.registerBlock(craftingStationWood, "CraftingStation"); GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation"); craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab"); GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab"); heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan"); GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock"); GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic"); craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil"); craftedSoil.stepSound = Block.soundGravelFootstep; GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil"); searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab"); searedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab"); speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab"); speedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab"); metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock"); metalBlock.stepSound = Block.soundMetalFootstep; GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock"); meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock"); GameRegistry.registerBlock(meatBlock, "MeatBlock"); OreDictionary.registerOre("hambone", new ItemStack(meatBlock)); LanguageRegistry.addName(meatBlock, "Hambone"); GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw)); woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth"); woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1"); woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth"); woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2"); //Smeltery smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery"); GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery"); GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain"); GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants"); lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setUnlocalizedName("LavaTank"); lavaTank.setStepSound(Block.soundGlassFootstep); GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank"); GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank"); searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock"); GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock"); GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable"); GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet"); GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin"); castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel"); GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel"); GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel"); tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air"); GameRegistry.registerBlock(tankAir, "TankAir"); GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air"); //Redstone machines redstoneMachine = new RedstoneMachine(PHConstruct.redstoneMachine).setUnlocalizedName("Redstone.Machine"); GameRegistry.registerBlock(redstoneMachine, RedstoneMachineItem.class, "Redstone.Machine"); GameRegistry.registerTileEntity(DrawbridgeLogic.class, "Drawbridge"); GameRegistry.registerTileEntity(FirestarterLogic.class, "Firestarter"); GameRegistry.registerTileEntity(AdvancedDrawbridgeLogic.class, "AdvDrawbridge"); //Traps landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone) .setUnlocalizedName("landmine"); GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine"); GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine"); punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji"); GameRegistry.registerBlock(punji, "trap.punji"); barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak"); GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak"); barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce"); GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce"); barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch"); GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch"); barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle"); GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle"); dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack"); GameRegistry.registerBlock(dryingRack, "Armor.DryingRack"); GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack"); //Liquids liquidMetal = new MaterialLiquid(MapColor.tntColor); moltenIronFluid = new Fluid("iron.molten"); if (!FluidRegistry.registerFluid(moltenIronFluid)) moltenIronFluid = FluidRegistry.getFluid("iron.molten"); moltenIron = new LiquidMetalFinite(PHConstruct.moltenIron, moltenIronFluid, "liquid_iron").setUnlocalizedName("metal.molten.iron"); GameRegistry.registerBlock(moltenIron, "metal.molten.iron"); fluids[0] = moltenIronFluid; fluidBlocks[0] = moltenIron; moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty))); moltenGoldFluid = new Fluid("gold.molten"); if (!FluidRegistry.registerFluid(moltenGoldFluid)) moltenGoldFluid = FluidRegistry.getFluid("gold.molten"); moltenGold = new LiquidMetalFinite(PHConstruct.moltenGold, moltenGoldFluid, "liquid_gold").setUnlocalizedName("metal.molten.gold"); GameRegistry.registerBlock(moltenGold, "metal.molten.gold"); fluids[1] = moltenGoldFluid; fluidBlocks[1] = moltenGold; moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty))); moltenCopperFluid = new Fluid("copper.molten"); if (!FluidRegistry.registerFluid(moltenCopperFluid)) moltenCopperFluid = FluidRegistry.getFluid("copper.molten"); moltenCopper = new LiquidMetalFinite(PHConstruct.moltenCopper, moltenCopperFluid, "liquid_copper").setUnlocalizedName("metal.molten.copper"); GameRegistry.registerBlock(moltenCopper, "metal.molten.copper"); fluids[2] = moltenCopperFluid; fluidBlocks[2] = moltenCopper; moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty))); moltenTinFluid = new Fluid("tin.molten"); if (!FluidRegistry.registerFluid(moltenTinFluid)) moltenTinFluid = FluidRegistry.getFluid("tin.molten"); moltenTin = new LiquidMetalFinite(PHConstruct.moltenTin, moltenTinFluid, "liquid_tin").setUnlocalizedName("metal.molten.tin"); GameRegistry.registerBlock(moltenTin, "metal.molten.tin"); fluids[3] = moltenTinFluid; fluidBlocks[3] = moltenTin; moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty))); moltenAluminumFluid = new Fluid("aluminum.molten"); if (!FluidRegistry.registerFluid(moltenAluminumFluid)) moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten"); moltenAluminum = new LiquidMetalFinite(PHConstruct.moltenAluminum, moltenAluminumFluid, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum"); GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum"); fluids[4] = moltenAluminumFluid; fluidBlocks[4] = moltenAluminum; moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty))); moltenCobaltFluid = new Fluid("cobalt.molten"); if (!FluidRegistry.registerFluid(moltenCobaltFluid)) moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten"); moltenCobalt = new LiquidMetalFinite(PHConstruct.moltenCobalt, moltenCobaltFluid, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt"); GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt"); fluids[5] = moltenCobaltFluid; fluidBlocks[5] = moltenCobalt; moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty))); moltenArditeFluid = new Fluid("ardite.molten"); if (!FluidRegistry.registerFluid(moltenArditeFluid)) moltenArditeFluid = FluidRegistry.getFluid("ardite.molten"); moltenArdite = new LiquidMetalFinite(PHConstruct.moltenArdite, moltenArditeFluid, "liquid_ardite").setUnlocalizedName("metal.molten.ardite"); GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite"); fluids[6] = moltenArditeFluid; fluidBlocks[6] = moltenArdite; moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty))); moltenBronzeFluid = new Fluid("bronze.molten"); if (!FluidRegistry.registerFluid(moltenBronzeFluid)) moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten"); moltenBronze = new LiquidMetalFinite(PHConstruct.moltenBronze, moltenBronzeFluid, "liquid_bronze").setUnlocalizedName("metal.molten.bronze"); GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze"); fluids[7] = moltenBronzeFluid; fluidBlocks[7] = moltenBronze; moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty))); moltenAlubrassFluid = new Fluid("aluminumbrass.molten"); if (!FluidRegistry.registerFluid(moltenAlubrassFluid)) moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten"); moltenAlubrass = new LiquidMetalFinite(PHConstruct.moltenAlubrass, moltenAlubrassFluid, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass"); GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass"); fluids[8] = moltenAlubrassFluid; fluidBlocks[8] = moltenAlubrass; moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty))); moltenManyullynFluid = new Fluid("manyullyn.molten"); if (!FluidRegistry.registerFluid(moltenManyullynFluid)) moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten"); moltenManyullyn = new LiquidMetalFinite(PHConstruct.moltenManyullyn, moltenManyullynFluid, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn"); GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn"); fluids[9] = moltenManyullynFluid; fluidBlocks[9] = moltenManyullyn; moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty))); moltenAlumiteFluid = new Fluid("alumite.molten"); if (!FluidRegistry.registerFluid(moltenAlumiteFluid)) moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten"); moltenAlumite = new LiquidMetalFinite(PHConstruct.moltenAlumite, moltenAlumiteFluid, "liquid_alumite").setUnlocalizedName("metal.molten.alumite"); GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite"); fluids[10] = moltenAlumiteFluid; fluidBlocks[10] = moltenAlumite; moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty))); moltenObsidianFluid = new Fluid("obsidian.molten"); if (!FluidRegistry.registerFluid(moltenObsidianFluid)) moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten"); moltenObsidian = new LiquidMetalFinite(PHConstruct.moltenObsidian, moltenObsidianFluid, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian"); GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian"); fluids[11] = moltenObsidianFluid; fluidBlocks[11] = moltenObsidian; moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty))); moltenSteelFluid = new Fluid("steel.molten"); if (!FluidRegistry.registerFluid(moltenSteelFluid)) moltenSteelFluid = FluidRegistry.getFluid("steel.molten"); moltenSteel = new LiquidMetalFinite(PHConstruct.moltenSteel, moltenSteelFluid, "liquid_steel").setUnlocalizedName("metal.molten.steel"); GameRegistry.registerBlock(moltenSteel, "metal.molten.steel"); fluids[12] = moltenSteelFluid; fluidBlocks[12] = moltenSteel; moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty))); moltenGlassFluid = new Fluid("glass.molten"); if (!FluidRegistry.registerFluid(moltenGlassFluid)) moltenGlassFluid = FluidRegistry.getFluid("glass.molten"); moltenGlass = new LiquidMetalFinite(PHConstruct.moltenGlass, moltenGlassFluid, "liquid_glass").setUnlocalizedName("metal.molten.glass"); GameRegistry.registerBlock(moltenGlass, "metal.molten.glass"); fluids[13] = moltenGlassFluid; fluidBlocks[13] = moltenGlass; moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty))); moltenStoneFluid = new Fluid("stone.seared"); if (!FluidRegistry.registerFluid(moltenStoneFluid)) moltenStoneFluid = FluidRegistry.getFluid("stone.seared"); moltenStone = new LiquidMetalFinite(PHConstruct.moltenStone, moltenStoneFluid, "liquid_stone").setUnlocalizedName("molten.stone"); GameRegistry.registerBlock(moltenStone, "molten.stone"); fluids[14] = moltenStoneFluid; fluidBlocks[14] = moltenStone; moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty))); moltenEmeraldFluid = new Fluid("emerald.liquid"); if (!FluidRegistry.registerFluid(moltenEmeraldFluid)) moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid"); moltenEmerald = new LiquidMetalFinite(PHConstruct.moltenEmerald, moltenEmeraldFluid, "liquid_villager").setUnlocalizedName("molten.emerald"); GameRegistry.registerBlock(moltenEmerald, "molten.emerald"); fluids[15] = moltenEmeraldFluid; fluidBlocks[15] = moltenEmerald; moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty))); bloodFluid = new Fluid("blood"); if (!FluidRegistry.registerFluid(bloodFluid)) bloodFluid = FluidRegistry.getFluid("blood"); blood = new LiquidMetalFinite(PHConstruct.blood, bloodFluid, "liquid_cow").setUnlocalizedName("liquid.blood"); GameRegistry.registerBlock(blood, "liquid.blood"); fluids[16] = bloodFluid; fluidBlocks[16] = blood; bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty))); moltenNickelFluid = new Fluid("nickel.molten"); if (!FluidRegistry.registerFluid(moltenNickelFluid)) moltenNickelFluid = FluidRegistry.getFluid("nickel.molten"); moltenNickel = new LiquidMetalFinite(PHConstruct.moltenNickel, moltenNickelFluid, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel"); GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel"); fluids[17] = moltenNickelFluid; fluidBlocks[17] = moltenNickel; moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty))); moltenLeadFluid = new Fluid("lead.molten"); if (!FluidRegistry.registerFluid(moltenLeadFluid)) moltenLeadFluid = FluidRegistry.getFluid("lead.molten"); moltenLead = new LiquidMetalFinite(PHConstruct.moltenLead, moltenLeadFluid, "liquid_lead").setUnlocalizedName("metal.molten.lead"); GameRegistry.registerBlock(moltenLead, "metal.molten.lead"); fluids[18] = moltenLeadFluid; fluidBlocks[18] = moltenLead; moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty))); moltenSilverFluid = new Fluid("silver.molten"); if (!FluidRegistry.registerFluid(moltenSilverFluid)) moltenSilverFluid = FluidRegistry.getFluid("silver.molten"); moltenSilver = new LiquidMetalFinite(PHConstruct.moltenSilver, moltenSilverFluid, "liquid_silver").setUnlocalizedName("metal.molten.silver"); GameRegistry.registerBlock(moltenSilver, "metal.molten.silver"); fluids[19] = moltenSilverFluid; fluidBlocks[19] = moltenSilver; moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty))); moltenShinyFluid = new Fluid("platinum.molten"); if (!FluidRegistry.registerFluid(moltenShinyFluid)) moltenShinyFluid = FluidRegistry.getFluid("platinum.molten"); moltenShiny = new LiquidMetalFinite(PHConstruct.moltenShiny, moltenShinyFluid, "liquid_shiny").setUnlocalizedName("metal.molten.shiny"); GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny"); fluids[20] = moltenLeadFluid; fluidBlocks[20] = moltenShiny; moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty))); moltenInvarFluid = new Fluid("invar.molten"); if (!FluidRegistry.registerFluid(moltenInvarFluid)) moltenInvarFluid = FluidRegistry.getFluid("invar.molten"); moltenInvar = new LiquidMetalFinite(PHConstruct.moltenInvar, moltenInvarFluid, "liquid_invar").setUnlocalizedName("metal.molten.invar"); GameRegistry.registerBlock(moltenInvar, "metal.molten.invar"); fluids[21] = moltenInvarFluid; fluidBlocks[21] = moltenInvar; moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty))); moltenElectrumFluid = new Fluid("electrum.molten"); if (!FluidRegistry.registerFluid(moltenElectrumFluid)) moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten"); moltenElectrum = new LiquidMetalFinite(PHConstruct.moltenElectrum, moltenElectrumFluid, "liquid_electrum").setUnlocalizedName("metal.molten.electrum"); GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum"); fluids[22] = moltenElectrumFluid; fluidBlocks[22] = moltenElectrum; moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty))); moltenEnderFluid = new Fluid("ender"); if (!FluidRegistry.registerFluid(moltenEnderFluid)) moltenEnderFluid = FluidRegistry.getFluid("ender"); moltenEnder = new LiquidMetalFinite(PHConstruct.moltenEnder, moltenEnderFluid, "liquid_ender").setUnlocalizedName("liquid.ender"); GameRegistry.registerBlock(moltenEnder, "liquid.ender"); fluids[23] = moltenEnderFluid; fluidBlocks[23] = moltenEnder; moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty))); //Slime slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f); blueSlimeFluid = new Fluid("slime.blue"); if (!FluidRegistry.registerFluid(blueSlimeFluid)) blueSlimeFluid = FluidRegistry.getFluid("slime.blue"); slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime"); GameRegistry.registerBlock(slimePool, "liquid.slime"); fluids[24] = blueSlimeFluid; fluidBlocks[24] = slimePool; blueSlimeFluid.setBlockID(slimePool); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty))); slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel"); GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel"); slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass"); GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass"); slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall"); GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall"); slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves"); GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves"); slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling"); GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling"); slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water).setStepSound(slimeStep).setUnlocalizedName("slime.channel"); GameRegistry.registerBlock(slimeChannel, "slime.channel"); TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1; slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setUnlocalizedName("slime.pad"); GameRegistry.registerBlock(slimePad, "slime.pad"); TConstructRegistry.drawbridgeState[slimePad.blockID] = 1; //Decoration stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch"); GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch"); stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder"); GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder"); multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick"); GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick"); multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy"); GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy"); //Ores String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" }; oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one"); GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one"); String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" }; oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two"); GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two"); String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" }; oreSlag = new MetalOre(PHConstruct.oreSlag, Material.iron, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore"); GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick"); MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1); oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore"); GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre"); MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2); MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4); speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock"); GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock"); //Glass clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock"); clearGlass.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock"); glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false); GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane"); stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear"); stainedGlassClear.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear"); stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane); GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained"); //Crystalline essenceExtractor = new EssenceExtractor(PHConstruct.essenceExtractor).setHardness(12f).setUnlocalizedName("extractor.essence"); GameRegistry.registerBlock(essenceExtractor, "extractor.essence"); GameRegistry.registerTileEntity(EssenceExtractorLogic.class, "extractor.essence"); //Rail woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood"); GameRegistry.registerBlock(woodenRail, "rail.wood"); } void registerItems () { titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon"); String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" }; blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern"); materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials"); toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod"); toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard"); woodPattern = new Pattern(PHConstruct.woodPattern, "WoodPattern", "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern"); metalPattern = new MetalPattern(PHConstruct.metalPattern, "MetalPattern", "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern"); armorPattern = new ArmorPattern(PHConstruct.armorPattern, "ArmorPattern", "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern"); TConstructRegistry.addItemToDirectory("blankPattern", blankPattern); TConstructRegistry.addItemToDirectory("woodPattern", woodPattern); TConstructRegistry.addItemToDirectory("metalPattern", metalPattern); TConstructRegistry.addItemToDirectory("armorPattern", armorPattern); String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead", "knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" }; for (int i = 1; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i)); } for (int i = 0; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i)); } String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" }; for (int i = 1; i < armorPartTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i)); } manualBook = new Manual(PHConstruct.manual); buckets = new FilledBucket(PHConstruct.buckets); pickaxe = new Pickaxe(PHConstruct.pickaxe); shovel = new Shovel(PHConstruct.shovel); hatchet = new Hatchet(PHConstruct.axe); broadsword = new Broadsword(PHConstruct.broadsword); longsword = new Longsword(PHConstruct.longsword); rapier = new Rapier(PHConstruct.rapier); dagger = new Dagger(PHConstruct.dagger); cutlass = new Cutlass(PHConstruct.cutlass); frypan = new FryingPan(PHConstruct.frypan); battlesign = new BattleSign(PHConstruct.battlesign); mattock = new Mattock(PHConstruct.mattock); chisel = new Chisel(PHConstruct.chisel); lumberaxe = new LumberAxe(PHConstruct.lumberaxe); cleaver = new Cleaver(PHConstruct.cleaver); scythe = new Scythe(PHConstruct.scythe); excavator = new Excavator(PHConstruct.excavator); hammer = new Hammer(PHConstruct.hammer); battleaxe = new Battleaxe(PHConstruct.battleaxe); shortbow = new Shortbow(PHConstruct.shortbow); arrow = new Arrow(PHConstruct.arrow); Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe }; String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe", "excavator", "hammer", "battleaxe" }; for (int i = 0; i < tools.length; i++) { TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]); } potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher"); pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead"); shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead"); hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead"); binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding"); toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding"); toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod"); largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate"); swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade"); wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard"); handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard"); crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar"); knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade"); fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard"); frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead"); signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead"); chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead"); scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade"); broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead"); excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead"); largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade"); hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead"); bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring"); arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead"); fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching"); Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard, frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead }; String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard", "crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring", "fletching", "arrowhead" }; for (int i = 0; i < toolParts.length; i++) { TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]); } diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond"); strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood"); oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry"); jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky"); //Wearables //heavyHelmet = new TArmorBase(PHConstruct.heavyHelmet, 0).setUnlocalizedName("tconstruct.HeavyHelmet"); heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister"); //heavyBoots = new TArmorBase(PHConstruct.heavyBoots, 3).setUnlocalizedName("tconstruct.HeavyBoots"); //glove = new Glove(PHConstruct.glove).setUnlocalizedName("tconstruct.Glove"); knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage"); //Crystalline essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence"); goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead"); LiquidCasting basinCasting = TConstruct.getBasinCasting(); materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3); helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood"); chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood"); leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood"); bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood"); // essenceCrystal = new EssenceCrystal(PHConstruct.essenceCrystal).setUnlocalizedName("tconstruct.crystal.essence"); String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper", "ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper", "nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze", "nuggetAlumite", "nuggetSteel" }; for (int i = 0; i < materialStrings.length; i++) { TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i)); } String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" }; for (int i = 0; i < oreberries.length; i++) { TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i)); } TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0)); TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0)); TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0)); TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1)); TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2)); //Vanilla stack sizes Item.doorWood.setMaxStackSize(16); Item.doorIron.setMaxStackSize(16); Item.snowball.setMaxStackSize(64); Item.boat.setMaxStackSize(16); Item.minecartEmpty.setMaxStackSize(3); Item.minecartCrate.setMaxStackSize(3); Item.minecartPowered.setMaxStackSize(3); Item.itemsList[Block.cake.blockID].setMaxStackSize(16); //Block.torchWood.setTickRandomly(false); } void registerMaterials () { TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound"); TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", ""); TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", ""); TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged"); TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", ""); TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable"); TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", ""); TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", ""); TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", ""); TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", ""); TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", ""); TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", ""); TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime //Material ID, mass, fragility TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather for (int i = 0; i < 4; i++) TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime PatternBuilder pb = PatternBuilder.instance; if (PHConstruct.enableTWood) pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0); else pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0); if (PHConstruct.enableTStone) { pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1); pb.registerMaterial(Block.cobblestone, 2, "Stone"); } else pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0); pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2); if (PHConstruct.enableTFlint) pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); else pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); if (PHConstruct.enableTCactus) pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); else pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); if (PHConstruct.enableTBone) pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); else pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6); pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian"); if (PHConstruct.enableTNetherrack) pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); else pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); if (PHConstruct.enableTSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8); else pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8); if (PHConstruct.enableTPaper) pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9); else pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9); pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10); pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11); pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12); pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13); pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14); pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15); pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16); if (PHConstruct.enableTBlueSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17); else pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17); pb.addToolPattern((IPattern) woodPattern); } public static Item[] patternOutputs; public static FluidStack[] liquids; void addCraftingRecipes () { /* Tools */ patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod, toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead }; int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 17 }; if (PHConstruct.craftMetalTools) { for (int mat = 0; mat < 18; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat)); } } } else { for (int mat = 0; mat < nonMetals.length; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat])); } } } ToolBuilder tb = ToolBuilder.instance; tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding); tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard); tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod); tb.addNormalToolRecipe(shovel, shovelHead, toolRod); tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard); tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar); tb.addNormalToolRecipe(frypan, frypanHead, toolRod); tb.addNormalToolRecipe(battlesign, signHead, toolRod); tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead); tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar); tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard); tb.addNormalToolRecipe(chisel, chiselHead, toolRod); tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod); tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod); tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate); tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding); //tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod); BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow); tb.addCustomToolRecipe(recipe); tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching); ItemStack diamond = new ItemStack(Item.diamond); tb.registerToolMod(new ModRepair()); tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b")); tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72")); modE = new ModElectric(); tb.registerToolMod(modE); ItemStack redstoneItem = new ItemStack(Item.redstone); ItemStack redstoneBlock = new ItemStack(Block.blockRedstone); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem }, 2, 1)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneItem }, 2, 2)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock }, 2, 9)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneItem, redstoneBlock }, 2, 10)); tb.registerToolMod(new ModRedstone(new ItemStack[] { redstoneBlock, redstoneBlock }, 2, 18)); ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4); ItemStack lapisBlock = new ItemStack(Block.blockLapis); modL = new ModLapis(new ItemStack[] { lapisItem }, 10, 1); tb.registerToolMod(modL); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisItem }, 10, 2)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock }, 10, 9)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisItem, lapisBlock }, 10, 10)); tb.registerToolMod(new ModLapis(new ItemStack[] { lapisBlock, lapisBlock }, 10, 18)); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair")); ItemStack blazePowder = new ItemStack(Item.blazePowder); tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder }, 7, 1)); tb.registerToolMod(new ModBlaze(new ItemStack[] { blazePowder, blazePowder }, 7, 2)); tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt")); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal")); ItemStack quartzItem = new ItemStack(Item.netherQuartz); ItemStack quartzBlock = new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem }, 11, 1)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzItem }, 11, 2)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock }, 11, 4)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzItem, quartzBlock }, 11, 5)); tb.registerToolMod(new ModAttack("Quartz", new ItemStack[] { quartzBlock, quartzBlock }, 11, 8)); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free")); ItemStack silkyJewel = new ItemStack(materials, 1, 26); tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12)); ItemStack piston = new ItemStack(Block.pistonBase); tb.registerToolMod(new ModPiston(new ItemStack[] { piston }, 3, 1)); tb.registerToolMod(new ModPiston(new ItemStack[] { piston, piston }, 3, 2)); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading")); ItemStack holySoil = new ItemStack(craftedSoil, 1, 4); tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil }, 14, 1)); tb.registerToolMod(new ModSmite("Smite", new ItemStack[] { holySoil, holySoil }, 14, 2)); ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye); tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball }, 15, 1)); tb.registerToolMod(new ModAntiSpider("Anti-Spider", new ItemStack[] { spidereyeball, spidereyeball }, 15, 2)); ItemStack obsidianPlate = new ItemStack(largePlate, 1, 6); tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1)); TConstructRegistry.registerActiveToolMod(new TActiveOmniMod()); /* Smeltery */ ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); ItemStack jewelCast = new ItemStack(metalPattern, 1, 23); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); //Blank tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80); tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80); //Ingots tableCasting.addCastingRecipe(new ItemStack(Item.ingotIron), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //Iron tableCasting.addCastingRecipe(new ItemStack(Item.ingotGold), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //gold tableCasting.addCastingRecipe(new ItemStack(materials, 1, 9), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //copper tableCasting.addCastingRecipe(new ItemStack(materials, 1, 10), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //tin tableCasting.addCastingRecipe(new ItemStack(materials, 1, 11), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //aluminum tableCasting.addCastingRecipe(new ItemStack(materials, 1, 3), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //cobalt tableCasting.addCastingRecipe(new ItemStack(materials, 1, 4), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //ardite tableCasting.addCastingRecipe(new ItemStack(materials, 1, 13), new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //bronze tableCasting.addCastingRecipe(new ItemStack(materials, 1, 14), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //albrass tableCasting.addCastingRecipe(new ItemStack(materials, 1, 5), new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //manyullyn tableCasting.addCastingRecipe(new ItemStack(materials, 1, 15), new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //alumite tableCasting.addCastingRecipe(new ItemStack(materials, 1, 18), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //obsidian tableCasting.addCastingRecipe(new ItemStack(materials, 1, 16), new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //steel tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), ingotcast, 80); //steel //Buckets ItemStack bucket = new ItemStack(Item.bucketEmpty); tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 0), new FluidStack(moltenIronFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //Iron tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 1), new FluidStack(moltenGoldFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //gold tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 2), new FluidStack(moltenCopperFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //copper tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 3), new FluidStack(moltenTinFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //tin tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 4), new FluidStack(moltenAluminumFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //aluminum tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 5), new FluidStack(moltenCobaltFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //cobalt tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 6), new FluidStack(moltenArditeFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //ardite tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 7), new FluidStack(moltenBronzeFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //bronze tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 8), new FluidStack(moltenAlubrassFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //alubrass tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 9), new FluidStack(moltenManyullynFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //manyullyn tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 10), new FluidStack(moltenAlumiteFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //alumite tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 11), new FluidStack(moltenObsidianFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10);// obsidian tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 12), new FluidStack(moltenSteelFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //steel tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 13), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //glass tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 14), new FluidStack(moltenStoneFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //seared stone tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 15), new FluidStack(moltenEmeraldFluid, FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); //emerald tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80); liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1), new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1), new FluidStack(moltenSteelFluid, 1) }; int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16 }; for (int iter = 0; iter < patternOutputs.length; iter++) { if (patternOutputs[iter] != null) { ItemStack cast = new ItemStack(metalPattern, 1, iter + 1); tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++) { ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]); tableCasting.addCastingRecipe(metalCast, new FluidStack(liquids[iterTwo].getFluid(), ((IPattern) metalPattern).getPatternCost(metalCast) * TConstruct.ingotLiquidValue / 2), cast, 50); } } } ItemStack[] ingotShapes = { new ItemStack(Item.ingotIron), new ItemStack(Item.ingotGold), new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2) }; for (int i = 0; i < ingotShapes.length; i++) { TConstruct.tableCasting.addCastingRecipe(new ItemStack(TContent.metalPattern, 1, 0), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50); TConstruct.tableCasting.addCastingRecipe(new ItemStack(TContent.metalPattern, 1, 0), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50); } ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); LiquidCasting basinCasting = TConstructRegistry.getBasinCasting(); basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //Iron basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //gold basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //copper basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //tin basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //aluminum basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //cobalt basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //ardite basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //bronze basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //albrass basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //manyullyn basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //alumite basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2), null, true, 100);// obsidian basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 9), null, true, 100); //steel basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue / 9), new ItemStack(Block.gravel), true, 100); //brownstone basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, 25), new ItemStack(Block.obsidian), true, 100); //endstone basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, 1000), null, true, 100); //ender //Armor casts basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 0), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(helmetWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 0), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(helmetWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(chestplateWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(chestplateWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 2), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(leggingsWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(leggingsWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 3), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(bootsWood), 50, new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, 3), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10), new ItemStack(bootsWood), 50, new FluidRenderProperties( Applications.BASIN.minHeight, 0.65F, Applications.BASIN)); //Ore Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); //Items Smeltery.addMelting(new ItemStack(Item.ingotIron, 4), Block.blockIron.blockID, 0, 500, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.ingotGold, 4), Block.blockGold.blockID, 0, 300, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.goldNugget, 4), Block.blockGold.blockID, 0, 150, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9)); Smeltery.addMelting(new ItemStack(materials, 1, 18), Block.obsidian.blockID, 0, 750, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue)); //Obsidian ingot Smeltery.addMelting(new ItemStack(blankPattern, 4, 1), metalBlock.blockID, 7, 150, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(blankPattern, 4, 2), metalBlock.blockID, 7, 150, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.enderPearl, 4), metalBlock.blockID, 10, 500, new FluidStack(moltenEnderFluid, 250)); Smeltery.addMelting(new ItemStack(metalBlock, 1, 10), metalBlock.blockID, 10, 500, new FluidStack(moltenEnderFluid, 1000)); //Blocks Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000)); Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250)); for (int i = 0; i < 16; i++) { Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250)); } //Alloys if (PHConstruct.harderBronze) Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 16), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze else Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, 24), new FluidStack(moltenCopperFluid, 24), new FluidStack(moltenTinFluid, 8)); //Bronze Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, 16), new FluidStack(moltenAluminumFluid, 24), new FluidStack(moltenCopperFluid, 8)); //Aluminum Brass Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, 16), new FluidStack(moltenCobaltFluid, 32), new FluidStack(moltenArditeFluid, 32)); //Manyullyn Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, 48), new FluidStack(moltenAluminumFluid, 80), new FluidStack(moltenIronFluid, 32), new FluidStack(moltenObsidianFluid, 32)); //Alumite //Oreberries Smeltery.addMelting(new ItemStack(oreBerries, 4, 0), Block.blockIron.blockID, 0, 100, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue / 9)); //Iron Smeltery.addMelting(new ItemStack(oreBerries, 4, 1), Block.blockGold.blockID, 0, 100, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9)); //Gold Smeltery.addMelting(new ItemStack(oreBerries, 4, 2), metalBlock.blockID, 3, 100, new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue / 9)); //Copper Smeltery.addMelting(new ItemStack(oreBerries, 4, 3), metalBlock.blockID, 5, 100, new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue / 9)); //Tin Smeltery.addMelting(new ItemStack(oreBerries, 4, 4), metalBlock.blockID, 6, 100, new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue / 9)); //Aluminum //Vanilla Armor Smeltery.addMelting(new ItemStack(Item.helmetIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.plateIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 8)); Smeltery.addMelting(new ItemStack(Item.legsIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Item.bootsIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Item.helmetGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.plateGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8)); Smeltery.addMelting(new ItemStack(Item.legsGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Item.bootsGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Item.helmetChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.plateChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.legsChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.bootsChain, 1, 0), this.metalBlock.blockID, 9, 700, new FluidStack(moltenSteelFluid, TConstruct.ingotLiquidValue)); //Vanilla tools Smeltery.addMelting(new ItemStack(Item.hoeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.swordIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.shovelIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 1)); Smeltery.addMelting(new ItemStack(Item.pickaxeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.axeIron, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.hoeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.swordGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Item.shovelGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 1)); Smeltery.addMelting(new ItemStack(Item.pickaxeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.axeGold, 1, 0), Block.blockGold.blockID, 0, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 3)); //Vanilla items Smeltery.addMelting(new ItemStack(Item.flintAndSteel, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Item.compass, 1, 0), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 4)); //Vanilla blocks Smeltery.addMelting(new ItemStack(Item.bucketEmpty), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 3)); Smeltery.addMelting(new ItemStack(Item.minecartEmpty), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 5)); Smeltery.addMelting(new ItemStack(Item.doorIron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6)); Smeltery.addMelting(new ItemStack(Block.fenceIron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6 / 16)); Smeltery.addMelting(new ItemStack(Block.pressurePlateIron), Block.blockIron.blockID, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Block.pressurePlateGold, 4), Block.blockGold.blockID, 0, 600, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(new ItemStack(Block.rail), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 6 / 16)); Smeltery.addMelting(new ItemStack(Block.railPowered), Block.blockGold.blockID, 8, 350, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.railDetector), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.railActivator), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(new ItemStack(Block.enchantmentTable), Block.obsidian.blockID, 0, 750, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 4)); Smeltery.addMelting(new ItemStack(Block.cauldron), Block.blockIron.blockID, 8, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 7)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 0), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 1), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); Smeltery.addMelting(new ItemStack(Block.anvil, 1, 2), Block.blockIron.blockID, 8, 800, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 31)); /* Detailing */ Detailing chiseling = TConstructRegistry.getChiselDetailing(); chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel); chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel); chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel); chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel); chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel); chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel); chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel); chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel); chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel); chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel); //chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel); //chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel); chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel); chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel); chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel); chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel); chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel); chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel); chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel); chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel); chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel); chiseling.addDetailing(materials, 18, multiBrick, 13, chisel); chiseling.addDetailing(multiBrick, 0, multiBrickFancy, 0, chisel); chiseling.addDetailing(multiBrick, 1, multiBrickFancy, 1, chisel); chiseling.addDetailing(multiBrick, 2, multiBrickFancy, 2, chisel); chiseling.addDetailing(multiBrick, 3, multiBrickFancy, 3, chisel); chiseling.addDetailing(multiBrick, 4, multiBrickFancy, 4, chisel); chiseling.addDetailing(multiBrick, 5, multiBrickFancy, 5, chisel); chiseling.addDetailing(multiBrick, 6, multiBrickFancy, 6, chisel); chiseling.addDetailing(multiBrick, 7, multiBrickFancy, 7, chisel); chiseling.addDetailing(multiBrick, 8, multiBrickFancy, 8, chisel); chiseling.addDetailing(multiBrick, 9, multiBrickFancy, 9, chisel); chiseling.addDetailing(multiBrick, 10, multiBrickFancy, 10, chisel); chiseling.addDetailing(multiBrick, 11, multiBrickFancy, 11, chisel); chiseling.addDetailing(multiBrick, 12, multiBrickFancy, 12, chisel); chiseling.addDetailing(multiBrick, 13, multiBrickFancy, 13, chisel); chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel); chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel); /*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/ chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel); chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel); chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel); chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel); chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel); chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 0), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockIron); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 1), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockGold); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 2), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockDiamond); GameRegistry.addRecipe(new ItemStack(toolForge, 1, 3), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', Block.blockEmerald); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 4), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockCobalt")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockArdite")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 6), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockManyullyn")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 7), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 8), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockBronze")); GameRegistry .addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 9), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockTin")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 10), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockNaturalAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 11), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockAluminumBrass")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 12), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockAlumite")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, 13), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', "blockSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser))); //Drawbridge GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 0), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Block.dispenser))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 1), "aca", "#d#", "#r#", '#', "ingotBronze", 'a', "ingotAluminumBrass", 'c', new ItemStack(largePlate, 1, 7), 'r', new ItemStack(Item.redstone), 'd', new ItemStack(Item.flintAndSteel))); //Igniter GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 1), 'r', new ItemStack( Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(redstoneMachine, 1, 2), " c ", "rdr", " a ", 'a', "ingotAluminumBrass", 'c', new ItemStack(blankPattern, 1, 2), 'r', new ItemStack( Item.redstone), 'd', new ItemStack(redstoneMachine, 1, 0))); /* Crafting */ GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.workbench); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood")); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest); if (PHConstruct.stencilTableCrafting) { GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3)); } GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood")); if (PHConstruct.stencilTableCrafting) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood")); GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern);//Vanilla books GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper); //Paper stack OreDictionary.registerOre("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1)); OreDictionary.registerOre("stoneMossy", new ItemStack(Block.cobblestoneMossy)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), "ppp", "ppp", "ppp", 'p', "stoneMossy")); //Moss ball GameRegistry.addRecipe(new ItemStack(materials, 1, 6), "ppp", "ppp", "ppp", 'p', new ItemStack(Block.stoneBrick, 1, 1)); //Moss ball GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod); //Auto-smelt GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod); //Auto-smelt GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt); //Slimy sand GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt); //Slimy sand GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel); //Grout GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 8, 1), Block.blockClay, Block.sand, Block.gravel, Block.sand, Block.gravel, Block.sand, Block.gravel, Block.sand, Block.gravel); //Grout GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15)); //Graveyard Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime //GameRegistry.addRecipe(new ItemStack(oreSlag, 1, 0), "pp", "pp", 'p', new ItemStack(materials, 1, 2)); //Seared brick block GameRegistry.addRecipe(new ItemStack(materials, 1, 25), "sss", "sns", "sss", 'n', new ItemStack(materials, 1, 24), 's', new ItemStack(Item.silk)); //Silky Cloth GameRegistry.addRecipe(new ItemStack(materials, 1, 25), "sss", "sns", "sss", 'n', new ItemStack(Item.goldNugget), 's', new ItemStack(Item.silk)); GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald)); //Silky Jewel GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, new Object[] { "www", "w w", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, new Object[] { "w w", "www", "www", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, new Object[] { "www", "w w", "w w", 'w', "logWood" })); GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, new Object[] { "w w", "w w", 'w', "logWood" })); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 12), 0.5f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f); //FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 12), 0.2f); FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f); //Metal conversion GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 12), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel GameRegistry.addRecipe(new ItemStack(Item.ingotIron), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 19)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 1, 9), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 20)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 1, 10), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 21)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 1, 12), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 22)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 1, 14), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 24)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 1, 18), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 27)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 1, 3), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 28)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 1, 4), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 29)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 1, 5), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 30)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 1, 13), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 31)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 1, 15), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 32)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 1, 16), "mmm", "mmm", "mmm", 'm', new ItemStack(materials, 1, 33)); //Steel GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel //Dyes String[] pattern = { "###", "#m#", "###" }; String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite" }; for (int i = 0; i < 16; i++) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), pattern, 'm', dyeTypes[15 - i], '#', clearGlass)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), dyeTypes[15 - i], clearGlass)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), dyeTypes[15 - i], new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), pattern, 'm', dyeTypes[15 - i], '#', glassPane)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), dyeTypes[15 - i], glassPane)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), pattern, 'm', dyeTypes[15 - i], '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), dyeTypes[15 - i], new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); } //Glass GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass }); GameRegistry.addRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', Block.glass, 'Q', Item.netherQuartz, 'W', Block.woodSingleSlab }); GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian }); //Smeltery ItemStack searedBrick = new ItemStack(materials, 1, 2); GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 0), "bbb", "bgb", "bbb", 'b', searedBrick, 'g', Block.glass); //Tank GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', Block.glass); //Glass GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', Block.glass); //Window GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 0), "bbb", "bgb", "bbb", 'b', searedBrick, 'g', clearGlass); //Tank GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', clearGlass); //Glass GameRegistry.addRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', clearGlass); //Window GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 'w', new ItemStack(stoneTorch)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(woodenRail, 4, 0), "b b", "bxb", "b b", 'b', "plankWood", 'x', "stickWood")); GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone)); GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone)); ItemStack aluBrass = new ItemStack(materials, 1, 14); GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass); ItemStack necroticBone = new ItemStack(materials, 1, 8); //Accessories GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum")); GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed)); GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), necroticBone, new ItemStack(heartCanister, 1, 0), new ItemStack(heartCanister, 1, 1)); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', new ItemStack(Item.ingotGold)); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', new ItemStack(materials, 1, 14)); //Armor GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood")); //Landmine GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); //Ultra hardcore recipes String[] surround = { "###", "#m#", "###" }; if (PHConstruct.goldAppleRecipe) { RecipeRemover.removeShapedRecipe(new ItemStack(Item.appleGold)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.goldenCarrot)); RecipeRemover.removeShapelessRecipe(new ItemStack(Item.speckledMelon)); GameRegistry.addRecipe(new ItemStack(Item.appleGold), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(Item.goldenCarrot), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.carrot)); GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3)); GameRegistry.addShapelessRecipe(new ItemStack(Item.speckledMelon), new ItemStack(Block.blockGold), new ItemStack(Item.melon)); tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8), new ItemStack(Item.appleRed), true, 50); } else { GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(Item.goldNugget), 'm', new ItemStack(Item.skull, 1, 3)); GameRegistry.addRecipe(new ItemStack(Item.appleGold), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(Item.goldenCarrot), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); GameRegistry.addRecipe(new ItemStack(goldHead), surround, '#', new ItemStack(oreBerries, 1, 1), 'm', new ItemStack(Item.appleRed)); tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue / 9 * 8), new ItemStack(Item.appleRed), true, 50); } tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1, 1), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8 * 9), new ItemStack(Item.appleRed), true, 50); //Drying rack DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0)); DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1)); DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2)); //DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3)); DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4)); DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5)); //DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather); //Slabs for (int i = 0; i < 7; i++) { GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i)); } GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11)); //Traps GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed)); GameRegistry.addRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 0)); GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood")); GameRegistry.addRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood")); //Slab crafters GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); GameRegistry.addRecipe(new ItemStack(essenceExtractor, 1, 0), " b ", "eme", "mmm", 'b', Item.book, 'e', Item.emerald, 'm', Block.whiteStone); //Slime GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood); GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0)); GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall); GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, new ItemStack(slimeGel, 1, Short.MAX_VALUE), "slimeBall")); //Slab crafters GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', new ItemStack(Block.workbench)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); } void setupToolTabs () { TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255)); TConstructRegistry.blockTab.init(new ItemStack(toolStationWood)); ItemStack tool = new ItemStack(longsword, 1, 0); NBTTagCompound compound = new NBTTagCompound(); compound.setCompoundTag("InfiTool", new NBTTagCompound()); compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2); compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0); compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10); tool.setTagCompound(compound); //TConstruct. TConstructRegistry.toolTab.init(tool); } public void addLoot () { //Item, min, max, weight ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27); tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1)); int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 }; Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead }; for (int partIter = 0; partIter < partTypes.length; partIter++) { for (int typeIter = 0; typeIter < validTypes.length; typeIter++) { tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15)); } } tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30); for (int i = 0; i < 13; i++) { tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20)); } tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40)); } public static String[] liquidNames; public void oreRegistry () { OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1)); OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2)); OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3)); OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4)); OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0)); OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1)); OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5)); OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2)); OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3)); OreDictionary.registerOre("oreNaturalAluminum", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3)); OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4)); OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5)); OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9)); OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10)); OreDictionary.registerOre("ingotNaturalAluminum", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("naturalAluminum", new ItemStack(materials, 1, 12)); OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13)); OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15)); OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16)); OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0)); OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1)); OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2)); OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3)); OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4)); OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5)); OreDictionary.registerOre("blockNaturalAluminum", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8)); OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9)); OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19)); OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20)); OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21)); OreDictionary.registerOre("nuggetNaturalAluminum", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27)); OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28)); OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29)); OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30)); OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31)); OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32)); OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33)); String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel", "blueslime" }; for (int i = 0; i < matNames.length; i++) OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i)); OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31)); String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow", "glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" }; for (int i = 0; i < 16; i++) { OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i)); } BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg()); BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow()); //Vanilla stuff OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0)); OreDictionary.registerOre("glass", new ItemStack(clearGlass)); RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder)); } public static boolean thaumcraftAvailable; public void intermodCommunication () { if (Loader.isModLoaded("Thaumcraft")) { FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13)); } if (Loader.isModLoaded("Mystcraft")) { MystImcHandler.blacklistFluids(); } if (Loader.isModLoaded("BuildCraft|Transport")) { BCImcHandler.registerFacades(); } /* FORESTRY * Edit these strings to change what items are added to the backpacks * Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on * Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder * May add more backpack items later - Spyboticsguy */ if (Loader.isModLoaded("Forestry")) { String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*"; FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems); } if (!Loader.isModLoaded("AppliedEnergistics")) { AEImcHandler.registerForSpatialIO(); } } private static boolean initRecipes; public static void modRecipes () { if (!initRecipes) { initRecipes = true; if (PHConstruct.removeVanillaToolRecipes) { RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold)); } } } public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray) { String var3 = ""; int var4 = 0; int var5 = 0; int var6 = 0; if (objArray[var4] instanceof String[]) { String[] var7 = (String[]) ((String[]) objArray[var4++]); for (int var8 = 0; var8 < var7.length; ++var8) { String var9 = var7[var8]; ++var6; var5 = var9.length(); var3 = var3 + var9; } } else { while (objArray[var4] instanceof String) { String var11 = (String) objArray[var4++]; ++var6; var5 = var11.length(); var3 = var3 + var11; } } HashMap var12; for (var12 = new HashMap(); var4 < objArray.length; var4 += 2) { Character var13 = (Character) objArray[var4]; ItemStack var14 = null; if (objArray[var4 + 1] instanceof Item) { var14 = new ItemStack((Item) objArray[var4 + 1]); } else if (objArray[var4 + 1] instanceof Block) { var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE); } else if (objArray[var4 + 1] instanceof ItemStack) { var14 = (ItemStack) objArray[var4 + 1]; } var12.put(var13, var14); } ItemStack[] var15 = new ItemStack[var5 * var6]; for (int var16 = 0; var16 < var5 * var6; ++var16) { char var10 = var3.charAt(var16); if (var12.containsKey(Character.valueOf(var10))) { var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy(); } else { var15[var16] = null; } } ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack); recipeList.add(0, var17); } public void modIntegration () { ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), ""); /* IC2 */ //ItemStack reBattery = ic2.api.item.Items.getItem("reBattery"); Object reBattery = getStaticItem("reBattery", "ic2.core.Ic2Items"); if (reBattery != null) { modE.batteries.add((ItemStack) reBattery); } //ItemStack chargedReBattery = ic2.api.item.Items.getItem("chargedReBattery"); Object chargedReBattery = getStaticItem("chargedReBattery", "ic2.core.Ic2Items"); if (chargedReBattery != null) { modE.batteries.add((ItemStack) chargedReBattery); } //ItemStack electronicCircuit = ic2.api.item.Items.getItem("electronicCircuit"); Object electronicCircuit = getStaticItem("electronicCircuit", "ic2.core.Ic2Items"); if (electronicCircuit != null) modE.circuits.add((ItemStack) electronicCircuit); if (chargedReBattery != null && electronicCircuit != null) TConstructClientRegistry.registerManualModifier("electricmod", ironpick.copy(), (ItemStack) chargedReBattery, (ItemStack) electronicCircuit); /* Thaumcraft */ Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems"); if (obj != null) { TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools."); thaumcraftAvailable = true; TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true); TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic"); PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31); for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31)); } TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f); TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f); TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F); } else { TConstruct.logger.warning("Thaumcraft not detected."); } if (Loader.isModLoaded("Natura")) { try { Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent"); TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f); } catch (Exception e) { } //No need to handle } ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting(); /* Thermal Expansion */ ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotLead"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotSilver"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotPlatinum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotInvar"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar } ores = OreDictionary.getOres("ingotElectrum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); tableCasting.addCastingRecipe(ingot, new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum } ores = OreDictionary.getOres("blockNickel"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockLead"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockSilver"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockPlatinum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockInvar"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue * 9), null, 100); } ores = OreDictionary.getOres("blockElectrum"); if (ores.size() > 0) { ItemStack ingot = ores.get(0); basinCasting.addCastingRecipe(ingot, new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue * 9), null, 100); } } public static Object getStaticItem (String name, String classPackage) { try { Class clazz = Class.forName(classPackage); Field field = clazz.getDeclaredField(name); Object ret = field.get(null); if (ret != null && (ret instanceof ItemStack || ret instanceof Item)) return ret; return null; } catch (Exception e) { TConstruct.logger.warning("Could not find " + name); return null; } } @Override public int getBurnTime (ItemStack fuel) { if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7) return 26400; return 0; } }
diff --git a/pregelix/pregelix-core/src/main/java/edu/uci/ics/pregelix/core/driver/Driver.java b/pregelix/pregelix-core/src/main/java/edu/uci/ics/pregelix/core/driver/Driver.java index f07a24684..3a4c41bf3 100644 --- a/pregelix/pregelix-core/src/main/java/edu/uci/ics/pregelix/core/driver/Driver.java +++ b/pregelix/pregelix-core/src/main/java/edu/uci/ics/pregelix/core/driver/Driver.java @@ -1,254 +1,260 @@ /* * Copyright 2009-2010 by The Regents of the University of California * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * you may obtain a copy of the License from * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.pregelix.core.driver; import java.io.File; import java.io.FilenameFilter; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import edu.uci.ics.hyracks.api.client.HyracksConnection; import edu.uci.ics.hyracks.api.client.IHyracksClientConnection; import edu.uci.ics.hyracks.api.exceptions.HyracksException; import edu.uci.ics.hyracks.api.job.JobFlag; import edu.uci.ics.hyracks.api.job.JobId; import edu.uci.ics.hyracks.api.job.JobSpecification; import edu.uci.ics.pregelix.api.job.PregelixJob; import edu.uci.ics.pregelix.core.base.IDriver; import edu.uci.ics.pregelix.core.jobgen.JobGen; import edu.uci.ics.pregelix.core.jobgen.JobGenInnerJoin; import edu.uci.ics.pregelix.core.jobgen.JobGenOuterJoin; import edu.uci.ics.pregelix.core.jobgen.JobGenOuterJoinSingleSort; import edu.uci.ics.pregelix.core.jobgen.JobGenOuterJoinSort; import edu.uci.ics.pregelix.core.jobgen.clusterconfig.ClusterConfig; import edu.uci.ics.pregelix.core.util.Utilities; import edu.uci.ics.pregelix.dataflow.util.IterationUtils; @SuppressWarnings("rawtypes") public class Driver implements IDriver { private static final Log LOG = LogFactory.getLog(Driver.class); private JobGen jobGen; private boolean profiling; private String applicationName; private IHyracksClientConnection hcc; private Class exampleClass; public Driver(Class exampleClass) { this.exampleClass = exampleClass; } @Override public void runJob(PregelixJob job, String ipAddress, int port) throws HyracksException { runJob(job, Plan.OUTER_JOIN, ipAddress, port, false); } @Override public void runJob(PregelixJob job, Plan planChoice, String ipAddress, int port, boolean profiling) throws HyracksException { applicationName = exampleClass.getSimpleName() + UUID.randomUUID(); try { /** add hadoop configurations */ URL hadoopCore = job.getClass().getClassLoader().getResource("core-site.xml"); - job.getConfiguration().addResource(hadoopCore); + if (hadoopCore != null) { + job.getConfiguration().addResource(hadoopCore); + } URL hadoopMapRed = job.getClass().getClassLoader().getResource("mapred-site.xml"); - job.getConfiguration().addResource(hadoopMapRed); + if (hadoopMapRed != null) { + job.getConfiguration().addResource(hadoopMapRed); + } URL hadoopHdfs = job.getClass().getClassLoader().getResource("hdfs-site.xml"); - job.getConfiguration().addResource(hadoopHdfs); + if (hadoopHdfs != null) { + job.getConfiguration().addResource(hadoopHdfs); + } ClusterConfig.loadClusterConfig(ipAddress, port); LOG.info("job started"); long start = System.currentTimeMillis(); long end = start; long time = 0; this.profiling = profiling; switch (planChoice) { case INNER_JOIN: jobGen = new JobGenInnerJoin(job); break; case OUTER_JOIN: jobGen = new JobGenOuterJoin(job); break; case OUTER_JOIN_SORT: jobGen = new JobGenOuterJoinSort(job); break; case OUTER_JOIN_SINGLE_SORT: jobGen = new JobGenOuterJoinSingleSort(job); break; default: jobGen = new JobGenInnerJoin(job); } if (hcc == null) hcc = new HyracksConnection(ipAddress, port); URLClassLoader classLoader = (URLClassLoader) exampleClass.getClassLoader(); List<File> jars = new ArrayList<File>(); URL[] urls = classLoader.getURLs(); for (URL url : urls) if (url.toString().endsWith(".jar")) jars.add(new File(url.getPath())); installApplication(jars); start = System.currentTimeMillis(); FileSystem dfs = FileSystem.get(job.getConfiguration()); dfs.delete(FileOutputFormat.getOutputPath(job), true); runCreate(jobGen); runDataLoad(jobGen); end = System.currentTimeMillis(); time = end - start; LOG.info("data loading finished " + time + "ms"); int i = 1; boolean terminate = false; do { start = System.currentTimeMillis(); runLoopBodyIteration(jobGen, i); end = System.currentTimeMillis(); time = end - start; LOG.info("iteration " + i + " finished " + time + "ms"); terminate = IterationUtils.readTerminationState(job.getConfiguration(), jobGen.getJobId()) || IterationUtils.readForceTerminationState(job.getConfiguration(), jobGen.getJobId()); i++; } while (!terminate); start = System.currentTimeMillis(); runHDFSWRite(jobGen); runCleanup(jobGen); destroyApplication(applicationName); end = System.currentTimeMillis(); time = end - start; LOG.info("result writing finished " + time + "ms"); LOG.info("job finished"); } catch (Exception e) { try { /** * destroy application if there is any exception */ if (hcc != null) { destroyApplication(applicationName); } } catch (Exception e2) { throw new HyracksException(e2); } throw new HyracksException(e); } } private void runCreate(JobGen jobGen) throws Exception { try { JobSpecification treeCreateSpec = jobGen.generateCreatingJob(); execute(treeCreateSpec); } catch (Exception e) { throw e; } } private void runDataLoad(JobGen jobGen) throws Exception { try { JobSpecification bulkLoadJobSpec = jobGen.generateLoadingJob(); execute(bulkLoadJobSpec); } catch (Exception e) { throw e; } } private void runLoopBodyIteration(JobGen jobGen, int iteration) throws Exception { try { JobSpecification loopBody = jobGen.generateJob(iteration); execute(loopBody); } catch (Exception e) { throw e; } } private void runHDFSWRite(JobGen jobGen) throws Exception { try { JobSpecification scanSortPrintJobSpec = jobGen.scanIndexWriteGraph(); execute(scanSortPrintJobSpec); } catch (Exception e) { throw e; } } private void runCleanup(JobGen jobGen) throws Exception { try { JobSpecification[] cleanups = jobGen.generateCleanup(); runJobArray(cleanups); } catch (Exception e) { throw e; } } private void runJobArray(JobSpecification[] jobs) throws Exception { for (JobSpecification job : jobs) { execute(job); } } private void execute(JobSpecification job) throws Exception { job.setUseConnectorPolicyForScheduling(false); JobId jobId = hcc.startJob(applicationName, job, profiling ? EnumSet.of(JobFlag.PROFILE_RUNTIME) : EnumSet.noneOf(JobFlag.class)); hcc.waitForCompletion(jobId); } public void installApplication(List<File> jars) throws Exception { Set<String> allJars = new TreeSet<String>(); for (File jar : jars) { allJars.add(jar.getAbsolutePath()); } long start = System.currentTimeMillis(); File appZip = Utilities.getHyracksArchive(applicationName, allJars); long end = System.currentTimeMillis(); LOG.info("jar packing finished " + (end - start) + "ms"); start = System.currentTimeMillis(); hcc.createApplication(applicationName, appZip); end = System.currentTimeMillis(); LOG.info("jar deployment finished " + (end - start) + "ms"); } public void destroyApplication(String appName) throws Exception { hcc.destroyApplication(appName); } } class FileFilter implements FilenameFilter { private String ext; public FileFilter(String ext) { this.ext = "." + ext; } public boolean accept(File dir, String name) { return name.endsWith(ext); } }
false
true
public void runJob(PregelixJob job, Plan planChoice, String ipAddress, int port, boolean profiling) throws HyracksException { applicationName = exampleClass.getSimpleName() + UUID.randomUUID(); try { /** add hadoop configurations */ URL hadoopCore = job.getClass().getClassLoader().getResource("core-site.xml"); job.getConfiguration().addResource(hadoopCore); URL hadoopMapRed = job.getClass().getClassLoader().getResource("mapred-site.xml"); job.getConfiguration().addResource(hadoopMapRed); URL hadoopHdfs = job.getClass().getClassLoader().getResource("hdfs-site.xml"); job.getConfiguration().addResource(hadoopHdfs); ClusterConfig.loadClusterConfig(ipAddress, port); LOG.info("job started"); long start = System.currentTimeMillis(); long end = start; long time = 0; this.profiling = profiling; switch (planChoice) { case INNER_JOIN: jobGen = new JobGenInnerJoin(job); break; case OUTER_JOIN: jobGen = new JobGenOuterJoin(job); break; case OUTER_JOIN_SORT: jobGen = new JobGenOuterJoinSort(job); break; case OUTER_JOIN_SINGLE_SORT: jobGen = new JobGenOuterJoinSingleSort(job); break; default: jobGen = new JobGenInnerJoin(job); } if (hcc == null) hcc = new HyracksConnection(ipAddress, port); URLClassLoader classLoader = (URLClassLoader) exampleClass.getClassLoader(); List<File> jars = new ArrayList<File>(); URL[] urls = classLoader.getURLs(); for (URL url : urls) if (url.toString().endsWith(".jar")) jars.add(new File(url.getPath())); installApplication(jars); start = System.currentTimeMillis(); FileSystem dfs = FileSystem.get(job.getConfiguration()); dfs.delete(FileOutputFormat.getOutputPath(job), true); runCreate(jobGen); runDataLoad(jobGen); end = System.currentTimeMillis(); time = end - start; LOG.info("data loading finished " + time + "ms"); int i = 1; boolean terminate = false; do { start = System.currentTimeMillis(); runLoopBodyIteration(jobGen, i); end = System.currentTimeMillis(); time = end - start; LOG.info("iteration " + i + " finished " + time + "ms"); terminate = IterationUtils.readTerminationState(job.getConfiguration(), jobGen.getJobId()) || IterationUtils.readForceTerminationState(job.getConfiguration(), jobGen.getJobId()); i++; } while (!terminate); start = System.currentTimeMillis(); runHDFSWRite(jobGen); runCleanup(jobGen); destroyApplication(applicationName); end = System.currentTimeMillis(); time = end - start; LOG.info("result writing finished " + time + "ms"); LOG.info("job finished"); } catch (Exception e) { try { /** * destroy application if there is any exception */ if (hcc != null) { destroyApplication(applicationName); } } catch (Exception e2) { throw new HyracksException(e2); } throw new HyracksException(e); } }
public void runJob(PregelixJob job, Plan planChoice, String ipAddress, int port, boolean profiling) throws HyracksException { applicationName = exampleClass.getSimpleName() + UUID.randomUUID(); try { /** add hadoop configurations */ URL hadoopCore = job.getClass().getClassLoader().getResource("core-site.xml"); if (hadoopCore != null) { job.getConfiguration().addResource(hadoopCore); } URL hadoopMapRed = job.getClass().getClassLoader().getResource("mapred-site.xml"); if (hadoopMapRed != null) { job.getConfiguration().addResource(hadoopMapRed); } URL hadoopHdfs = job.getClass().getClassLoader().getResource("hdfs-site.xml"); if (hadoopHdfs != null) { job.getConfiguration().addResource(hadoopHdfs); } ClusterConfig.loadClusterConfig(ipAddress, port); LOG.info("job started"); long start = System.currentTimeMillis(); long end = start; long time = 0; this.profiling = profiling; switch (planChoice) { case INNER_JOIN: jobGen = new JobGenInnerJoin(job); break; case OUTER_JOIN: jobGen = new JobGenOuterJoin(job); break; case OUTER_JOIN_SORT: jobGen = new JobGenOuterJoinSort(job); break; case OUTER_JOIN_SINGLE_SORT: jobGen = new JobGenOuterJoinSingleSort(job); break; default: jobGen = new JobGenInnerJoin(job); } if (hcc == null) hcc = new HyracksConnection(ipAddress, port); URLClassLoader classLoader = (URLClassLoader) exampleClass.getClassLoader(); List<File> jars = new ArrayList<File>(); URL[] urls = classLoader.getURLs(); for (URL url : urls) if (url.toString().endsWith(".jar")) jars.add(new File(url.getPath())); installApplication(jars); start = System.currentTimeMillis(); FileSystem dfs = FileSystem.get(job.getConfiguration()); dfs.delete(FileOutputFormat.getOutputPath(job), true); runCreate(jobGen); runDataLoad(jobGen); end = System.currentTimeMillis(); time = end - start; LOG.info("data loading finished " + time + "ms"); int i = 1; boolean terminate = false; do { start = System.currentTimeMillis(); runLoopBodyIteration(jobGen, i); end = System.currentTimeMillis(); time = end - start; LOG.info("iteration " + i + " finished " + time + "ms"); terminate = IterationUtils.readTerminationState(job.getConfiguration(), jobGen.getJobId()) || IterationUtils.readForceTerminationState(job.getConfiguration(), jobGen.getJobId()); i++; } while (!terminate); start = System.currentTimeMillis(); runHDFSWRite(jobGen); runCleanup(jobGen); destroyApplication(applicationName); end = System.currentTimeMillis(); time = end - start; LOG.info("result writing finished " + time + "ms"); LOG.info("job finished"); } catch (Exception e) { try { /** * destroy application if there is any exception */ if (hcc != null) { destroyApplication(applicationName); } } catch (Exception e2) { throw new HyracksException(e2); } throw new HyracksException(e); } }
diff --git a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyImpl.java b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyImpl.java index 2e43d65ac..a6669878b 100644 --- a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyImpl.java +++ b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyImpl.java @@ -1,733 +1,735 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.proxy; import gov.nist.javax.sip.header.Via; import java.io.IOException; import java.io.Serializable; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import javax.servlet.sip.Proxy; import javax.servlet.sip.ProxyBranch; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import javax.servlet.sip.SipURI; import javax.servlet.sip.URI; import javax.sip.SipException; import javax.sip.SipProvider; import javax.sip.header.ContactHeader; import javax.sip.header.Header; import javax.sip.header.RecordRouteHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.mobicents.servlet.sip.JainSipUtils; import org.mobicents.servlet.sip.address.SipURIImpl; import org.mobicents.servlet.sip.address.TelURLImpl; import org.mobicents.servlet.sip.core.session.MobicentsSipSession; import org.mobicents.servlet.sip.message.SipFactoryImpl; import org.mobicents.servlet.sip.message.SipServletRequestImpl; import org.mobicents.servlet.sip.message.SipServletResponseImpl; /** * @author root * */ public class ProxyImpl implements Proxy, Serializable { private static transient Logger logger = Logger.getLogger(ProxyImpl.class); private transient SipServletRequestImpl originalRequest; private transient SipServletResponseImpl bestResponse; private transient ProxyBranchImpl bestBranch; private boolean recurse = true; private int proxyTimeout; private int seqSearchTimeout; private boolean supervised = true; private boolean recordRoutingEnabled; private boolean parallel = true; private boolean addToPath; protected transient SipURI pathURI; protected transient SipURI recordRouteURI; private transient SipURI outboundInterface; private transient SipFactoryImpl sipFactoryImpl; private boolean isNoCancel; // clustering : will be recreated when loaded from the cache private transient ProxyUtils proxyUtils; private transient Map<URI, ProxyBranch> proxyBranches; private boolean started; private boolean ackReceived = false; private boolean tryingSent = false; // This branch is the final branch (set when the final response has been sent upstream by the proxy) // that will be used for proxying subsequent requests private ProxyBranchImpl finalBranchForSubsequentRequests; // Keep the URI of the previous SIP entity that sent the original request to us (either another proxy or UA) private SipURI previousNode; // The From-header of the initiator of the request. Used to determine the direction of the request. // Caller -> Callee or Caller <- Callee private String callerFromHeader; public ProxyImpl(SipServletRequestImpl request, SipFactoryImpl sipFactoryImpl) { this.originalRequest = request; this.sipFactoryImpl = sipFactoryImpl; this.proxyBranches = new LinkedHashMap<URI, ProxyBranch> (); this.proxyUtils = new ProxyUtils(sipFactoryImpl, this); this.proxyTimeout = 180; // 180 secs default this.outboundInterface = ((MobicentsSipSession)request.getSession()).getOutboundInterface(); this.callerFromHeader = request.getFrom().toString(); this.previousNode = extractPreviousNodeFromRequest(request); } /* * This method will find the address of the machine that is the previous dialog path node. * If there are proxies before the current one that are adding Record-Route we should visit them, * otherwise just send to the client directly. And we don't want to visit proxies that are not * Record-Routing, because they are not in the dialog path. */ private SipURI extractPreviousNodeFromRequest(SipServletRequestImpl request) { SipURI uri = null; try { // First check for record route RecordRouteHeader rrh = (RecordRouteHeader) request.getMessage().getHeader(RecordRouteHeader.NAME); if(rrh != null) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) rrh.getAddress().getURI(); uri = new SipURIImpl(sipUri); } else { // If no record route is found then use the last via (the originating endpoint) ListIterator<ViaHeader> viaHeaders = request.getMessage().getHeaders(ViaHeader.NAME); ViaHeader lastVia = null; while(viaHeaders.hasNext()) { lastVia = viaHeaders.next(); } String uriString = ((Via)lastVia).getSentBy().toString(); uri = sipFactoryImpl.createSipURI(null, uriString); if(lastVia.getTransport() != null) { uri.setTransportParam(lastVia.getTransport()); } else { uri.setTransportParam("udp"); } } } catch (Exception e) { // We shouldn't completely fail in this case because it is rare to visit this code logger.error("Failed parsing previous address ", e); } return uri; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#cancel() */ public void cancel() { cancelAllExcept(null, null, null, null, true); } /* * (non-Javadoc) * @see javax.servlet.sip.Proxy#cancel(java.lang.String[], int[], java.lang.String[]) */ public void cancel(String[] protocol, int[] reasonCode, String[] reasonText) { cancelAllExcept(null, protocol, reasonCode, reasonText, true); } public void cancelAllExcept(ProxyBranch except, String[] protocol, int[] reasonCode, String[] reasonText, boolean throwExceptionIfCannotCancel) { if(ackReceived) throw new IllegalStateException("There has been an ACK received on this branch. Can not cancel."); for(ProxyBranch proxyBranch : proxyBranches.values()) { if(!proxyBranch.equals(except)) { try { proxyBranch.cancel(protocol, reasonCode, reasonText); } catch (IllegalStateException e) { // TODO: Instead of catching excpetions here just determine if the branch is cancellable if(throwExceptionIfCannotCancel) throw e; } } } } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#createProxyBranches(java.util.List) */ public List<ProxyBranch> createProxyBranches(List<? extends URI> targets) { ArrayList<ProxyBranch> list = new ArrayList<ProxyBranch>(); for(URI target: targets) { if(target == null) throw new NullPointerException("URI can't be null"); if(!JainSipUtils.checkScheme(target.toString())) { throw new IllegalArgumentException("Scheme " + target.getScheme() + " is not supported"); } ProxyBranchImpl branch = new ProxyBranchImpl(target, this); branch.setRecordRoute(recordRoutingEnabled); branch.setRecurse(recurse); list.add(branch); this.proxyBranches.put(target, branch); } return list; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getAddToPath() */ public boolean getAddToPath() { return addToPath; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getOriginalRequest() */ public SipServletRequest getOriginalRequest() { return originalRequest; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getParallel() */ public boolean getParallel() { return this.parallel; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getPathURI() */ public SipURI getPathURI() { if(!this.addToPath) throw new IllegalStateException("You must setAddToPath(true) before getting URI"); return this.pathURI; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getProxyBranch(javax.servlet.sip.URI) */ public ProxyBranch getProxyBranch(URI uri) { return this.proxyBranches.get(uri); } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getProxyBranches() */ public List<ProxyBranch> getProxyBranches() { return new ArrayList<ProxyBranch>(this.proxyBranches.values()); } /** * @return the finalBranchForSubsequentRequest */ public ProxyBranchImpl getFinalBranchForSubsequentRequests() { return finalBranchForSubsequentRequests; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getProxyTimeout() */ public int getProxyTimeout() { return this.proxyTimeout; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getRecordRoute() */ public boolean getRecordRoute() { return this.recordRoutingEnabled; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getRecordRouteURI() */ public SipURI getRecordRouteURI() { if(!this.recordRoutingEnabled) throw new IllegalStateException("You must setRecordRoute(true) before getting URI"); return this.recordRouteURI; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getRecurse() */ public boolean getRecurse() { return this.recurse; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getSequentialSearchTimeout() */ public int getSequentialSearchTimeout() { return this.seqSearchTimeout; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getStateful() */ public boolean getStateful() { return true; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#getSupervised() */ public boolean getSupervised() { return this.supervised; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#proxyTo(java.util.List) */ public void proxyTo(List<? extends URI> uris) { for (URI uri : uris) { if(uri == null) throw new NullPointerException("URI can't be null"); if(!JainSipUtils.checkScheme(uri.toString())) { throw new IllegalArgumentException("Scheme " + uri.getScheme() + " is not supported"); } ProxyBranchImpl branch = new ProxyBranchImpl((SipURI) uri, this); branch.setRecordRoute(recordRoutingEnabled); branch.setRecurse(recurse); this.proxyBranches.put(uri, branch); } startProxy(); } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#proxyTo(javax.servlet.sip.URI) */ public void proxyTo(URI uri) { if(uri == null) throw new NullPointerException("URI can't be null"); if(!JainSipUtils.checkScheme(uri.toString())) { throw new IllegalArgumentException("Scheme " + uri.getScheme() + " is not supported"); } ProxyBranchImpl branch = new ProxyBranchImpl(uri, this); branch.setRecordRoute(recordRoutingEnabled); branch.setRecurse(recurse); this.proxyBranches.put(uri, branch); startProxy(); } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#setAddToPath(boolean) */ public void setAddToPath(boolean p) { if(started) { throw new IllegalStateException("Cannot set a record route on an already started proxy"); } if(this.pathURI == null) { this.pathURI = new SipURIImpl ( JainSipUtils.createRecordRouteURI( sipFactoryImpl.getSipNetworkInterfaceManager(), null)); } addToPath = p; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#setParallel(boolean) */ public void setParallel(boolean parallel) { this.parallel = parallel; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#setProxyTimeout(int) */ public void setProxyTimeout(int seconds) { if(seconds<=0) throw new IllegalArgumentException("Negative or zero timeout not allowed"); proxyTimeout = seconds; for(ProxyBranch proxyBranch : proxyBranches.values()) { proxyBranch.setProxyBranchTimeout(seconds); } } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#setRecordRoute(boolean) */ public void setRecordRoute(boolean rr) { if(started) { throw new IllegalStateException("Cannot set a record route on an already started proxy"); } if(rr) { this.recordRouteURI = new SipURIImpl ( JainSipUtils.createRecordRouteURI( sipFactoryImpl.getSipNetworkInterfaceManager(), null)); if(logger.isDebugEnabled()) { logger.debug("Record routing enabled for proxy, Record Route used will be : " + recordRouteURI.toString()); } } this.recordRoutingEnabled = rr; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#setRecurse(boolean) */ public void setRecurse(boolean recurse) { this.recurse = recurse; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#setSequentialSearchTimeout(int) */ public void setSequentialSearchTimeout(int seconds) { seqSearchTimeout = seconds; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#setStateful(boolean) */ public void setStateful(boolean stateful) { //NOTHING } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#setSupervised(boolean) */ public void setSupervised(boolean supervised) { this.supervised = supervised; } /* (non-Javadoc) * @see javax.servlet.sip.Proxy#startProxy() */ public void startProxy() { if(this.ackReceived) throw new IllegalStateException("Can't start. ACK has been received."); if(!this.originalRequest.isInitial()) throw new IllegalStateException("Applications should not attepmt to " + "proxy subsequent requests. Proxying the initial request is " + "sufficient to carry all subsequent requests through the same" + " path."); // Only send TRYING when the request is INVITE, needed by testProxyGen2xx form TCK (it sends MESSAGE) if(this.originalRequest.getMethod().equals(Request.INVITE) && !tryingSent) { // Send provisional TRYING. Chapter 10.2 // We must send only one TRYING no matter how many branches we spawn later. // This is needed for tests like testProxyBranchRecurse tryingSent = true; logger.info("Sending 100 Trying to the source"); SipServletResponse trying = originalRequest.createResponse(100); try { trying.send(); } catch (IOException e) { logger.error("Cannot send the 100 Trying",e); } } started = true; if(this.parallel) { for (ProxyBranch pb : this.proxyBranches.values()) { if(!((ProxyBranchImpl)pb).isStarted()) ((ProxyBranchImpl)pb).start(); } } else { startNextUntriedBranch(); } } public SipURI getOutboundInterface() { return outboundInterface; } public void onFinalResponse(ProxyBranchImpl branch) { //Get the final response SipServletResponseImpl response = (SipServletResponseImpl) branch.getResponse(); // Cancel all others if 2xx or 6xx 10.2.4 and it's not a retransmission if(!isNoCancel && response.getTransaction() != null) { if(this.getParallel()) { if( (response.getStatus() >= 200 && response.getStatus() < 300) || (response.getStatus() >= 600 && response.getStatus() < 700) ) { cancelAllExcept(branch, null, null, null, false); } - } else { - if( (response.getStatus() >= 200 && response.getStatus() < 300) ) { - cancelAllExcept(branch, null, null, null, false); - } } } // Recurse if allowed if(response.getStatus() >= 300 && response.getStatus() < 400 && getRecurse()) { // We may want to store these for "moved permanently" and others ListIterator<Header> headers = response.getMessage().getHeaders(ContactHeader.NAME); while(headers.hasNext()) { ContactHeader contactHeader = (ContactHeader) headers.next(); javax.sip.address.URI addressURI = contactHeader.getAddress().getURI(); URI contactURI = null; if (addressURI instanceof javax.sip.address.SipURI) { contactURI = new SipURIImpl( (javax.sip.address.SipURI) addressURI); } else if (addressURI instanceof javax.sip.address.TelURL) { contactURI = new TelURLImpl( (javax.sip.address.TelURL) addressURI); } ProxyBranchImpl recurseBranch = new ProxyBranchImpl(contactURI, this); recurseBranch.setRecordRoute(recordRoutingEnabled); recurseBranch.setRecurse(recurse); this.proxyBranches.put(contactURI, recurseBranch); branch.addRecursedBranch(branch); if(parallel) recurseBranch.start(); // if not parallel, just adding it to the list is enough } } // Sort best do far if(bestResponse == null || bestResponse.getStatus() > response.getStatus()) { //Assume 600 and 400 are equally bad, the better one is the one that came first (TCK doBranchBranchTest) if(bestResponse != null) { if(response.getStatus()<400) { bestResponse = response; bestBranch = branch; } } else { bestResponse = response; bestBranch = branch; } } // Check if we are waiting for more response - if(allResponsesHaveArrived()) { + if(parallel && allResponsesHaveArrived()) { finalBranchForSubsequentRequests = bestBranch; sendFinalResponse(bestResponse, bestBranch); - } else if(!parallel) { - startNextUntriedBranch(); + } + if(!parallel) { + if(bestResponse.getStatus()>=200 && bestResponse.getStatus()<300) { + finalBranchForSubsequentRequests = bestBranch; + sendFinalResponse(bestResponse, bestBranch); + } else { + startNextUntriedBranch(); + } } } public void onBranchTimeOut(ProxyBranchImpl branch) { if(this.bestBranch == null) this.bestBranch = branch; if(allResponsesHaveArrived()) { sendFinalResponse(bestResponse, bestBranch); } else { if(!parallel) { branch.cancel(); startNextUntriedBranch(); } } } // In sequential proxying get some untried branch and start it, then wait for response and repeat public void startNextUntriedBranch() { if(this.parallel) throw new IllegalStateException("This method is only for sequantial proxying"); for(ProxyBranch pb: this.proxyBranches.values()) { ProxyBranchImpl pbi = (ProxyBranchImpl) pb; if(!pbi.isStarted()) { pbi.start(); return; } } } public boolean allResponsesHaveArrived() { for(ProxyBranch pb: this.proxyBranches.values()) { ProxyBranchImpl pbi = (ProxyBranchImpl) pb; SipServletResponse response = pb.getResponse(); // The unstarted branches still haven't got a chance to get response if(!pbi.isStarted()) { return false; } if(pbi.isStarted() && !pbi.isTimedOut() && !pbi.isCanceled()) { if(response == null || // if there is no response yet response.getStatus() < Response.OK) { // or if the response if not final return false; // then we should wait more } } } return true; } public void sendFinalResponse(SipServletResponseImpl response, ProxyBranchImpl proxyBranch) { // If we didn't get any response and only a timeout just return a timeout if(proxyBranch.isTimedOut()) { try { originalRequest.createResponse(Response.REQUEST_TIMEOUT).send(); return; } catch (IOException e) { throw new IllegalStateException("Failed to send a timeout response", e); } } //Otherwise proceed with proxying the response SipServletResponseImpl proxiedResponse = getProxyUtils().createProxiedResponse(response, proxyBranch); if(proxiedResponse == null) { return; // this response was addressed to this proxy } if(proxiedResponse.getTransaction() != null) { // non retransmission case try { proxiedResponse.send(); proxyBranches = new LinkedHashMap<URI, ProxyBranch> (); originalRequest = null; bestBranch = null; bestResponse = null; } catch (Exception e) { logger.error("A problem occured while proxying the final response", e); } } else { // retransmission case, RFC3261 specifies that the retrans should be proxied statelessly String transport = JainSipUtils.findTransport(proxiedResponse.getMessage()); SipProvider sipProvider = getSipFactoryImpl().getSipNetworkInterfaceManager().findMatchingListeningPoint( transport, false).getSipProvider(); try { sipProvider.sendResponse((Response)proxiedResponse.getMessage()); } catch (SipException e) { logger.error("A problem occured while proxying the final response retransmission", e); } } } ProxyUtils getProxyUtils() { if(proxyUtils == null) { proxyUtils = new ProxyUtils(sipFactoryImpl, this); } return proxyUtils; } /** * @return the bestResponse */ public SipServletResponseImpl getBestResponse() { return bestResponse; } public void setOriginalRequest(SipServletRequestImpl originalRequest) { this.originalRequest = originalRequest; } /** * {@inheritDoc} */ public boolean getNoCancel() { return isNoCancel; } /** * {@inheritDoc} */ public void setNoCancel(boolean isNoCancel) { this.isNoCancel = isNoCancel; } /** * @return the sipFactoryImpl */ public SipFactoryImpl getSipFactoryImpl() { return sipFactoryImpl; } /** * @param sipFactoryImpl the sipFactoryImpl to set */ public void setSipFactoryImpl(SipFactoryImpl sipFactoryImpl) { this.sipFactoryImpl = sipFactoryImpl; } /** * {@inheritDoc} */ public void setOutboundInterface(InetAddress inetAddress) { String address = inetAddress.getHostAddress(); List<SipURI> list = this.sipFactoryImpl.getSipNetworkInterfaceManager().getOutboundInterfaces(); SipURI networkInterface = null; for(SipURI networkInterfaceURI:list) { if(networkInterfaceURI.toString().contains(address)) { networkInterface = networkInterfaceURI; } } if(networkInterface == null) throw new IllegalArgumentException("Network interface for " + inetAddress.getHostAddress() + " not found"); outboundInterface = networkInterface; } /** * {@inheritDoc} */ public void setOutboundInterface(InetSocketAddress inetSocketAddress) { String address = inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort(); List<SipURI> list = this.sipFactoryImpl.getSipNetworkInterfaceManager().getOutboundInterfaces(); SipURI networkInterface = null; for(SipURI networkInterfaceURI:list) { if(networkInterfaceURI.toString().contains(address)) { networkInterface = networkInterfaceURI; } } if(networkInterface == null) throw new IllegalArgumentException("Network interface for " + address + " not found"); outboundInterface = networkInterface; } public void setAckReceived(boolean received) { this.ackReceived = received; } public boolean getAckReceived() { return this.ackReceived; } public SipURI getPreviousNode() { return previousNode; } public String getCallerFromHeader() { return callerFromHeader; } public void setCallerFromHeader(String initiatorFromHeader) { this.callerFromHeader = initiatorFromHeader; } }
false
true
public void onFinalResponse(ProxyBranchImpl branch) { //Get the final response SipServletResponseImpl response = (SipServletResponseImpl) branch.getResponse(); // Cancel all others if 2xx or 6xx 10.2.4 and it's not a retransmission if(!isNoCancel && response.getTransaction() != null) { if(this.getParallel()) { if( (response.getStatus() >= 200 && response.getStatus() < 300) || (response.getStatus() >= 600 && response.getStatus() < 700) ) { cancelAllExcept(branch, null, null, null, false); } } else { if( (response.getStatus() >= 200 && response.getStatus() < 300) ) { cancelAllExcept(branch, null, null, null, false); } } } // Recurse if allowed if(response.getStatus() >= 300 && response.getStatus() < 400 && getRecurse()) { // We may want to store these for "moved permanently" and others ListIterator<Header> headers = response.getMessage().getHeaders(ContactHeader.NAME); while(headers.hasNext()) { ContactHeader contactHeader = (ContactHeader) headers.next(); javax.sip.address.URI addressURI = contactHeader.getAddress().getURI(); URI contactURI = null; if (addressURI instanceof javax.sip.address.SipURI) { contactURI = new SipURIImpl( (javax.sip.address.SipURI) addressURI); } else if (addressURI instanceof javax.sip.address.TelURL) { contactURI = new TelURLImpl( (javax.sip.address.TelURL) addressURI); } ProxyBranchImpl recurseBranch = new ProxyBranchImpl(contactURI, this); recurseBranch.setRecordRoute(recordRoutingEnabled); recurseBranch.setRecurse(recurse); this.proxyBranches.put(contactURI, recurseBranch); branch.addRecursedBranch(branch); if(parallel) recurseBranch.start(); // if not parallel, just adding it to the list is enough } } // Sort best do far if(bestResponse == null || bestResponse.getStatus() > response.getStatus()) { //Assume 600 and 400 are equally bad, the better one is the one that came first (TCK doBranchBranchTest) if(bestResponse != null) { if(response.getStatus()<400) { bestResponse = response; bestBranch = branch; } } else { bestResponse = response; bestBranch = branch; } } // Check if we are waiting for more response if(allResponsesHaveArrived()) { finalBranchForSubsequentRequests = bestBranch; sendFinalResponse(bestResponse, bestBranch); } else if(!parallel) { startNextUntriedBranch(); } }
public void onFinalResponse(ProxyBranchImpl branch) { //Get the final response SipServletResponseImpl response = (SipServletResponseImpl) branch.getResponse(); // Cancel all others if 2xx or 6xx 10.2.4 and it's not a retransmission if(!isNoCancel && response.getTransaction() != null) { if(this.getParallel()) { if( (response.getStatus() >= 200 && response.getStatus() < 300) || (response.getStatus() >= 600 && response.getStatus() < 700) ) { cancelAllExcept(branch, null, null, null, false); } } } // Recurse if allowed if(response.getStatus() >= 300 && response.getStatus() < 400 && getRecurse()) { // We may want to store these for "moved permanently" and others ListIterator<Header> headers = response.getMessage().getHeaders(ContactHeader.NAME); while(headers.hasNext()) { ContactHeader contactHeader = (ContactHeader) headers.next(); javax.sip.address.URI addressURI = contactHeader.getAddress().getURI(); URI contactURI = null; if (addressURI instanceof javax.sip.address.SipURI) { contactURI = new SipURIImpl( (javax.sip.address.SipURI) addressURI); } else if (addressURI instanceof javax.sip.address.TelURL) { contactURI = new TelURLImpl( (javax.sip.address.TelURL) addressURI); } ProxyBranchImpl recurseBranch = new ProxyBranchImpl(contactURI, this); recurseBranch.setRecordRoute(recordRoutingEnabled); recurseBranch.setRecurse(recurse); this.proxyBranches.put(contactURI, recurseBranch); branch.addRecursedBranch(branch); if(parallel) recurseBranch.start(); // if not parallel, just adding it to the list is enough } } // Sort best do far if(bestResponse == null || bestResponse.getStatus() > response.getStatus()) { //Assume 600 and 400 are equally bad, the better one is the one that came first (TCK doBranchBranchTest) if(bestResponse != null) { if(response.getStatus()<400) { bestResponse = response; bestBranch = branch; } } else { bestResponse = response; bestBranch = branch; } } // Check if we are waiting for more response if(parallel && allResponsesHaveArrived()) { finalBranchForSubsequentRequests = bestBranch; sendFinalResponse(bestResponse, bestBranch); } if(!parallel) { if(bestResponse.getStatus()>=200 && bestResponse.getStatus()<300) { finalBranchForSubsequentRequests = bestBranch; sendFinalResponse(bestResponse, bestBranch); } else { startNextUntriedBranch(); } } }
diff --git a/ini/trakem2/persistence/Loader.java b/ini/trakem2/persistence/Loader.java index 7c7f44c6..94e256b9 100644 --- a/ini/trakem2/persistence/Loader.java +++ b/ini/trakem2/persistence/Loader.java @@ -1,4635 +1,4633 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt ) This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.persistence; import ini.trakem2.utils.IJError; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.VirtualStack; import ij.gui.GenericDialog; import ij.gui.Roi; import ij.gui.YesNoCancelDialog; import ij.io.DirectoryChooser; import ij.io.FileInfo; import ij.io.FileSaver; import ij.io.Opener; import ij.io.OpenDialog; import ij.io.TiffEncoder; import ij.process.ByteProcessor; import ij.process.ImageProcessor; import ij.process.StackStatistics; import ij.process.ImageStatistics; import ij.measure.Calibration; import ini.trakem2.Project; import ini.trakem2.display.AreaList; import ini.trakem2.display.DLabel; import ini.trakem2.display.Display; import ini.trakem2.display.Displayable; import ini.trakem2.display.DisplayablePanel; import ini.trakem2.display.Layer; import ini.trakem2.display.LayerSet; import ini.trakem2.display.Patch; import ini.trakem2.display.Polyline; import ini.trakem2.display.Region; import ini.trakem2.display.Selection; import ini.trakem2.display.Stack; import ini.trakem2.display.YesNoDialog; import ini.trakem2.display.ZDisplayable; import ini.trakem2.tree.*; import ini.trakem2.utils.*; import ini.trakem2.io.*; import ini.trakem2.imaging.*; import ini.trakem2.ControlWindow; import javax.swing.JPopupMenu; import javax.swing.JMenuItem; import java.awt.Color; import java.awt.Component; import java.awt.Checkbox; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.IndexColorModel; import java.awt.geom.Area; import java.awt.geom.AffineTransform; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.Map; import java.util.HashSet; import java.util.Set; import java.util.Collections; import java.util.Collection; import java.util.Iterator; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.swing.JMenu; import mpi.fruitfly.math.datastructures.FloatArray2D; import mpi.fruitfly.registration.ImageFilter; import mpi.fruitfly.general.MultiThreading; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import loci.formats.ChannelSeparator; import loci.formats.FormatException; import loci.formats.IFormatReader; /** Handle all data-related issues with a virtualization engine, including load/unload and saving, saving as and overwriting. */ abstract public class Loader { // Only one thread at a time is to use the connection and cache protected final Object db_lock = new Object(); private boolean db_busy = false; protected Opener opener = new Opener(); protected final int MAX_RETRIES = 3; /** Keep track of whether there are any unsaved changes.*/ protected boolean changes = false; final private AtomicLong nextTempId = new AtomicLong( -1 ); static public final int ERROR_PATH_NOT_FOUND = Integer.MAX_VALUE; /** Whether incremental garbage collection is enabled. */ /* static protected final boolean Xincgc = isXincgcSet(); static protected final boolean isXincgcSet() { String[] args = IJ.getInstance().getArgs(); for (int i=0; i<args.length; i++) { if ("-Xingc".equals(args[i])) return true; } return false; } */ static public final IndexColorModel GRAY_LUT = makeGrayLut(); static public final IndexColorModel makeGrayLut() { final byte[] r = new byte[256]; final byte[] g = new byte[256]; final byte[] b = new byte[256]; for (int i=0; i<256; i++) { r[i]=(byte)i; g[i]=(byte)i; b[i]=(byte)i; } return new IndexColorModel(8, 256, r, g, b); } protected final Set<Displayable> hs_unloadable = Collections.synchronizedSet(new HashSet<Displayable>()); static public final BufferedImage NOT_FOUND = new BufferedImage(10, 10, BufferedImage.TYPE_BYTE_INDEXED, Loader.GRAY_LUT); static { Graphics2D g = NOT_FOUND.createGraphics(); g.setColor(Color.white); g.drawRect(1, 1, 8, 8); g.drawLine(3, 3, 7, 7); g.drawLine(7, 3, 3, 7); } static public final BufferedImage REGENERATING = new BufferedImage(10, 10, BufferedImage.TYPE_BYTE_INDEXED, Loader.GRAY_LUT); static { Graphics2D g = REGENERATING.createGraphics(); g.setColor(Color.white); g.setFont(new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 8)); g.drawString("R", 1, 9); } /** Returns true if the awt is a signaling image like NOT_FOUND or REGENERATING. */ static public boolean isSignalImage(final Image awt) { return REGENERATING == awt || NOT_FOUND == awt; } // the cache: shared, for there is only one JVM! (we could open a second one, and store images there, and transfer them through sockets) // What I need is not provided: a LinkedHashMap with a method to do 'removeFirst' or remove(0) !!! To call my_map.entrySet().iterator() to delete the the first element of a LinkedHashMap is just too much calling for an operation that has to be blazing fast. So I create a double list setup with arrays. The variables are not static because each loader could be connected to a different database, and each database has its own set of unique ids. Memory from other loaders is free by the releaseOthers(double) method. transient protected CacheImagePlus imps = new CacheImagePlus(50); transient protected CacheImageMipMaps mawts = new CacheImageMipMaps(50); static transient protected Vector<Loader> v_loaders = null; // Vector: synchronized protected Loader() { // register if (null == v_loaders) v_loaders = new Vector<Loader>(); v_loaders.add(this); if (!ControlWindow.isGUIEnabled()) { opener.setSilentMode(true); } // debug: report cache status every ten seconds /* final Loader lo = this; new Thread() { public void run() { setPriority(Thread.NORM_PRIORITY); while (true) { try { Thread.sleep(1000); } catch (InterruptedException ie) {} synchronized(db_lock) { lock(); //if (!v_loaders.contains(lo)) { // unlock(); // break; //} // TODO BROKEN: not registered! Utils.log2("CACHE: \n\timps: " + imps.size() + "\n\tmawts: " + mawts.size()); mawts.debug(); unlock(); } } } }.start(); */ Utils.log2("MAX_MEMORY: " + max_memory); } /** When the loader has completed its initialization, it should return true on this method. */ abstract public boolean isReady(); /** To be called within a synchronized(db_lock) */ protected final void lock() { //Utils.printCaller(this, 7); while (db_busy) { try { db_lock.wait(); } catch (InterruptedException ie) {} } db_busy = true; } /** To be called within a synchronized(db_lock) */ protected final void unlock() { //Utils.printCaller(this, 7); if (db_busy) { db_busy = false; db_lock.notifyAll(); } } /** Release all memory and unregister itself. Child Loader classes should call this method in their destroy() methods. */ synchronized public void destroy() { if (null != IJ.getInstance() && IJ.getInstance().quitting()) { return; // no need to do anything else } Utils.showStatus("Releasing all memory ...", false); destroyCache(); Project p = Project.findProject(this); if (null != v_loaders) { v_loaders.remove(this); // sync issues when deleting two loaders consecutively if (0 == v_loaders.size()) v_loaders = null; } exec.shutdownNow(); guiExec.quit(); gcrunner.interrupt(); } /**Retrieve next id from a sequence for a new DBObject to be added.*/ abstract public long getNextId(); /**Retrieve next id from a sequence for a temporary Object to be added. Is negative.*/ public long getNextTempId() { return nextTempId.getAndDecrement(); } /** Ask for the user to provide a template XML file to extract a root TemplateThing. */ public TemplateThing askForXMLTemplate(Project project) { // ask for an .xml file or a .dtd file //fd.setFilenameFilter(new XMLFileFilter(XMLFileFilter.BOTH)); String user = System.getProperty("user.name"); OpenDialog od = new OpenDialog("Select XML Template", OpenDialog.getDefaultDirectory(), null); String filename = od.getFileName(); if (null == filename || filename.toLowerCase().startsWith("null")) return null; // if there is a path, read it out if possible String dir = od.getDirectory(); if (null == dir) return null; if (IJ.isWindows()) dir = dir.replace('\\', '/'); if (!dir.endsWith("/")) dir += "/"; TemplateThing[] roots; try { roots = DTDParser.extractTemplate(dir + filename); } catch (Exception e) { IJError.print(e); return null; } if (null == roots || roots.length < 1) return null; if (roots.length > 1) { Utils.showMessage("Found more than one root.\nUsing first root only."); } return roots[0]; } private int temp_snapshots_mode = 0; public void startLargeUpdate() { LayerSet ls = Project.findProject(this).getRootLayerSet(); temp_snapshots_mode = ls.getSnapshotsMode(); if (2 != temp_snapshots_mode) ls.setSnapshotsMode(2); // disable repainting snapshots } public void commitLargeUpdate() { Project.findProject(this).getRootLayerSet().setSnapshotsMode(temp_snapshots_mode); } public void rollback() { Project.findProject(this).getRootLayerSet().setSnapshotsMode(temp_snapshots_mode); } abstract public double[][][] fetchBezierArrays(long id); abstract public ArrayList fetchPipePoints(long id); abstract public ArrayList fetchBallPoints(long id); abstract public Area fetchArea(long area_list_id, long layer_id); /* GENERIC, from DBObject calls */ abstract public boolean addToDatabase(DBObject ob); abstract public boolean updateInDatabase(DBObject ob, String key); abstract public boolean updateInDatabase(DBObject ob, Set<String> keys); abstract public boolean removeFromDatabase(DBObject ob); /* Reflection would be the best way to do all above; when it's about and 'id', one only would have to check whether the field in question is a BIGINT and the object given a DBObject, and call getId(). Such an approach demands, though, perfect matching of column names with class field names. */ public void addCrossLink(long project_id, long id1, long id2) {} /** Remove a link between two objects. Returns true always in this empty method. */ public boolean removeCrossLink(long id1, long id2) { return true; } /** Add to the cache, or if already there, make it be the last (to be flushed the last). */ public void cache(final Displayable d, final ImagePlus imp) { synchronized (db_lock) { lock(); final long id = d.getId(); // each Displayable has a unique id for each database, not for different databases, that's why the cache is NOT shared. if (Patch.class == d.getClass()) { unlock(); cache((Patch)d, imp); return; } else { Utils.log("Loader.cache: don't know how to cache: " + d); } unlock(); } } public void cache(final Patch p, final ImagePlus imp) { if (null == imp || null == imp.getProcessor()) return; synchronized (db_lock) { lock(); final long id = p.getId(); final ImagePlus cached = imps.get(id); if (null == cached || cached != imp || imp.getProcessor().getPixels() != cached.getProcessor().getPixels() ) { imps.put(id, imp); } else { imps.get(id); // send to the end } unlock(); } } /** Cache any ImagePlus, as long as a unique id is assigned to it there won't be problems; you can obtain a unique id from method getNextId() .*/ public void cacheImagePlus(long id, ImagePlus imp) { synchronized (db_lock) { lock(); imps.put(id, imp); // TODO this looks totally unnecessary unlock(); } } public void decacheImagePlus(long id) { synchronized (db_lock) { lock(); ImagePlus imp = imps.remove(id); flush(imp); unlock(); } } public void decacheImagePlus(long[] id) { synchronized (db_lock) { lock(); for (int i=0; i<id.length; i++) { ImagePlus imp = imps.remove(id[i]); flush(imp); } unlock(); } } /** Retrieves a zipped ImagePlus from the given InputStream. The stream is not closed and must be closed elsewhere. No error checking is done as to whether the stream actually contains a zipped tiff file. */ protected ImagePlus unzipTiff(InputStream i_stream, String title) { ImagePlus imp; try { // Reading a zipped tiff file in the database /* // works but not faster byte[] bytes = null; // new style: RAM only ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int len; int length = 0; while (true) { len = i_stream.read(buf); if (len<0) break; length += len; out.write(buf, 0, len); } Inflater infl = new Inflater(); infl.setInput(out.toByteArray(), 0, length); int buflen = length + length; buf = new byte[buflen]; //short almost for sure int offset = 0; ArrayList al = new ArrayList(); while (true) { len = infl.inflate(buf, offset, buf.length); al.add(buf); if (0 == infl.getRemaining()) break; buf = new byte[length*2]; offset += len; } infl.end(); byte[][] b = new byte[al.size()][]; al.toArray(b); int blength = buflen * (b.length -1) + len; // the last may be shorter bytes = new byte[blength]; for (int i=0; i<b.length -1; i++) { System.arraycopy(b[i], 0, bytes, i*buflen, buflen); } System.arraycopy(b[b.length-1], 0, bytes, buflen * (b.length-1), len); */ //OLD, creates tmp file (archive style) ZipInputStream zis = new ZipInputStream(i_stream); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; //copying savagely from ImageJ's Opener.openZip() ZipEntry entry = zis.getNextEntry(); // I suspect this is needed as an iterator int len; while (true) { len = zis.read(buf); if (len<0) break; out.write(buf, 0, len); } zis.close(); byte[] bytes = out.toByteArray(); ij.IJ.redirectErrorMessages(); imp = opener.openTiff(new ByteArrayInputStream(bytes), title); //old //ij.IJ.redirectErrorMessages(); //imp = new Opener().openTiff(i_stream, title); } catch (Exception e) { IJError.print(e); return null; } return imp; } /////////////////// static protected final Runtime RUNTIME = Runtime.getRuntime(); static public final long getCurrentMemory() { // totalMemory() is the amount of current JVM heap allocation, whether it's being used or not. It may grow over time if -Xms < -Xmx return RUNTIME.totalMemory() - RUNTIME.freeMemory(); } static public final long getFreeMemory() { // max_memory changes as some is reserved by image opening calls return max_memory - getCurrentMemory(); } /** Maximum vailable memory, in bytes. */ static private final long MAX_MEMORY = RUNTIME.maxMemory() - 128000000; // 128 M always free /** Really available maximum memory, in bytes. * This value can only be edited under synchronized MAXMEMLOCK. * I could use an AtomicLong, but why the overhead? It's private to Loader. */ static private long max_memory = MAX_MEMORY; static private final Object MAXMEMLOCK = new Object(); /** Use this method to reserve a chunk of memory (With a negative value) or to return it to the pool (with a positive value.) */ static protected void alterMaxMem(final long n_bytes) { synchronized (MAXMEMLOCK) { if (max_memory + n_bytes > MAX_MEMORY) max_memory = MAX_MEMORY; // paranoid programming else max_memory += n_bytes; } } /** Measure whether there are at least 'n_bytes' free. */ static final protected boolean enoughFreeMemory(final long n_bytes) { long free = getFreeMemory(); if (free < n_bytes) { return false; } //if (Runtime.getRuntime().freeMemory() < n_bytes + MIN_FREE_BYTES) return false; return n_bytes < max_memory - getCurrentMemory(); } public final boolean releaseToFit(final int width, final int height, final int type, float factor) { long bytes = width * height; switch (type) { case ImagePlus.GRAY32: bytes *= 5; // 4 for the FloatProcessor, and 1 for the generated pixels8 to make an image if (factor < 4) factor = 4; // for Open_MRC_Leginon ... TODO this is unnecessary in all other cases break; case ImagePlus.COLOR_RGB: bytes *= 4; break; case ImagePlus.GRAY16: bytes *= 3; // 2 for the ShortProcessor, and 1 for the pixels8 break; default: // times 1 break; } return releaseToFit((long)(bytes*factor)); } /** Release enough memory so that as many bytes as passed as argument can be loaded. */ public final boolean releaseToFit(final long n_bytes) { if (n_bytes > max_memory) { Utils.log("WARNING: Can't fit " + n_bytes + " bytes in memory."); // Try anyway releaseAll(); return false; } if (enoughFreeMemory(n_bytes)) return true; boolean result = true; synchronized (db_lock) { lock(); result = releaseToFit2(n_bytes); unlock(); } return result; } // Like releaseToFit but non-locking; calls releaseToFit2 protected final boolean releaseToFit3(long n_bytes) { if (enoughFreeMemory(n_bytes)) return true; boolean result = releaseToFit2(n_bytes); return result; } // non-locking version protected final boolean releaseToFit2(long n_bytes) { //if (enoughFreeMemory(n_bytes)) return true; if (releaseMemory2(n_bytes, true) >= n_bytes) return true; // Java will free on its own if it has to // else, wait for GC int iterations = 30; while (iterations > 0) { if (0 == imps.size() && 0 == mawts.size()) { // wait for GC ... System.gc(); try { Thread.sleep(300); } catch (InterruptedException ie) {} } if (enoughFreeMemory(n_bytes)) return true; iterations--; } return true; } final private class GCRunner extends Thread { boolean run = false; GCRunner() { super("GCRunner"); setPriority(Thread.NORM_PRIORITY); setDaemon(true); start(); } final void trigger() { synchronized (this) { run = true; notify(); } } public final void run() { while (true) { synchronized (this) { try { wait(); } catch (InterruptedException ie) { return; } } worker: while (run) { synchronized (this) { run = false; } final long initial = IJ.currentMemory(); long now = initial; final int max = 7; long sleep = 50; // initial value int iterations = 0; Utils.showStatus("Clearing memory..."); do { System.gc(); Thread.yield(); // 'run' should be false. If true, re-read initial values and iterations, for a new request came in: if (run) { Utils.log2("reinit GC after iter " + (iterations + 1)); continue worker; } try { Thread.sleep(sleep); } catch (InterruptedException ie) { return; } sleep += sleep; // incremental now = IJ.currentMemory(); Utils.log2("\titer " + iterations + " initial: " + initial + " now: " + now); Utils.log2("\t mawts: " + mawts.size() + " imps: " + imps.size()); iterations++; } while (now >= initial && iterations < max); Utils.showStatus("Memory cleared."); } } } } private final GCRunner gcrunner = new GCRunner(); /** Trigger garbage collection in a separate thread. */ public final void triggerGC() { gcrunner.trigger(); } /** This method tries to cope with the lack of real time garbage collection in java (that is, lack of predictable time for memory release). */ public final int runGC() { //Utils.printCaller("runGC", 4); final long initial = IJ.currentMemory(); long now = initial; final int max = 7; long sleep = 50; // initial value int iterations = 0; Utils.showStatus("Clearing memory..."); do { //Runtime.getRuntime().runFinalization(); // enforce it System.gc(); Thread.yield(); try { Thread.sleep(sleep); } catch (InterruptedException ie) {} sleep += sleep; // incremental now = IJ.currentMemory(); Utils.log2("\titer " + iterations + " initial: " + initial + " now: " + now); Utils.log2("\t mawts: " + mawts.size() + " imps: " + imps.size()); iterations++; } while (now >= initial && iterations < max); Utils.showStatus("Memory cleared."); return iterations + 1; } static public final void runGCAll() { Loader[] lo = new Loader[v_loaders.size()]; v_loaders.toArray(lo); for (int i=0; i<lo.length; i++) { lo[i].runGC(); } } static public void printCacheStatus() { Loader[] lo = new Loader[v_loaders.size()]; v_loaders.toArray(lo); for (int i=0; i<lo.length; i++) { Utils.log2("Loader " + i + " : mawts: " + lo[i].mawts.size() + " imps: " + lo[i].imps.size()); } } /** The minimal number of memory bytes that should always be free. */ public static long MIN_FREE_BYTES = computeDesirableMinFreeBytes(); /** 100 Mb per processor, which is a bit more than 67 Mb, the size of a 32-bit 4096x4096 image. */ public static long computeDesirableMinFreeBytes() { long f = 150000000 * Runtime.getRuntime().availableProcessors(); if (f > max_memory / 2) { Utils.logAll("WARNING you are operating with low memory\n considering the number of CPU cores.\n Please restart with a higher -Xmx value."); return max_memory / 2; } return f; } /** If the number of minimally free memory bytes (100 Mb times the number of CPU cores) is too low for your (giant) images, set it to a larger value here. */ public static void setDesirableMinFreeBytes(final long n_bytes) { long f = computeDesirableMinFreeBytes(); long max = IJ.maxMemory(); if (n_bytes < f) { Utils.logAll("Refusing to use " + n_bytes + " as the desirable amount of free memory bytes,\n considering the lower limit at " + f); } else if (n_bytes > max) { Utils.logAll("Refusing to use a number of minimally free memory bytes larger than max_memory " + max); } else if (n_bytes > max / 2) { Utils.logAll("WARNING you are setting a value of minimally free memory bytes larger than half the maximum memory."); } else { f = n_bytes; } MIN_FREE_BYTES = f; Utils.logAll("Using min free bytes " + MIN_FREE_BYTES + " (max memory: " + max + ")"); } private final long measureSize(final ImagePlus imp) { if (null == imp) return 0; final long size = imp.getWidth() * imp.getHeight() * imp.getNSlices(); switch (imp.getType()) { case ImagePlus.GRAY16: return size * 2 + 100; case ImagePlus.GRAY32: case ImagePlus.COLOR_RGB: return size * 4 + 100; // some overhead, it's 16 but allowing for a lot more case ImagePlus.GRAY8: return size + 100; case ImagePlus.COLOR_256: return size + 868; // 100 + 3 * 256 (the LUT) } return 0; } /** Returns a lower-bound estimate: as if it was grayscale; plus some overhead. */ private final long measureSize(final Image img) { if (null == img) return 0; return img.getWidth(null) * img.getHeight(null) + 100; } /** Free up to MIN_FREE_BYTES. Locks on db_lock. */ public final long releaseMemory() { synchronized (db_lock) { try { lock(); return releaseMemory2(); } catch (Throwable e) { IJError.print(e); return 0; } finally { unlock(); } } } /** Free up to @param min_free_bytes. Locks on db_lock. */ public final long releaseMemory(final long min_free_bytes) { synchronized (db_lock) { try { lock(); return releaseMemory2(min_free_bytes, true); } catch (Throwable e) { IJError.print(e); return 0; } finally { unlock(); } } } /** Free up to MIN_FREE_BYTES. */ protected final long releaseMemory2() { return releaseMemory2(MIN_FREE_BYTES, true); } private final long releaseOthers(final long min_free_bytes) { if (1 == v_loaders.size()) return 0; long released = 0; for (final Loader lo : new Vector<Loader>(v_loaders)) { if (lo == this) continue; released += lo.releaseMemory2(min_free_bytes, false); // locking on the other Loader's db_lock if (released >= min_free_bytes) return released; } return released; } /** Release as much of the cache as necessary to make at least min_free_bytes free.<br /> * The very last thing to remove is the stored awt.Image objects.<br /> * Removes one ImagePlus at a time if a == 0, else up to 0 &lt; a &lt;= 1.0 .<br /> * NOT locked, however calls must take care of that.<br /> */ protected final long releaseMemory2(long min_free_bytes, final boolean release_others) { if (min_free_bytes < MIN_FREE_BYTES) min_free_bytes = MIN_FREE_BYTES; long released = 0; int BATCH_SIZE = 5 * Runtime.getRuntime().availableProcessors(); if (BATCH_SIZE < 10) BATCH_SIZE = 10; try { int iterations = 0; while (released < min_free_bytes) { if (enoughFreeMemory(min_free_bytes)) return released; iterations++; // First from other loaders, if any if (release_others) { released += releaseOthers(min_free_bytes); if (released >= min_free_bytes) return released; } // Second some ImagePlus if (0 != imps.size()) { for (int i=0; i<BATCH_SIZE; ) { ImagePlus imp = imps.removeFirst(); if (null == imp) break; // BATCH_SIZE larger than cache i += imp.getNSlices(); // a stack will contribute much more released += measureSize(imp); flush(imp); } Thread.yield(); if (released >= min_free_bytes) return released; } // Third some awts if (0 != mawts.size()) { for (int i=0; i<BATCH_SIZE; i++) { Image mawt = mawts.removeFirst(); if (null == mawt) break; // BATCH_SIZE larger than cache released += measureSize(mawt); if (null != mawt) mawt.flush(); } if (released >= min_free_bytes) return released; } // sanity check: if (0 == imps.size() && 0 == mawts.size()) { Utils.log2("Loader.releaseMemory: empty cache."); // Remove any autotraces Polyline.flushTraceCache(Project.findProject(this)); // in any case, can't release more: mawts.gc(); if (0 == clonks.incrementAndGet() % 20) { triggerGC(); } return released; } else if (iterations > 50) { triggerGC(); } } } catch (Throwable e) { IJError.print(e); } finally { // if released more than min_free_bytes but there isn't enough free memory, it's time to trigger GC: if (!enoughFreeMemory(min_free_bytes)) { triggerGC(); } } return released; } static private final AtomicLong clonks = new AtomicLong(); static public void releaseAllCaches() { for (final Loader lo : new Vector<Loader>(v_loaders)) { lo.releaseAll(); } } /** Empties the caches. */ public void releaseAll() { synchronized (db_lock) { lock(); try { for (ImagePlus imp : imps.removeAll()) { flush(imp); } mawts.removeAndFlushAll(); } catch (Exception e) { IJError.print(e); } unlock(); } } private void destroyCache() { synchronized (db_lock) { try { lock(); if (null != IJ.getInstance() && IJ.getInstance().quitting()) { return; } if (null != imps) { for (ImagePlus imp : imps.removeAll()) { flush(imp); } imps = null; } if (null != mawts) { mawts.removeAndFlushAll(); } } catch (Exception e) { unlock(); IJError.print(e); } finally { unlock(); } } } /** Removes from the cache all awt images bond to the given id. */ public void decacheAWT(final long id) { synchronized (db_lock) { lock(); mawts.removeAndFlush(id); // where are my lisp macros! Wrapping any function in a synch/lock/unlock could be done crudely with reflection, but what a pain unlock(); } } public Image getCachedAWT(final long id, final int level) { synchronized (db_lock) { try { lock(); return mawts.get(id, level); } finally { unlock(); } } } public void cacheAWT( final long id, final Image awt) { synchronized (db_lock) { lock(); if (null != awt) { mawts.put(id, awt, 0); } unlock(); } } /** Transform mag to nearest scale level that delivers an equally sized or larger image.<br /> * Requires 0 &lt; mag &lt;= 1.0<br /> * Returns -1 if the magnification is NaN or negative or zero.<br /> * As explanation:<br /> * mag = 1 / Math.pow(2, level) <br /> * so that 100% is 0, 50% is 1, 25% is 2, and so on, but represented in values between 0 and 1. */ static public final int getMipMapLevel(final double mag, final double size) { // check parameters if (mag > 1) return 0; // there is no level for mag > 1, so use mag = 1 if (mag <= 0 || Double.isNaN(mag)) { Utils.log2("ERROR: mag is " + mag); return 0; // survive } final int level = (int)(0.0001 + Math.log(1/mag) / Math.log(2)); // compensating numerical instability: 1/0.25 should be 2 eaxctly final int max_level = getHighestMipMapLevel(size); /* if (max_level > 6) { Utils.log2("ERROR max_level > 6: " + max_level + ", size: " + size); } */ return Math.min(level, max_level); /* int level = 0; double scale; static private ExecutorService exec = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors() ); while (true) { scale = 1 / Math.pow(2, level); //Utils.log2("scale, mag, level: " + scale + ", " + mag + ", " + level); if (Math.abs(scale - mag) < 0.00000001) { //if (scale == mag) { // floating-point typical behaviour break; } else if (scale < mag) { // provide the previous one level--; break; } // else, continue search level++; } return level; */ } public static final double maxDim(final Displayable d) { return Math.max(d.getWidth(), d.getHeight()); } public boolean isImagePlusCached(final Patch p) { synchronized (db_lock) { try { lock(); return null != imps.get(p.getId()); } catch (Exception e) { IJError.print(e); return false; } finally { unlock(); } } } /** Returns true if there is a cached awt image for the given mag and Patch id. */ public boolean isCached(final Patch p, final double mag) { synchronized (db_lock) { try { lock(); return mawts.contains(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); } catch (Exception e) { IJError.print(e); return false; } finally { unlock(); } } } public Image getCached(final long id, final int level) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestAbove(id, level); unlock(); } return awt; } /** Above or equal in size. */ public Image getCachedClosestAboveImage(final Patch p, final double mag) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestAbove(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); } return awt; } /** Below, not equal. */ public Image getCachedClosestBelowImage(final Patch p, final double mag) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestBelow(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); } return awt; } protected final class ImageLoadingLock extends Lock { final String key; ImageLoadingLock(final String key) { this.key = key; } } /** Table of dynamic locks, a single one per Patch if any. */ private final Hashtable<String,ImageLoadingLock> ht_plocks = new Hashtable<String,ImageLoadingLock>(); protected final ImageLoadingLock getOrMakeImageLoadingLock(final long id, final int level) { final String key = new StringBuffer().append(id).append('.').append(level).toString(); ImageLoadingLock plock = ht_plocks.get(key); if (null != plock) return plock; plock = new ImageLoadingLock(key); ht_plocks.put(key, plock); return plock; } protected final void removeImageLoadingLock(final ImageLoadingLock pl) { ht_plocks.remove(pl.key); } /** Calls fetchImage(p, mag) unless overriden. */ public Image fetchDataImage(Patch p, double mag) { return fetchImage(p, mag); } public Image fetchImage(Patch p) { return fetchImage(p, 1.0); } /** Fetch a suitable awt.Image for the given mag(nification). * If the mag is bigger than 1.0, it will return as if was 1.0. * Will return Loader.NOT_FOUND if, err, not found (probably an Exception will print along). */ public Image fetchImage(final Patch p, double mag) { if (mag > 1.0) mag = 1.0; // Don't want to create gigantic images! final int level = Loader.getMipMapLevel(mag, maxDim(p)); final int max_level = Loader.getHighestMipMapLevel(p); return fetchAWTImage(p, level > max_level ? max_level : level); } final public Image fetchAWTImage(final Patch p, int level) { // Below, the complexity of the synchronized blocks is to provide sufficient granularity. Keep in mind that only one thread at at a time can access a synchronized block for the same object (in this case, the db_lock), and thus calling lock() and unlock() is not enough. One needs to break the statement in as many synch blocks as possible for maximizing the number of threads concurrently accessing different parts of this function. // find an equal or larger existing pyramid awt final long id = p.getId(); ImageLoadingLock plock = null; synchronized (db_lock) { lock(); try { if (null == mawts) { return NOT_FOUND; // when lazy repainting after closing a project, the awts is null } if (level >= 0 && isMipMapsEnabled()) { // 1 - check if the exact level is cached final Image mawt = mawts.get(id, level); if (null != mawt) { //Utils.log2("returning cached exact mawt for level " + level); return mawt; } // releaseMemory2(); plock = getOrMakeImageLoadingLock(p.getId(), level); } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } Image mawt = null; long n_bytes = 0; // 2 - check if the exact file is present for the desired level if (level >= 0 && isMipMapsEnabled()) { synchronized (plock) { plock.lock(); synchronized (db_lock) { lock(); mawt = mawts.get(id, level); unlock(); } if (null != mawt) { plock.unlock(); return mawt; // was loaded by a different thread } // going to load: synchronized (db_lock) { lock(); n_bytes = estimateImageFileSize(p, level); alterMaxMem(-n_bytes); unlock(); } try { // Locks on db_lock to release memory when needed mawt = fetchMipMapAWT(p, level, n_bytes); } catch (Throwable t) { IJError.print(t); mawt = null; } synchronized (db_lock) { try { lock(); alterMaxMem(n_bytes); if (null != mawt) { //Utils.log2("returning exact mawt from file for level " + level); if (REGENERATING != mawt) { mawts.put(id, mawt, level); Display.repaintSnapshot(p); } return mawt; } // 3 - else, load closest level to it but still giving a larger image final int lev = getClosestMipMapLevel(p, level); // finds the file for the returned level, otherwise returns zero //Utils.log2("closest mipmap level is " + lev); if (lev >= 0) { mawt = mawts.getClosestAbove(id, lev); boolean newly_cached = false; if (null == mawt) { // reload existing scaled file mawt = fetchMipMapAWT2(p, lev, n_bytes); if (null != mawt) { mawts.put(id, mawt, lev); newly_cached = true; // means: cached was false, now it is } // else if null, the file did not exist or could not be regenerated or regeneration is off } //Utils.log2("from getClosestMipMapLevel: mawt is " + mawt); if (null != mawt) { if (newly_cached) Display.repaintSnapshot(p); //Utils.log2("returning from getClosestMipMapAWT with level " + lev); return mawt; } } else if (ERROR_PATH_NOT_FOUND == lev) { mawt = NOT_FOUND; } } catch (Exception e) { IJError.print(e); } finally { removeImageLoadingLock(plock); unlock(); plock.unlock(); } } } } // level is zero or nonsensically lower than zero, or was not found //Utils.log2("not found!"); synchronized (db_lock) { try { lock(); // 4 - check if any suitable level is cached (whithout mipmaps, it may be the large image) mawt = mawts.getClosestAbove(id, level); if (null != mawt) { //Utils.log2("returning from getClosest with level " + level); return mawt; } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } // 5 - else, fetch the (perhaps) transformed ImageProcessor and make an image from it of the proper size and quality if (hs_unloadable.contains(p)) return NOT_FOUND; synchronized (db_lock) { try { lock(); releaseMemory2(); plock = getOrMakeImageLoadingLock(p.getId(), level); } catch (Exception e) { return NOT_FOUND; } finally { unlock(); } } synchronized (plock) { try { plock.lock(); // Check if a previous call made it while waiting: mawt = mawts.getClosestAbove(id, level); if (null != mawt) { synchronized (db_lock) { lock(); removeImageLoadingLock(plock); unlock(); } return mawt; } // Else, create the mawt: plock.unlock(); Patch.PatchImage pai = p.createTransformedImage(); plock.lock(); if (null != pai && null != pai.target) { final ImageProcessor ip = pai.target; ip.setMinAndMax(p.getMin(), p.getMax()); ByteProcessor alpha_mask = pai.mask; // can be null; final ByteProcessor outside_mask = pai.outside; // can be null if (null == alpha_mask) { alpha_mask = outside_mask; } pai = null; if (null != alpha_mask) { mawt = createARGBImage(ip.getWidth(), ip.getHeight(), embedAlpha((int[])ip.convertToRGB().getPixels(), (byte[])alpha_mask.getPixels(), null == outside_mask ? null : (byte[])outside_mask.getPixels())); } else { mawt = ip.createImage(); } } } catch (Exception e) { Utils.log2("Could not create an image for Patch " + p); mawt = null; } finally { plock.unlock(); } } synchronized (db_lock) { try { lock(); if (null != mawt) { mawts.put(id, mawt, level); Display.repaintSnapshot(p); //Utils.log2("Created mawt from scratch."); return mawt; } } catch (Exception e) { IJError.print(e); } finally { removeImageLoadingLock(plock); unlock(); } } return NOT_FOUND; } /** Returns null.*/ public ByteProcessor fetchImageMask(final Patch p) { return null; } public String getAlphaPath(final Patch p) { return null; } /** Does nothing unless overriden. */ public void storeAlphaMask(final Patch p, final ByteProcessor fp) {} /** Does nothing unless overriden. */ public boolean removeAlphaMask(final Patch p) { return false; } /** Must be called within synchronized db_lock. */ private final Image fetchMipMapAWT2(final Patch p, final int level, final long n_bytes) { final long size = estimateImageFileSize(p, level); alterMaxMem(-size); unlock(); Image mawt = null; try { mawt = fetchMipMapAWT(p, level, n_bytes); // locks on db_lock } catch (Throwable e) { IJError.print(e); } lock(); alterMaxMem(size); return mawt; } /** Simply reads from the cache, does no reloading at all. If the ImagePlus is not found in the cache, it returns null and the burden is on the calling method to do reconstruct it if necessary. This is intended for the LayerStack. */ public ImagePlus getCachedImagePlus(final long id) { synchronized(db_lock) { ImagePlus imp = null; lock(); imp = imps.get(id); unlock(); return imp; } } abstract public ImagePlus fetchImagePlus(Patch p); /** Returns null unless overriden. */ public ImageProcessor fetchImageProcessor(Patch p) { return null; } public ImagePlus fetchImagePlus( Stack p ) { return null; } abstract public Object[] fetchLabel(DLabel label); /**Returns the ImagePlus as a zipped InputStream of bytes; the InputStream has to be closed by whoever is calling this method. */ protected InputStream createZippedStream(ImagePlus imp) throws Exception { FileInfo fi = imp.getFileInfo(); Object info = imp.getProperty("Info"); if (info != null && (info instanceof String)) { fi.info = (String)info; } if (null == fi.description) { fi.description = new ij.io.FileSaver(imp).getDescriptionString(); } //see whether this is a stack or not /* //never the case in my program if (fi.nImages > 1) { IJ.log("saving a stack!"); //virtual stacks would be supported? I don't think so because the FileSaver.saveAsTiffStack(String path) doesn't. if (fi.pixels == null && imp.getStack().isVirtual()) { //don't save it! IJ.showMessage("Virtual stacks not supported."); return false; } //setup stack things as in FileSaver.saveAsTiffStack(String path) fi.sliceLabels = imp.getStack().getSliceLabels(); } */ TiffEncoder te = new TiffEncoder(fi); ByteArrayInputStream i_stream = null; ByteArrayOutputStream o_bytes = new ByteArrayOutputStream(); DataOutputStream o_stream = null; try { /* // works, but not significantly faster and breaks older databases (can't read zipped images properly) byte[] bytes = null; // compress in RAM o_stream = new DataOutputStream(new BufferedOutputStream(o_bytes)); te.write(o_stream); o_stream.flush(); o_stream.close(); Deflater defl = new Deflater(); byte[] unzipped_bytes = o_bytes.toByteArray(); defl.setInput(unzipped_bytes); defl.finish(); bytes = new byte[unzipped_bytes.length]; // this length *should* be enough int length = defl.deflate(bytes); if (length < unzipped_bytes.length) { byte[] bytes2 = new byte[length]; System.arraycopy(bytes, 0, bytes2, 0, length); bytes = bytes2; } */ // old, creates temp file o_bytes = new ByteArrayOutputStream(); // clearing ZipOutputStream zos = new ZipOutputStream(o_bytes); o_stream = new DataOutputStream(new BufferedOutputStream(zos)); zos.putNextEntry(new ZipEntry(imp.getTitle())); te.write(o_stream); o_stream.flush(); //this was missing and was 1) truncating the Path images and 2) preventing the snapshots (which are very small) to be saved at all!! o_stream.close(); // this should ensure the flush above anyway. This can work because closing a ByteArrayOutputStream has no effect. byte[] bytes = o_bytes.toByteArray(); //Utils.showStatus("Zipping " + bytes.length + " bytes...", false); //Utils.debug("Zipped ImagePlus byte array size = " + bytes.length); i_stream = new ByteArrayInputStream(bytes); } catch (Exception e) { Utils.log("Loader: ImagePlus NOT zipped! Problems at writing the ImagePlus using the TiffEncoder.write(dos) :\n " + e); //attempt to cleanup: try { if (null != o_stream) o_stream.close(); if (null != i_stream) i_stream.close(); } catch (IOException ioe) { Utils.log("Loader: Attempt to clean up streams failed."); IJError.print(ioe); } return null; } return i_stream; } /** A dialog to open a stack, making sure there is enough memory for it. */ synchronized public ImagePlus openStack() { final OpenDialog od = new OpenDialog("Select stack", OpenDialog.getDefaultDirectory(), null); String file_name = od.getFileName(); if (null == file_name || file_name.toLowerCase().startsWith("null")) return null; String dir = od.getDirectory().replace('\\', '/'); if (!dir.endsWith("/")) dir += "/"; File f = new File(dir + file_name); if (!f.exists()) { Utils.showMessage("File " + dir + file_name + " does not exist."); return null; } // avoid opening trakem2 projects if (file_name.toLowerCase().endsWith(".xml")) { Utils.showMessage("Cannot import " + file_name + " as a stack."); return null; } // estimate file size: assumes an uncompressed tif, or a zipped tif with an average compression ratio of 2.5 long size = f.length() / 1024; // in megabytes if (file_name.length() -4 == file_name.toLowerCase().lastIndexOf(".zip")) { size = (long)(size * 2.5); // 2.5 is a reasonable compression ratio estimate based on my experience } int max_iterations = 15; while (enoughFreeMemory(size)) { if (0 == max_iterations) { // leave it to the Opener class to throw an OutOfMemoryError if so. break; } max_iterations--; releaseMemory(); } ImagePlus imp_stack = null; try { IJ.redirectErrorMessages(); imp_stack = openImagePlus(f.getCanonicalPath()); } catch (Exception e) { IJError.print(e); return null; } if (null == imp_stack) { Utils.showMessage("Can't open the stack."); return null; } else if (1 == imp_stack.getStackSize()) { Utils.showMessage("Not a stack!"); return null; } return imp_stack; // the open... command } public Bureaucrat importSequenceAsGrid(Layer layer) { return importSequenceAsGrid(layer, null); } public Bureaucrat importSequenceAsGrid(final Layer layer, String dir) { return importSequenceAsGrid(layer, dir, null); } /** Open one of the images to find out the dimensions, and get a good guess at what is the desirable scale for doing phase- and cross-correlations with about 512x512 images. */ private int getCCScaleGuess(final File images_dir, final String[] all_images) { try { if (null != all_images && all_images.length > 0) { Utils.showStatus("Opening one image ... ", false); String sdir = images_dir.getAbsolutePath().replace('\\', '/'); if (!sdir.endsWith("/")) sdir += "/"; IJ.redirectErrorMessages(); ImagePlus imp = openImagePlus(sdir + all_images[0]); if (null != imp) { int w = imp.getWidth(); int h = imp.getHeight(); flush(imp); imp = null; int cc_scale = (int)((512.0 / (w > h ? w : h)) * 100); if (cc_scale > 100) return 100; return cc_scale; } } } catch (Exception e) { Utils.log2("Could not get an estimate for the optimal scale."); } return 25; } /** Import a sequence of images as a grid, and put them in the layer. If the directory (@param dir) is null, it'll be asked for. The image_file_names can be null, and in any case it's only the names, not the paths. */ public Bureaucrat importSequenceAsGrid(final Layer first_layer, String dir, final String[] image_file_names) { String[] all_images = null; String file = null; // first file File images_dir = null; if (null != dir && null != image_file_names) { all_images = image_file_names; images_dir = new File(dir); } else if (null == dir) { String[] dn = Utils.selectFile("Select first image"); if (null == dn) return null; dir = dn[0]; file = dn[1]; images_dir = new File(dir); } else { images_dir = new File(dir); if (!(images_dir.exists() && images_dir.isDirectory())) { Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir); return null; } } if (null == image_file_names) all_images = images_dir.list(new ini.trakem2.io.ImageFileFilter("", null)); if (null == file && all_images.length > 0) { file = all_images[0]; } int n_max = all_images.length; // reasonable estimate int side = (int)Math.floor(Math.sqrt(n_max)); GenericDialog gd = new GenericDialog("Conventions"); gd.addStringField("file_name_matches: ", ""); gd.addNumericField("first_image: ", 1, 0); gd.addNumericField("last_image: ", n_max, 0); gd.addCheckbox("Reverse list order", false); gd.addNumericField("number_of_rows: ", side, 0); gd.addNumericField("number_of_columns: ", side, 0); gd.addNumericField("number_of_slices: ", 1, 0); gd.addMessage("The top left coordinate for the imported grid:"); gd.addNumericField("base_x: ", 0, 3); gd.addNumericField("base_y: ", 0, 3); gd.addMessage("Amount of image overlap, in pixels"); gd.addNumericField("bottom-top overlap: ", 0, 2); //as asked by Joachim Walter gd.addNumericField("left-right overlap: ", 0, 2); gd.addCheckbox("link images", false); gd.addCheckbox("montage", true); gd.addChoice("stitching_rule: ", StitchingTEM.rules, StitchingTEM.rules[0]); gd.addCheckbox("homogenize_contrast", false); final Component[] c = { //(Component)gd.getSliders().get(gd.getSliders().size()-2), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-2), //(Component)gd.getSliders().get(gd.getSliders().size()-1), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-1), (Component)gd.getChoices().get(gd.getChoices().size()-1) }; - // enable the checkbox to control the slider and its associated numeric field: - Utils.addEnablerListener((Checkbox)gd.getCheckboxes().get(gd.getCheckboxes().size()-2), c, null); //gd.addCheckbox("Apply non-linear deformation", false); gd.showDialog(); if (gd.wasCanceled()) return null; final String regex = gd.getNextString(); Utils.log2(new StringBuffer("using regex: ").append(regex).toString()); // avoid destroying backslashes int first = (int)gd.getNextNumber(); if (first < 1) first = 1; int last = (int)gd.getNextNumber(); if (last < 1) last = 1; if (last < first) { Utils.showMessage("Last is smaller that first!"); return null; } final boolean reverse_order = gd.getNextBoolean(); final int n_rows = (int)gd.getNextNumber(); final int n_cols = (int)gd.getNextNumber(); final int n_slices = (int)gd.getNextNumber(); final double bx = gd.getNextNumber(); final double by = gd.getNextNumber(); double bt_overlap = gd.getNextNumber(); double lr_overlap = gd.getNextNumber(); final boolean link_images = gd.getNextBoolean(); final boolean stitch_tiles = gd.getNextBoolean(); final boolean homogenize_contrast = gd.getNextBoolean(); final int stitching_rule = gd.getNextChoiceIndex(); //boolean apply_non_linear_def = gd.getNextBoolean(); // Ensure tiles overlap if using SIFT if (StitchingTEM.FREE_RULE == stitching_rule) { if (bt_overlap <= 0) bt_overlap = 1; if (lr_overlap <= 0) lr_overlap = 1; } String[] file_names = null; if (null == image_file_names) { file_names = images_dir.list(new ini.trakem2.io.ImageFileFilter(regex, null)); Arrays.sort(file_names); //assumes 001, 002, 003 ... that style, since it does binary sorting of strings if (reverse_order) { // flip in place for (int i=file_names.length/2; i>-1; i--) { String tmp = file_names[i]; int j = file_names.length -1 -i; file_names[i] = file_names[j]; file_names[j] = tmp; } } } else { file_names = all_images; } if (0 == file_names.length) { Utils.showMessage("No images found."); return null; } // check if the selected image is in the list. Otherwise, shift selected image to the first of the included ones. boolean found_first = false; for (int i=0; i<file_names.length; i++) { if (file.equals(file_names[i])) { found_first = true; break; } } if (!found_first) { file = file_names[0]; Utils.log("Using " + file + " as the reference image for size."); } // crop list if (last > file_names.length) last = file_names.length -1; if (first < 1) first = 1; if (1 != first || last != file_names.length) { Utils.log("Cropping list."); String[] file_names2 = new String[last - first + 1]; System.arraycopy(file_names, first -1, file_names2, 0, file_names2.length); file_names = file_names2; } // should be multiple of rows and cols and slices if (file_names.length != n_rows * n_cols * n_slices) { Utils.log("ERROR: rows * cols * slices does not match with the number of selected images."); Utils.log("n_images:" + file_names.length + " rows,cols,slices : " + n_rows + "," + n_cols + "," + n_slices + " total=" + n_rows*n_cols*n_slices); return null; } // I luv java final String[] file_names_ = file_names; final String dir_ = dir; final String file_ = file; // the first file final double bt_overlap_ = bt_overlap; final double lr_overlap_ = lr_overlap; return Bureaucrat.createAndStart(new Worker.Task("Importing", true) { public void exec() { StitchingTEM.PhaseCorrelationParam pc_param = null; // Slice up list: for (int sl=0; sl<n_slices; sl++) { if (Thread.currentThread().isInterrupted() || hasQuitted()) return; Utils.log("Importing " + (sl+1) + "/" + n_slices); int start = sl * n_rows * n_cols; ArrayList cols = new ArrayList(); for (int i=0; i<n_cols; i++) { String[] col = new String[n_rows]; for (int j=0; j<n_rows; j++) { col[j] = file_names_[start + j*n_cols + i]; } cols.add(col); } Layer layer = 0 == sl ? first_layer : first_layer.getParent().getLayer(first_layer.getZ() + first_layer.getThickness() * sl, first_layer.getThickness(), true); if (stitch_tiles && null == pc_param) { pc_param = new StitchingTEM.PhaseCorrelationParam(); pc_param.setup(layer); } insertGrid(layer, dir_, file_, n_rows*n_cols, cols, bx, by, bt_overlap_, lr_overlap_, link_images, stitch_tiles, homogenize_contrast, stitching_rule, pc_param, this); } } }, first_layer.getProject()); } public Bureaucrat importGrid(Layer layer) { return importGrid(layer, null); } /** Import a grid of images and put them in the layer. If the directory (@param dir) is null, it'll be asked for. */ public Bureaucrat importGrid(final Layer layer, String dir) { try { String file = null; if (null == dir) { String[] dn = Utils.selectFile("Select first image"); if (null == dn) return null; dir = dn[0]; file = dn[1]; } String convention = "cdd"; // char digit digit boolean chars_are_columns = true; // examine file name /* if (file.matches("\\A[a-zA-Z]\\d\\d.*")) { // one letter, 2 numbers //means: // \A - beggining of input // [a-zA-Z] - any letter upper or lower case // \d\d - two consecutive digits // .* - any row of chars ini_grid_convention = true; } */ // ask for chars->rows, numbers->columns or viceversa GenericDialog gd = new GenericDialog("Conventions"); gd.addStringField("file_name_contains:", ""); gd.addNumericField("base_x: ", 0, 3); gd.addNumericField("base_y: ", 0, 3); gd.addMessage("Use: x(any), c(haracter), d(igit)"); gd.addStringField("convention: ", convention); final String[] cr = new String[]{"columns", "rows"}; gd.addChoice("characters are: ", cr, cr[0]); gd.addMessage("[File extension ignored]"); gd.addNumericField("bottom-top overlap: ", 0, 3); //as asked by Joachim Walter gd.addNumericField("left-right overlap: ", 0, 3); gd.addCheckbox("link_images", false); gd.addCheckbox("montage", false); gd.addChoice("stitching_rule: ", StitchingTEM.rules, StitchingTEM.rules[0]); gd.addCheckbox("homogenize_contrast", true); final Component[] c = { (Component)gd.getSliders().get(gd.getSliders().size()-2), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-2), (Component)gd.getSliders().get(gd.getSliders().size()-1), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-1), (Component)gd.getChoices().get(gd.getChoices().size()-1) }; // enable the checkbox to control the slider and its associated numeric field: Utils.addEnablerListener((Checkbox)gd.getCheckboxes().get(gd.getCheckboxes().size()-1), c, null); //gd.addCheckbox("Apply non-linear deformation", false); gd.showDialog(); if (gd.wasCanceled()) { return null; } //collect data final String regex = gd.getNextString(); // filter away files not containing this tag // the base x,y of the whole grid final double bx = gd.getNextNumber(); final double by = gd.getNextNumber(); //if (!ini_grid_convention) { convention = gd.getNextString().toLowerCase(); //} if (/*!ini_grid_convention && */ (null == convention || convention.equals("") || -1 == convention.indexOf('c') || -1 == convention.indexOf('d'))) { // TODO check that the convention has only 'cdx' chars and also that there is an island of 'c's and of 'd's only. Utils.showMessage("Convention '" + convention + "' needs both c(haracters) and d(igits), optionally 'x', and nothing else!"); return null; } chars_are_columns = (0 == gd.getNextChoiceIndex()); double bt_overlap = gd.getNextNumber(); double lr_overlap = gd.getNextNumber(); final boolean link_images = gd.getNextBoolean(); final boolean stitch_tiles = gd.getNextBoolean(); final boolean homogenize_contrast = gd.getNextBoolean(); final int stitching_rule = gd.getNextChoiceIndex(); //boolean apply_non_linear_def = gd.getNextBoolean(); // Ensure tiles overlap if using SIFT if (StitchingTEM.FREE_RULE == stitching_rule) { if (bt_overlap <= 0) bt_overlap = 1; if (lr_overlap <= 0) lr_overlap = 1; } //start magic //get ImageJ-openable files that comply with the convention File images_dir = new File(dir); if (!(images_dir.exists() && images_dir.isDirectory())) { Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir); return null; } final String[] file_names = images_dir.list(new ImageFileFilter(regex, convention)); if (null == file && file_names.length > 0) { // the 'selected' file file = file_names[0]; } Utils.showStatus("Adding " + file_names.length + " patches.", false); if (0 == file_names.length) { Utils.log("Zero files match the convention '" + convention + "'"); return null; } // How to: select all files, and order their names in a double array as they should be placed in the Display. Then place them, displacing by offset, and resizing if necessary. // gather image files: final Montage montage = new Montage(convention, chars_are_columns); montage.addAll(file_names); final ArrayList cols = montage.getCols(); // an array of Object[] arrays, of unequal length maybe, each containing a column of image file names // !@#$%^&* final String dir_ = dir; final double bt_overlap_ = bt_overlap; final double lr_overlap_ = lr_overlap; final String file_ = file; return Bureaucrat.createAndStart(new Worker.Task("Insert grid", true) { public void exec() { StitchingTEM.PhaseCorrelationParam pc_param = null; if (stitch_tiles) { pc_param = new StitchingTEM.PhaseCorrelationParam(); pc_param.setup(layer); } insertGrid(layer, dir_, file_, file_names.length, cols, bx, by, bt_overlap_, lr_overlap_, link_images, stitch_tiles, homogenize_contrast, stitching_rule, pc_param, this); }}, layer.getProject()); } catch (Exception e) { IJError.print(e); } return null; } /** * Insert grid in layer (with optional stitching) * * @param layer The Layer to inser the grid into * @param dir The base dir of the images to open * @param first_image_name name of the first image in the list * @param cols The list of columns, containing each an array of String file names in each column. * @param bx The top-left X coordinate of the grid to insert * @param by The top-left Y coordinate of the grid to insert * @param bt_overlap bottom-top overlap of the images * @param lr_overlap left-right overlap of the images * @param link_images Link images to their neighbors * @param stitch_tiles montage option * @param cc_percent_overlap tiles overlap * @param cc_scale tiles scaling previous to stitching (1 = no scaling) * @param min_R regression threshold (minimum acceptable R) * @param homogenize_contrast contrast homogenization option * @param stitching_rule stitching rule (upper left corner or free) */ private void insertGrid( final Layer layer, final String dir_, final String first_image_name, final int n_images, final ArrayList<String[]> cols, final double bx, final double by, final double bt_overlap, final double lr_overlap, final boolean link_images, final boolean stitch_tiles, final boolean homogenize_contrast, final int stitching_rule, final StitchingTEM.PhaseCorrelationParam pc_param, final Worker worker) { // create a Worker, then give it to the Bureaucrat try { String dir = dir_; ArrayList<Patch> al = new ArrayList<Patch>(); Utils.showProgress(0.0D); opener.setSilentMode(true); // less repaints on IJ status bar int x = 0; int y = 0; int largest_y = 0; ImagePlus img = null; // open the selected image, to use as reference for width and height if (!enoughFreeMemory(MIN_FREE_BYTES)) releaseMemory(); dir = dir.replace('\\', '/'); // w1nd0wz safe if (!dir.endsWith("/")) dir += "/"; String path = dir + first_image_name; IJ.redirectErrorMessages(); ImagePlus first_img = openImagePlus(path); if (null == first_img) { Utils.log("Selected image to open first is null."); return; } if (null == first_img) return; final int first_image_width = first_img.getWidth(); final int first_image_height = first_img.getHeight(); final int first_image_type = first_img.getType(); // start final Patch[][] pall = new Patch[cols.size()][((String[])cols.get(0)).length]; int width, height; int k = 0; //counter boolean auto_fix_all = false; boolean ignore_all = false; boolean resize = false; if (!ControlWindow.isGUIEnabled()) { // headless mode: autofix all auto_fix_all = true; resize = true; } // Accumulate mipmap generation tasks final ArrayList<Future> fus = new ArrayList<Future>(); startLargeUpdate(); for (int i=0; i<cols.size(); i++) { String[] rows = (String[])cols.get(i); if (i > 0) { x -= lr_overlap; } for (int j=0; j<rows.length; j++) { if (Thread.currentThread().isInterrupted()) { Display.repaint(layer); rollback(); return; } if (j > 0) { y -= bt_overlap; } // get file name String file_name = (String)rows[j]; path = dir + file_name; if (null != first_img && file_name.equals(first_image_name)) { img = first_img; first_img = null; // release pointer } else { // open image //if (!enoughFreeMemory(MIN_FREE_BYTES)) releaseMemory(); // UNSAFE, doesn't wait for GC releaseToFit(first_image_width, first_image_height, first_image_type, 1.5f); try { IJ.redirectErrorMessages(); img = openImagePlus(path); } catch (OutOfMemoryError oome) { printMemState(); throw oome; } } if (null == img) { Utils.log("null image! skipping."); pall[i][j] = null; continue; } width = img.getWidth(); height = img.getHeight(); int rw = width; int rh = height; if (width != first_image_width || height != first_image_height) { int new_width = first_image_width; int new_height = first_image_height; if (!auto_fix_all && !ignore_all) { GenericDialog gdr = new GenericDialog("Size mismatch!"); gdr.addMessage("The size of " + file_name + " is " + width + " x " + height); gdr.addMessage("but the selected image was " + first_image_width + " x " + first_image_height); gdr.addMessage("Adjust to selected image dimensions?"); gdr.addNumericField("width: ", (double)first_image_width, 0); gdr.addNumericField("height: ", (double)first_image_height, 0); // should not be editable ... or at least, explain in some way that the dimensions can be edited just for this image --> done below gdr.addMessage("[If dimensions are changed they will apply only to this image]"); gdr.addMessage(""); String[] au = new String[]{"fix all", "ignore all"}; gdr.addChoice("Automate:", au, au[1]); gdr.addMessage("Cancel == NO OK = YES"); gdr.showDialog(); if (gdr.wasCanceled()) { resize = false; // do nothing: don't fix/resize } resize = true; //catch values new_width = (int)gdr.getNextNumber(); new_height = (int)gdr.getNextNumber(); int iau = gdr.getNextChoiceIndex(); if (new_width != first_image_width || new_height != first_image_height) { auto_fix_all = false; } else { auto_fix_all = (0 == iau); } ignore_all = (1 == iau); if (ignore_all) resize = false; } if (resize) { //resize Patch dimensions rw = first_image_width; rh = first_image_height; } } //add new Patch at base bx,by plus the x,y of the grid Patch patch = new Patch(layer.getProject(), img.getTitle(), bx + x, by + y, img); // will call back and cache the image if (width != rw || height != rh) patch.setDimensions(rw, rh, false); //if (null != nlt_coeffs) patch.setNonLinearCoeffs(nlt_coeffs); addedPatchFrom(path, patch); if (homogenize_contrast) setMipMapsRegeneration(false); // prevent it else fus.add(regenerateMipMaps(patch)); // layer.add(patch, true); // after the above two lines! Otherwise it will paint fine, but throw exceptions on the way patch.updateInDatabase("tiff_snapshot"); // otherwise when reopening it has to fetch all ImagePlus and scale and zip them all! This method though creates the awt and the snap, thus filling up memory and slowing down, but it's worth it. pall[i][j] = patch; al.add(patch); if (ControlWindow.isGUIEnabled()) { layer.getParent().enlargeToFit(patch, LayerSet.NORTHWEST); // northwest to prevent screwing up Patch coordinates. } y += img.getHeight(); Utils.showProgress((double)k / n_images); k++; } x += img.getWidth(); if (largest_y < y) { largest_y = y; } y = 0; //resetting! } // build list final Patch[] pa = new Patch[al.size()]; int f = 0; // list in row-first order for (int j=0; j<pall[0].length; j++) { // 'j' is row for (int i=0; i<pall.length; i++) { // 'i' is column pa[f++] = pall[i][j]; } } // optimize repaints: all to background image Display.clearSelection(layer); // make the first one be top, and the rest under it in left-right and top-bottom order for (int j=0; j<pa.length; j++) { layer.moveBottom(pa[j]); } // make picture //getFlatImage(layer, layer.getMinimalBoundingBox(Patch.class), 0.25, 1, ImagePlus.GRAY8, Patch.class, null, false).show(); // optimize repaints: all to background image Display.clearSelection(layer); if (homogenize_contrast) { if (null != worker) worker.setTaskName("Enhancing contrast"); // 0 - check that all images are of the same type int tmp_type = pa[0].getType(); for (int e=1; e<pa.length; e++) { if (pa[e].getType() != tmp_type) { // can't continue tmp_type = Integer.MAX_VALUE; Utils.log("Can't homogenize histograms: images are not all of the same type.\nFirst offending image is: " + al.get(e)); break; } } if (Integer.MAX_VALUE != tmp_type) { // checking on error flag // Set min and max for all images // 1 - fetch statistics for each image final ArrayList al_st = new ArrayList(); final ArrayList al_p = new ArrayList(); // list of Patch ordered by stdDev ASC int type = -1; releaseMemory(); // need some to operate for (int i=0; i<pa.length; i++) { if (Thread.currentThread().isInterrupted()) { Display.repaint(layer); rollback(); return; } ImagePlus imp = fetchImagePlus(pa[i]); // speed-up trick: extract data from smaller image if (imp.getWidth() > 1024) { releaseToFit(1024, (int)((imp.getHeight() * 1024) / imp.getWidth()), imp.getType(), 1.1f); // cheap and fast nearest-point resizing imp = new ImagePlus(imp.getTitle(), imp.getProcessor().resize(1024)); } if (-1 == type) type = imp.getType(); ImageStatistics i_st = imp.getStatistics(); // order by stdDev, from small to big int q = 0; for (Iterator it = al_st.iterator(); it.hasNext(); ) { ImageStatistics st = (ImageStatistics)it.next(); q++; if (st.stdDev > i_st.stdDev) break; } if (q == al.size()) { al_st.add(i_st); // append at the end. WARNING if importing thousands of images, this is a potential source of out of memory errors. I could just recompute it when I needed it again below al_p.add(pa[i]); } else { al_st.add(q, i_st); al_p.add(q, pa[i]); } } final ArrayList al_p2 = (ArrayList)al_p.clone(); // shallow copy of the ordered list // 2 - discard the first and last 25% (TODO: a proper histogram clustering analysis and histogram examination should apply here) if (pa.length > 3) { // under 4 images, use them all int i=0; while (i <= pa.length * 0.25) { al_p.remove(i); i++; } int count = i; i = pa.length -1 -count; while (i > (pa.length* 0.75) - count) { al_p.remove(i); i--; } } // 3 - compute common histogram for the middle 50% images final Patch[] p50 = new Patch[al_p.size()]; al_p.toArray(p50); StackStatistics stats = new StackStatistics(new PatchStack(p50, 1)); int n = 1; switch (type) { case ImagePlus.GRAY16: case ImagePlus.GRAY32: n = 2; break; } // 4 - compute autoAdjust min and max values // extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust int autoThreshold = 0; double min = 0; double max = 0; // once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value) int limit = stats.pixelCount/10; int[] histogram = stats.histogram; //if (autoThreshold<10) autoThreshold = 5000; //else autoThreshold /= 2; if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type) autoThreshold = 2500; else autoThreshold = 5000; int threshold = stats.pixelCount / autoThreshold; int i = -1; boolean found = false; int count; do { i++; count = histogram[i]; if (count>limit) count = 0; found = count > threshold; } while (!found && i<255); int hmin = i; i = 256; do { i--; count = histogram[i]; if (count > limit) count = 0; found = count > threshold; } while (!found && i>0); int hmax = i; if (hmax >= hmin) { min = stats.histMin + hmin*stats.binSize; max = stats.histMin + hmax*stats.binSize; if (min == max) { min = stats.min; max = stats.max; } } // 5 - compute common mean within min,max range double target_mean = getMeanOfRange(stats, min, max); Utils.log2("Loader min,max: " + min + ", " + max + ", target mean: " + target_mean); // 6 - apply to all for (i=al_p2.size()-1; i>-1; i--) { Patch p = (Patch)al_p2.get(i); // the order is different, thus getting it from the proper list double dm = target_mean - getMeanOfRange((ImageStatistics)al_st.get(i), min, max); p.setMinAndMax(min - dm, max - dm); // displacing in the opposite direction, makes sense, so that the range is drifted upwards and thus the target 256 range for an awt.Image will be closer to the ideal target_mean // OBSOLETE and wrong //p.putMinAndMax(fetchImagePlus(p)); } setMipMapsRegeneration(true); if (isMipMapsEnabled()) { // recreate files for (Patch p : al) fus.add(regenerateMipMaps(p)); } Display.repaint(layer, new Rectangle(0, 0, (int)layer.getParent().getLayerWidth(), (int)layer.getParent().getLayerHeight()), 0); // make picture //getFlatImage(layer, layer.getMinimalBoundingBox(Patch.class), 0.25, 1, ImagePlus.GRAY8, Patch.class, null, false).show(); } } if (stitch_tiles) { // Wait until all mipmaps for the new images have been generated before attempting to register Utils.wait(fus); // create undo layer.getParent().addTransformStep(new HashSet<Displayable>(layer.getDisplayables(Patch.class))); // wait until repainting operations have finished (otherwise, calling crop on an ImageProcessor fails with out of bounds exception sometimes) if (null != Display.getFront()) Display.getFront().getCanvas().waitForRepaint(); if (null != worker) worker.setTaskName("Stitching"); StitchingTEM.stitch(pa, cols.size(), bt_overlap, lr_overlap, true, stitching_rule, pc_param).run(); } // link with images on top, bottom, left and right. if (link_images) { if (null != worker) worker.setTaskName("Linking"); for (int i=0; i<pall.length; i++) { // 'i' is column for (int j=0; j<pall[0].length; j++) { // 'j' is row Patch p = pall[i][j]; if (null == p) continue; // can happen if a slot is empty if (i>0 && null != pall[i-1][j]) p.link(pall[i-1][j]); if (i<pall.length -1 && null != pall[i+1][j]) p.link(pall[i+1][j]); if (j>0 && null != pall[i][j-1]) p.link(pall[i][j-1]); if (j<pall[0].length -1 && null != pall[i][j+1]) p.link(pall[i][j+1]); } } } commitLargeUpdate(); // resize LayerSet int new_width = x; int new_height = largest_y; layer.getParent().setMinimumDimensions(); //Math.abs(bx) + new_width, Math.abs(by) + new_height); // update indexes layer.updateInDatabase("stack_index"); // so its done once only // create panels in all Displays showing this layer /* // not needed anymore Iterator it = al.iterator(); while (it.hasNext()) { Display.add(layer, (Displayable)it.next(), false); // don't set it active, don't want to reload the ImagePlus! } */ // update Displays Display.update(layer); layer.recreateBuckets(); //debug: } catch (Throwable t) { IJError.print(t); rollback(); setMipMapsRegeneration(true); } } public Bureaucrat importImages(final Layer ref_layer) { return importImages(ref_layer, null, null, 0, 0, false); } /** Import images from the given text file, which is expected to contain 4 columns:<br /> * - column 1: image file path (if base_dir is not null, it will be prepended)<br /> * - column 2: x coord<br /> * - column 3: y coord<br /> * - column 4: z coord (layer_thickness will be multiplied to it if not zero)<br /> * * This function implements the "Import from text file" command. * * Layers will be automatically created as needed inside the LayerSet to which the given ref_layer belongs.. <br /> * The text file can contain comments that start with the # sign.<br /> * Images will be imported in parallel, using as many cores as your machine has.<br /> * The @param calibration transforms the read coordinates into pixel coordinates, including x,y,z, and layer thickness. */ public Bureaucrat importImages(Layer ref_layer, String abs_text_file_path_, String column_separator_, double layer_thickness_, double calibration_, boolean homogenize_contrast_) { // check parameters: ask for good ones if necessary if (null == abs_text_file_path_) { String[] file = Utils.selectFile("Select text file"); if (null == file) return null; // user canceled dialog abs_text_file_path_ = file[0] + file[1]; } if (null == ref_layer || null == column_separator_ || 0 == column_separator_.length() || Double.isNaN(layer_thickness_) || layer_thickness_ <= 0 || Double.isNaN(calibration_) || calibration_ <= 0) { GenericDialog gdd = new GenericDialog("Options"); String[] separators = new String[]{"tab", "space", "coma (,)"}; gdd.addMessage("Choose a layer to act as the zero for the Z coordinates:"); Utils.addLayerChoice("Base layer", ref_layer, gdd); gdd.addChoice("Column separator: ", separators, separators[0]); gdd.addNumericField("Layer thickness: ", 60, 2); // default: 60 nm gdd.addNumericField("Calibration (data to pixels): ", 1, 2); gdd.addCheckbox("Homogenize contrast layer-wise", homogenize_contrast_); gdd.showDialog(); if (gdd.wasCanceled()) return null; layer_thickness_ = gdd.getNextNumber(); if (layer_thickness_ < 0 || Double.isNaN(layer_thickness_)) { Utils.log("Improper layer thickness value."); return null; } calibration_ = gdd.getNextNumber(); if (0 == calibration_ || Double.isNaN(calibration_)) { Utils.log("Improper calibration value."); return null; } ref_layer = ref_layer.getParent().getLayer(gdd.getNextChoiceIndex()); column_separator_ = "\t"; switch (gdd.getNextChoiceIndex()) { case 1: column_separator_ = " "; break; case 2: column_separator_ = ","; break; default: break; } homogenize_contrast_ = gdd.getNextBoolean(); } // make vars accessible from inner threads: final Layer base_layer = ref_layer; final String abs_text_file_path = abs_text_file_path_; final String column_separator = column_separator_; final double layer_thickness = layer_thickness_; final double calibration = calibration_; final boolean homogenize_contrast = homogenize_contrast_; return Bureaucrat.createAndStart(new Worker.Task("Importing images", true) { public void exec() { try { // 1 - read text file final String[] lines = Utils.openTextFileLines(abs_text_file_path); if (null == lines || 0 == lines.length) { Utils.log2("No images to import from " + abs_text_file_path); return; } ContrastEnhancerWrapper cew = null; if (homogenize_contrast) { cew = new ContrastEnhancerWrapper(); cew.showDialog(); } final String sep2 = column_separator + column_separator; // 2 - set a base dir path if necessary String base_dir = null; final Vector<Future> fus = new Vector<Future>(); // to wait on mipmap regeneration final LayerSet layer_set = base_layer.getParent(); final double z_zero = base_layer.getZ(); final AtomicInteger n_imported = new AtomicInteger(0); final Set<Layer> touched_layers = new HashSet<Layer>(); final int NP = Runtime.getRuntime().availableProcessors(); int np = NP; switch (np) { case 1: case 2: break; default: np = np / 2; break; } final ExecutorService ex = Utils.newFixedThreadPool(np, "import-images"); final List<Future> imported = new ArrayList<Future>(); final Worker wo = this; // 3 - parse each line for (int i = 0; i < lines.length; i++) { if (Thread.currentThread().isInterrupted() || hasQuitted()) { this.quit(); return; } // process line String line = lines[i].replace('\\','/').trim(); // first thing is the backslash removal, before they get processed at all int ic = line.indexOf('#'); if (-1 != ic) line = line.substring(0, ic); // remove comment at end of line if any if (0 == line.length() || '#' == line.charAt(0)) continue; // reduce line, so that separators are really unique while (-1 != line.indexOf(sep2)) { line = line.replaceAll(sep2, column_separator); } String[] column = line.split(column_separator); if (column.length < 4) { Utils.log("Less than 4 columns: can't import from line " + i + " : " + line); continue; } // obtain coordinates double x=0, y=0, z=0; try { x = Double.parseDouble(column[1].trim()); y = Double.parseDouble(column[2].trim()); z = Double.parseDouble(column[3].trim()); } catch (NumberFormatException nfe) { Utils.log("Non-numeric value in a numeric column at line " + i + " : " + line); continue; } x *= calibration; y *= calibration; z = z * calibration + z_zero; // obtain path String path = column[0].trim(); if (0 == path.length()) continue; // check if path is relative if ((!IJ.isWindows() && '/' != path.charAt(0)) || (IJ.isWindows() && 1 != path.indexOf(":/"))) { // path is relative. if (null == base_dir) { // may not be null if another thread that got the lock first set it to non-null // Ask for source directory DirectoryChooser dc = new DirectoryChooser("Choose source directory"); String dir = dc.getDirectory(); if (null == dir) { // quit all threads return; } base_dir = Utils.fixDir(dir); } } if (null != base_dir) path = base_dir + path; File f = new File(path); if (!f.exists()) { Utils.log("No file found for path " + path); continue; } final Layer layer = layer_set.getLayer(z, layer_thickness, true); // will create a new Layer if necessary touched_layers.add(layer); final String imagefilepath = path; final double xx = x; final double yy = y; // If loaded twice as many, wait for mipmaps to finish // Otherwise, images would end up loaded twice for no reason if (0 == (i % (NP+NP))) { final ArrayList<Future> a = new ArrayList<Future>(NP+NP); synchronized (fus) { // .add is also synchronized, it's a Vector int k = 0; while (!fus.isEmpty() && k < NP) { a.add(fus.remove(0)); k++; } } for (final Future fu : a) { try { if (wo.hasQuitted()) return; fu.get(); } catch (Throwable t) { t.printStackTrace(); } } } imported.add(ex.submit(new Runnable() { public void run() { if (wo.hasQuitted()) return; releaseMemory(); //ensures a usable minimum is free /* */ IJ.redirectErrorMessages(); ImagePlus imp = openImagePlus(imagefilepath); if (null == imp) { Utils.log("Ignoring unopenable image from " + imagefilepath); return; } // add Patch and generate its mipmaps final Patch patch = new Patch(layer.getProject(), imp.getTitle(), xx, yy, imp); addedPatchFrom(imagefilepath, patch); if (!homogenize_contrast) { fus.add(regenerateMipMaps(patch)); } synchronized (layer) { layer.add(patch, true); } wo.setTaskName("Imported " + (n_imported.incrementAndGet() + 1) + "/" + lines.length); } })); } Utils.wait(imported); ex.shutdown(); if (0 == n_imported.get()) { Utils.log("No images imported."); return; } base_layer.getParent().setMinimumDimensions(); Display.repaint(base_layer.getParent()); recreateBuckets(touched_layers); if (homogenize_contrast) { setTaskName("Enhance contrast"); // layer-wise (layer order is irrelevant): cew.applyLayerWise(touched_layers); cew.shutdown(); } Utils.wait(fus); } catch (Exception e) { IJError.print(e); } } }, base_layer.getProject()); } public Bureaucrat importLabelsAsAreaLists(final Layer layer) { return importLabelsAsAreaLists(layer, null, 0, 0, 0.4f, false); } /** If base_x or base_y are Double.MAX_VALUE, then those values are asked for in a GenericDialog. */ public Bureaucrat importLabelsAsAreaLists(final Layer first_layer, final String path_, final double base_x_, final double base_y_, final float alpha_, final boolean add_background_) { Worker worker = new Worker("Import labels as arealists") { public void run() { startedWorking(); try { String path = path_; if (null == path) { OpenDialog od = new OpenDialog("Select stack", ""); String name = od.getFileName(); if (null == name || 0 == name.length()) { return; } String dir = od.getDirectory().replace('\\', '/'); if (!dir.endsWith("/")) dir += "/"; path = dir + name; } if (path.toLowerCase().endsWith(".xml")) { Utils.log("Avoided opening a TrakEM2 project."); return; } double base_x = base_x_; double base_y = base_y_; float alpha = alpha_; boolean add_background = add_background_; Layer layer = first_layer; if (Double.MAX_VALUE == base_x || Double.MAX_VALUE == base_y || alpha < 0 || alpha > 1) { GenericDialog gd = new GenericDialog("Base x, y"); Utils.addLayerChoice("First layer:", first_layer, gd); gd.addNumericField("Base_X:", 0, 0); gd.addNumericField("Base_Y:", 0, 0); gd.addSlider("Alpha:", 0, 100, 40); gd.addCheckbox("Add background (zero)", false); gd.showDialog(); if (gd.wasCanceled()) { return; } layer = first_layer.getParent().getLayer(gd.getNextChoiceIndex()); base_x = gd.getNextNumber(); base_y = gd.getNextNumber(); if (Double.isNaN(base_x) || Double.isNaN(base_y)) { Utils.log("Base x or y is NaN!"); return; } alpha = (float)(gd.getNextNumber() / 100); add_background = gd.getNextBoolean(); } releaseMemory(); final ImagePlus imp = openImagePlus(path); if (null == imp) { Utils.log("Could not open image at " + path); return; } Map<Float,AreaList> alis = AmiraImporter.extractAreaLists(imp, layer, base_x, base_y, alpha, add_background); if (!hasQuitted() && alis.size() > 0) { layer.getProject().getProjectTree().insertSegmentations(layer.getProject(), alis.values()); } } catch (Exception e) { IJError.print(e); } finally { finishedWorking(); } } }; return Bureaucrat.createAndStart(worker, first_layer.getProject()); } public void recreateBuckets(final Collection<Layer> col) { final Layer[] lall = new Layer[col.size()]; col.toArray(lall); recreateBuckets(lall); } /** Recreate buckets for each Layer, one thread per layer, in as many threads as CPUs. */ public void recreateBuckets(final Layer[] la) { final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = MultiThreading.newThreads(); for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread() { public void run() { setPriority(Thread.NORM_PRIORITY); for (int i = ai.getAndIncrement(); i < la.length; i = ai.getAndIncrement()) { la[i].recreateBuckets(); } } }; } MultiThreading.startAndJoin(threads); } private double getMeanOfRange(ImageStatistics st, double min, double max) { if (min == max) return min; double mean = 0; int nn = 0; int first_bin = 0; int last_bin = st.nBins -1; for (int b=0; b<st.nBins; b++) { if (st.min + st.binSize * b > min) { first_bin = b; break; } } for (int b=last_bin; b>first_bin; b--) { if (st.max - st.binSize * b <= max) { last_bin = b; break; } } for (int h=first_bin; h<=last_bin; h++) { nn += st.histogram[h]; mean += h * st.histogram[h]; } return mean /= nn; } /** Used for the revert command. */ abstract public ImagePlus fetchOriginal(Patch patch); public Bureaucrat makeFlatImage(final Layer[] layer, final Rectangle srcRect, final double scale, final int c_alphas, final int type, final boolean force_to_file, final boolean quality) { return makeFlatImage(layer, srcRect, scale, c_alphas, type, force_to_file, quality, Color.black); } /** If the srcRect is null, makes a flat 8-bit or RGB image of the entire layer. Otherwise just of the srcRect. Checks first for enough memory and frees some if feasible. */ public Bureaucrat makeFlatImage(final Layer[] layer, final Rectangle srcRect, final double scale, final int c_alphas, final int type, final boolean force_to_file, final boolean quality, final Color background) { if (null == layer || 0 == layer.length) { Utils.log2("makeFlatImage: null or empty list of layers to process."); return null; } final Worker worker = new Worker("making flat images") { public void run() { try { // startedWorking(); Rectangle srcRect_ = srcRect; if (null == srcRect_) srcRect_ = layer[0].getParent().get2DBounds(); ImagePlus imp = null; String target_dir = null; boolean choose_dir = force_to_file; // if not saving to a file: if (!force_to_file) { final long size = (long)Math.ceil((srcRect_.width * scale) * (srcRect_.height * scale) * ( ImagePlus.GRAY8 == type ? 1 : 4 ) * layer.length); if (size > IJ.maxMemory() * 0.9) { YesNoCancelDialog yn = new YesNoCancelDialog(IJ.getInstance(), "WARNING", "The resulting stack of flat images is too large to fit in memory.\nChoose a directory to save the slices as an image sequence?"); if (yn.yesPressed()) { choose_dir = true; } else if (yn.cancelPressed()) { finishedWorking(); return; } else { choose_dir = false; // your own risk } } } if (choose_dir) { final DirectoryChooser dc = new DirectoryChooser("Target directory"); target_dir = dc.getDirectory(); if (null == target_dir || target_dir.toLowerCase().startsWith("null")) { finishedWorking(); return; } if (IJ.isWindows()) target_dir = target_dir.replace('\\', '/'); if (!target_dir.endsWith("/")) target_dir += "/"; } if (layer.length > 1) { // 1 - determine stack voxel depth (by choosing one, if there are layers with different thickness) double voxel_depth = 1; if (null != target_dir) { // otherwise, saving separately ArrayList al_thickness = new ArrayList(); for (int i=0; i<layer.length; i++) { Double t = new Double(layer[i].getThickness()); if (!al_thickness.contains(t)) al_thickness.add(t); } if (1 == al_thickness.size()) { // trivial case voxel_depth = ((Double)al_thickness.get(0)).doubleValue(); } else { String[] st = new String[al_thickness.size()]; for (int i=0; i<st.length; i++) { st[i] = al_thickness.get(i).toString(); } GenericDialog gdd = new GenericDialog("Choose voxel depth"); gdd.addChoice("voxel depth: ", st, st[0]); gdd.showDialog(); if (gdd.wasCanceled()) { finishedWorking(); return; } voxel_depth = ((Double)al_thickness.get(gdd.getNextChoiceIndex())).doubleValue(); } } // 2 - get all slices ImageStack stack = null; for (int i=0; i<layer.length; i++) { final ImagePlus slice = getFlatImage(layer[i], srcRect_, scale, c_alphas, type, Displayable.class, null, quality, background); if (null == slice) { Utils.log("Could not retrieve flat image for " + layer[i].toString()); continue; } if (null != target_dir) { saveToPath(slice, target_dir, layer[i].getPrintableTitle(), ".tif"); } else { if (null == stack) stack = new ImageStack(slice.getWidth(), slice.getHeight()); stack.addSlice(layer[i].getProject().findLayerThing(layer[i]).toString(), slice.getProcessor()); } } if (null != stack) { imp = new ImagePlus("z=" + layer[0].getZ() + " to z=" + layer[layer.length-1].getZ(), stack); final Calibration impCalibration = layer[0].getParent().getCalibrationCopy(); impCalibration.pixelWidth /= scale; impCalibration.pixelHeight /= scale; imp.setCalibration(impCalibration); } } else { imp = getFlatImage(layer[0], srcRect_, scale, c_alphas, type, Displayable.class, null, quality, background); if (null != target_dir) { saveToPath(imp, target_dir, layer[0].getPrintableTitle(), ".tif"); imp = null; // to prevent showing it } } if (null != imp) imp.show(); } catch (Throwable e) { IJError.print(e); } finishedWorking(); }}; // I miss my lisp macros, you have no idea return Bureaucrat.createAndStart(worker, layer[0].getProject()); } /** Will never overwrite, rather, add an underscore and ordinal to the file name. */ private void saveToPath(final ImagePlus imp, final String dir, final String file_name, final String extension) { if (null == imp) { Utils.log2("Loader.saveToPath: can't save a null image."); return; } // create a unique file name String path = dir + "/" + file_name; File file = new File(path + extension); int k = 1; while (file.exists()) { file = new File(path + "_" + k + ".tif"); k++; } try { new FileSaver(imp).saveAsTiff(file.getAbsolutePath()); } catch (OutOfMemoryError oome) { Utils.log2("Not enough memory. Could not save image for " + file_name); IJError.print(oome); } catch (Exception e) { Utils.log2("Could not save image for " + file_name); IJError.print(e); } } public ImagePlus getFlatImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, final boolean quality) { return getFlatImage(layer, srcRect_, scale, c_alphas, type, clazz, null, quality, Color.black); } public ImagePlus getFlatImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, List al_displ) { return getFlatImage(layer, srcRect_, scale, c_alphas, type, clazz, al_displ, false, Color.black); } public ImagePlus getFlatImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, List al_displ, boolean quality) { return getFlatImage(layer, srcRect_, scale, c_alphas, type, clazz, al_displ, quality, Color.black); } public ImagePlus getFlatImage(final Selection selection, final double scale, final int c_alphas, final int type, boolean quality, final Color background) { return getFlatImage(selection.getLayer(), selection.getBox(), scale, c_alphas, type, null, selection.getSelected(), quality, background); } /** Returns a screenshot of the given layer for the given magnification and srcRect. Returns null if the was not enough memory to create it. * @param al_displ The Displayable objects to paint. If null, all those matching Class clazz are included. * * If the 'quality' flag is given, then the flat image is created at a scale of 1.0, and later scaled down using the Image.getScaledInstance method with the SCALE_AREA_AVERAGING flag. * */ public ImagePlus getFlatImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, List al_displ, boolean quality, final Color background) { final Image bi = getFlatAWTImage(layer, srcRect_, scale, c_alphas, type, clazz, al_displ, quality, background); final ImagePlus imp = new ImagePlus(layer.getPrintableTitle(), bi); final Calibration impCalibration = layer.getParent().getCalibrationCopy(); impCalibration.pixelWidth /= scale; impCalibration.pixelHeight /= scale; imp.setCalibration(impCalibration); bi.flush(); return imp; } public Image getFlatAWTImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, List al_displ, boolean quality, final Color background) { try { // if quality is specified, then a larger image is generated: // - full size if no mipmaps // - double the size if mipmaps is enabled double scaleP = scale; if (quality) { if (isMipMapsEnabled()) { // just double the size scaleP = scale + scale; if (scaleP > 1.0) scaleP = 1.0; } else { // full scaleP = 1.0; } } // dimensions int x = 0; int y = 0; int w = 0; int h = 0; Rectangle srcRect = (null == srcRect_) ? null : (Rectangle)srcRect_.clone(); if (null != srcRect) { x = srcRect.x; y = srcRect.y; w = srcRect.width; h = srcRect.height; } else { w = (int)Math.ceil(layer.getLayerWidth()); h = (int)Math.ceil(layer.getLayerHeight()); srcRect = new Rectangle(0, 0, w, h); } Utils.log2("Loader.getFlatImage: using rectangle " + srcRect); // estimate image size final long n_bytes = (long)((w * h * scaleP * scaleP * (ImagePlus.GRAY8 == type ? 1.0 /*byte*/ : 4.0 /*int*/))); Utils.log2("Flat image estimated size in bytes: " + Long.toString(n_bytes) + " w,h : " + (int)Math.ceil(w * scaleP) + "," + (int)Math.ceil(h * scaleP) + (quality ? " (using 'quality' flag: scaling to " + scale + " is done later with proper area averaging)" : "")); if (!releaseToFit(n_bytes)) { // locks on it's own Utils.showMessage("Not enough free RAM for a flat image."); return null; } // go releaseMemory(); // savage ... BufferedImage bi = null; switch (type) { case ImagePlus.GRAY8: bi = new BufferedImage((int)Math.ceil(w * scaleP), (int)Math.ceil(h * scaleP), BufferedImage.TYPE_BYTE_INDEXED, GRAY_LUT); break; case ImagePlus.COLOR_RGB: bi = new BufferedImage((int)Math.ceil(w * scaleP), (int)Math.ceil(h * scaleP), BufferedImage.TYPE_INT_ARGB); break; default: Utils.log2("Left bi,icm as null"); break; } final Graphics2D g2d = bi.createGraphics(); g2d.setColor(background); g2d.fillRect(0, 0, bi.getWidth(), bi.getHeight()); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); releaseMemory(); // savage ... ArrayList al_zdispl = null; if (null == al_displ) { al_displ = layer.getDisplayables(clazz); al_zdispl = layer.getParent().getZDisplayables(clazz); } else { // separate ZDisplayables into their own array al_displ = new ArrayList(al_displ); //Utils.log2("al_displ size: " + al_displ.size()); al_zdispl = new ArrayList(); for (Iterator it = al_displ.iterator(); it.hasNext(); ) { Object ob = it.next(); if (ob instanceof ZDisplayable) { it.remove(); al_zdispl.add(ob); } } // order ZDisplayables by their stack order ArrayList al_zdispl2 = layer.getParent().getZDisplayables(); for (Iterator it = al_zdispl2.iterator(); it.hasNext(); ) { Object ob = it.next(); if (!al_zdispl.contains(ob)) it.remove(); } al_zdispl = al_zdispl2; } // prepare the canvas for the srcRect and magnification final AffineTransform at_original = g2d.getTransform(); final AffineTransform atc = new AffineTransform(); atc.scale(scaleP, scaleP); atc.translate(-srcRect.x, -srcRect.y); at_original.preConcatenate(atc); g2d.setTransform(at_original); //Utils.log2("will paint: " + al_displ.size() + " displ and " + al_zdispl.size() + " zdispl"); //int total = al_displ.size() + al_zdispl.size(); int count = 0; boolean zd_done = false; for(Iterator it = al_displ.iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); //Utils.log2("d is: " + d); // paint the ZDisplayables before the first label, if any if (!zd_done && d instanceof DLabel) { zd_done = true; for (Iterator itz = al_zdispl.iterator(); itz.hasNext(); ) { ZDisplayable zd = (ZDisplayable)itz.next(); if (!zd.isOutOfRepaintingClip(scaleP, srcRect, null)) { zd.paint(g2d, srcRect, scaleP, false, c_alphas, layer); } count++; //Utils.log2("Painted " + count + " of " + total); } } if (!d.isOutOfRepaintingClip(scaleP, srcRect, null)) { d.paintOffscreen(g2d, srcRect, scaleP, false, c_alphas, layer); //Utils.log("painted: " + d + "\n with: " + scaleP + ", " + c_alphas + ", " + layer); } else { //Utils.log2("out: " + d); } count++; //Utils.log2("Painted " + count + " of " + total); } if (!zd_done) { zd_done = true; for (Iterator itz = al_zdispl.iterator(); itz.hasNext(); ) { ZDisplayable zd = (ZDisplayable)itz.next(); if (!zd.isOutOfRepaintingClip(scaleP, srcRect, null)) { zd.paint(g2d, srcRect, scaleP, false, c_alphas, layer); } count++; //Utils.log2("Painted " + count + " of " + total); } } // ensure enough memory is available for the processor and a new awt from it releaseToFit((long)(n_bytes*2.3)); // locks on its own try { if (quality) { // need to scale back down Image scaled = null; if (!isMipMapsEnabled() || scale >= 0.499) { // there are no proper mipmaps above 50%, so there's need for SCALE_AREA_AVERAGING. scaled = bi.getScaledInstance((int)(w * scale), (int)(h * scale), Image.SCALE_AREA_AVERAGING); // very slow, but best by far if (ImagePlus.GRAY8 == type) { // getScaledInstance generates RGB images for some reason. BufferedImage bi8 = new BufferedImage((int)(w * scale), (int)(h * scale), BufferedImage.TYPE_BYTE_GRAY); bi8.createGraphics().drawImage(scaled, 0, 0, null); scaled.flush(); scaled = bi8; } } else { // faster, but requires gaussian blurred images (such as the mipmaps) if (bi.getType() == BufferedImage.TYPE_BYTE_INDEXED) { scaled = new BufferedImage((int)(w * scale), (int)(h * scale), bi.getType(), GRAY_LUT); } else { scaled = new BufferedImage((int)(w * scale), (int)(h * scale), bi.getType()); } Graphics2D gs = (Graphics2D)scaled.getGraphics(); //gs.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); gs.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); gs.drawImage(bi, 0, 0, (int)(w * scale), (int)(h * scale), null); } bi.flush(); return scaled; } else { // else the image was made scaled down already, and of the proper type return bi; } } catch (OutOfMemoryError oome) { Utils.log("Not enough memory to create the ImagePlus. Try scaling it down or not using the 'quality' flag."); } } catch (Exception e) { IJError.print(e); } return null; } /** Creates an ImageProcessor of the specified type. */ public ImageProcessor makeFlatImage(final int type, final Layer layer, final Rectangle srcRect, final double scale, final ArrayList<Patch> patches, final Color background) { return Patch.makeFlatImage(type, layer, srcRect, scale, patches, background); } public Bureaucrat makePrescaledTiles(final Layer[] layer, final Class clazz, final Rectangle srcRect, double max_scale_, final int c_alphas, final int type) { return makePrescaledTiles(layer, clazz, srcRect, max_scale_, c_alphas, type, null); } /** Generate 256x256 tiles, as many as necessary, to cover the given srcRect, starting at max_scale. Designed to be slow but memory-capable. * * filename = z + "/" + row + "_" + column + "_" + s + ".jpg"; * * row and column run from 0 to n stepsize 1 * that is, row = y / ( 256 * 2^s ) and column = x / ( 256 * 2^s ) * * z : z-level (slice) * x,y: the row and column * s: scale, which is 1 / (2^s), in integers: 0, 1, 2 ... * *  var MAX_S = Math.floor( Math.log( MAX_Y + 1 ) / Math.LN2 ) - Math.floor( Math.log( Y_TILE_SIZE ) / Math.LN2 ) - 1; * * The module should not be more than 5 * At al levels, there should be an even number of rows and columns, except for the coarsest level. * The coarsest level should be at least 5x5 tiles. * * Best results obtained when the srcRect approaches or is a square. Black space will pad the right and bottom edges when the srcRect is not exactly a square. * Only the area within the srcRect is ever included, even if actual data exists beyond. * * Returns the watcher thread, for joining purposes, or null if the dialog is canceled or preconditions ar enot passed. */ public Bureaucrat makePrescaledTiles(final Layer[] layer, final Class clazz, final Rectangle srcRect, double max_scale_, final int c_alphas, final int type, String target_dir) { if (null == layer || 0 == layer.length) return null; // choose target directory if (null == target_dir) { DirectoryChooser dc = new DirectoryChooser("Choose target directory"); target_dir = dc.getDirectory(); if (null == target_dir) return null; } if (IJ.isWindows()) target_dir = target_dir.replace('\\', '/'); if (!target_dir.endsWith("/")) target_dir += "/"; if (max_scale_ > 1) { Utils.log("Prescaled Tiles: using max scale of 1.0"); max_scale_ = 1; // no point } final String dir = target_dir; final double max_scale = max_scale_; final float jpeg_quality = ij.plugin.JpegWriter.getQuality() / 100.0f; Utils.log("Using jpeg quality: " + jpeg_quality); Worker worker = new Worker("Creating prescaled tiles") { private void cleanUp() { finishedWorking(); } public void run() { startedWorking(); try { // project name //String pname = layer[0].getProject().getTitle(); // create 'z' directories if they don't exist: check and ask! // start with the highest scale level final int[] best = determineClosestPowerOfTwo(srcRect.width > srcRect.height ? srcRect.width : srcRect.height); final int edge_length = best[0]; final int n_edge_tiles = edge_length / 256; Utils.log2("srcRect: " + srcRect); Utils.log2("edge_length, n_edge_tiles, best[1] " + best[0] + ", " + n_edge_tiles + ", " + best[1]); // thumbnail dimensions //LayerSet ls = layer[0].getParent(); double ratio = srcRect.width / (double)srcRect.height; double thumb_scale = 1.0; if (ratio >= 1) { // width is larger or equal than height thumb_scale = 192.0 / srcRect.width; } else { thumb_scale = 192.0 / srcRect.height; } for (int iz=0; iz<layer.length; iz++) { if (this.quit) { cleanUp(); return; } // 1 - create a directory 'z' named as the layer's Z coordinate String tile_dir = dir + layer[iz].getParent().indexOf(layer[iz]); File fdir = new File(tile_dir); int tag = 1; // Ensure there is a usable directory: while (fdir.exists() && !fdir.isDirectory()) { fdir = new File(tile_dir + "_" + tag); } if (!fdir.exists()) { fdir.mkdir(); Utils.log("Created directory " + fdir); } // if the directory exists already just reuse it, overwritting its files if so. final String tmp = fdir.getAbsolutePath().replace('\\','/'); if (!tile_dir.equals(tmp)) Utils.log("\tWARNING: directory will not be in the standard location."); // debug: Utils.log2("tile_dir: " + tile_dir + "\ntmp: " + tmp); tile_dir = tmp; if (!tile_dir.endsWith("/")) tile_dir += "/"; // 2 - create layer thumbnail, max 192x192 ImagePlus thumb = getFlatImage(layer[iz], srcRect, thumb_scale, c_alphas, type, clazz, true); ImageSaver.saveAsJpeg(thumb.getProcessor(), tile_dir + "small.jpg", jpeg_quality, ImagePlus.COLOR_RGB != type); flush(thumb); thumb = null; // 3 - fill directory with tiles if (edge_length < 256) { // edge_length is the largest length of the 256x256 tile map that covers an area equal or larger than the desired srcRect (because all tiles have to be 256x256 in size) // create single tile per layer makeTile(layer[iz], srcRect, max_scale, c_alphas, type, clazz, jpeg_quality, tile_dir + "0_0_0.jpg"); } else { // create piramid of tiles double scale = 1; //max_scale; // WARNING if scale is different than 1, it will FAIL to set the next scale properly. int scale_pow = 0; int n_et = n_edge_tiles; // cached for local modifications in the loop, works as loop controler while (n_et >= best[1]) { // best[1] is the minimal root found, i.e. 1,2,3,4,5 from hich then powers of two were taken to make up for the edge_length int tile_side = (int)(256/scale); // 0 < scale <= 1, so no precision lost for (int row=0; row<n_et; row++) { for (int col=0; col<n_et; col++) { final int i_tile = row * n_et + col; Utils.showProgress(i_tile / (double)(n_et * n_et)); if (0 == i_tile % 100) { releaseMemory(); } if (this.quit) { cleanUp(); return; } Rectangle tile_src = new Rectangle(srcRect.x + tile_side*row, srcRect.y + tile_side*col, tile_side, tile_side); // in absolute coords, magnification later. // crop bounds if (tile_src.x + tile_src.width > srcRect.x + srcRect.width) tile_src.width = srcRect.x + srcRect.width - tile_src.x; if (tile_src.y + tile_src.height > srcRect.y + srcRect.height) tile_src.height = srcRect.y + srcRect.height - tile_src.y; // negative tile sizes will be made into black tiles // (negative dimensions occur for tiles beyond the edges of srcRect, since the grid of tiles has to be of equal number of rows and cols) makeTile(layer[iz], tile_src, scale, c_alphas, type, clazz, jpeg_quality, new StringBuffer(tile_dir).append(col).append('_').append(row).append('_').append(scale_pow).append(".jpg").toString()); // should be row_col_scale, but results in transposed tiles in googlebrains, so I inversed it. } } scale_pow++; scale = 1 / Math.pow(2, scale_pow); // works as magnification n_et /= 2; } } } } catch (Exception e) { IJError.print(e); } finally { Utils.showProgress(1); } cleanUp(); finishedWorking(); }// end of run method }; // watcher thread return Bureaucrat.createAndStart(worker, layer[0].getProject()); } /** Will overwrite if the file path exists. */ private void makeTile(Layer layer, Rectangle srcRect, double mag, int c_alphas, int type, Class clazz, final float jpeg_quality, String file_path) throws Exception { ImagePlus imp = null; if (srcRect.width > 0 && srcRect.height > 0) { imp = getFlatImage(layer, srcRect, mag, c_alphas, type, clazz, null, true); // with quality } else { imp = new ImagePlus("", new ByteProcessor(256, 256)); // black tile } // correct cropped tiles if (imp.getWidth() < 256 || imp.getHeight() < 256) { ImagePlus imp2 = new ImagePlus(imp.getTitle(), imp.getProcessor().createProcessor(256, 256)); // ensure black background for color images if (imp2.getType() == ImagePlus.COLOR_RGB) { Roi roi = new Roi(0, 0, 256, 256); imp2.setRoi(roi); imp2.getProcessor().setValue(0); // black imp2.getProcessor().fill(); } imp2.getProcessor().insert(imp.getProcessor(), 0, 0); imp = imp2; } // debug //Utils.log("would save: " + srcRect + " at " + file_path); ImageSaver.saveAsJpeg(imp.getProcessor(), file_path, jpeg_quality, ImagePlus.COLOR_RGB != type); } /** Find the closest, but larger, power of 2 number for the given edge size; the base root may be any of {1,2,3,5}. */ private int[] determineClosestPowerOfTwo(final int edge) { int[] starter = new int[]{1, 2, 3, 5}; // I love primer numbers int[] larger = new int[starter.length]; System.arraycopy(starter, 0, larger, 0, starter.length); // I hate java's obscene verbosity for (int i=0; i<larger.length; i++) { while (larger[i] < edge) { larger[i] *= 2; } } int min_larger = larger[0]; int min_i = 0; for (int i=1; i<larger.length; i++) { if (larger[i] < min_larger) { min_i = i; min_larger = larger[i]; } } // 'larger' is now larger or equal to 'edge', and will reduce to starter[min_i] tiles squared. return new int[]{min_larger, starter[min_i]}; } /** WARNING may be altered concurrently. */ private String last_opened_path = null; /** Subclasses can override this method to register the URL of the imported image. */ public void addedPatchFrom(String path, Patch patch) {} /** Import an image into the given layer, in a separate task thread. */ public Bureaucrat importImage(final Layer layer, final double x, final double y, final String path, final boolean synch_mipmap_generation) { Worker worker = new Worker("Importing image") { public void run() { startedWorking(); try { //// if (null == layer) { Utils.log("Can't import. No layer found."); finishedWorking(); return; } Patch p = importImage(layer.getProject(), x, y, path, synch_mipmap_generation); if (null != p) { synchronized (layer) { layer.add(p); } layer.getParent().enlargeToFit(p, LayerSet.NORTHWEST); } //// } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; return Bureaucrat.createAndStart(worker, layer.getProject()); } public Patch importImage(Project project, double x, double y) { return importImage(project, x, y, null, false); } /** Import a new image at the given coordinates; does not puts it into any layer, unless it's a stack -in which case importStack is called with the current front layer of the given project as target. If a path is not provided it will be asked for.*/ public Patch importImage(Project project, double x, double y, String path, boolean synch_mipmap_generation) { if (null == path) { OpenDialog od = new OpenDialog("Import image", ""); String name = od.getFileName(); if (null == name || 0 == name.length()) return null; String dir = od.getDirectory().replace('\\', '/'); if (!dir.endsWith("/")) dir += "/"; path = dir + name; } else { path = path.replace('\\', '/'); } // avoid opening trakem2 projects if (path.toLowerCase().endsWith(".xml")) { Utils.showMessage("Cannot import " + path + " as a stack."); return null; } releaseMemory(); // some: TODO this should read the header only, and figure out the dimensions to do a releaseToFit(n_bytes) call IJ.redirectErrorMessages(); final ImagePlus imp = openImagePlus(path); if (null == imp) return null; if (imp.getNSlices() > 1) { // a stack! Layer layer = Display.getFrontLayer(project); if (null == layer) return null; importStack(layer, x, y, imp, true, path, true); return null; } if (0 == imp.getWidth() || 0 == imp.getHeight()) { Utils.showMessage("Can't import image of zero width or height."); flush(imp); return null; } Patch p = new Patch(project, imp.getTitle(), x, y, imp); addedPatchFrom(path, p); last_opened_path = path; // WARNING may be altered concurrently if (isMipMapsEnabled()) { if (synch_mipmap_generation) generateMipMaps(p); else regenerateMipMaps(p); // queue for regeneration } return p; } public Patch importNextImage(Project project, double x, double y) { if (null == last_opened_path) { return importImage(project, x, y); } int i_slash = last_opened_path.lastIndexOf("/"); String dir_name = last_opened_path.substring(0, i_slash + 1); File dir = new File(dir_name); String last_file = last_opened_path.substring(i_slash + 1); String[] file_names = dir.list(); String next_file = null; final String exts = "tiftiffjpgjpegpnggifzipdicombmppgm"; for (int i=0; i<file_names.length; i++) { if (last_file.equals(file_names[i]) && i < file_names.length -1) { // loop until finding a suitable next for (int j=i+1; j<file_names.length; j++) { String ext = file_names[j].substring(file_names[j].lastIndexOf('.') + 1).toLowerCase(); if (-1 != exts.indexOf(ext)) { next_file = file_names[j]; break; } } break; } } if (null == next_file) { Utils.showMessage("No more files after " + last_file); return null; } releaseMemory(); // some: TODO this should read the header only, and figure out the dimensions to do a releaseToFit(n_bytes) call IJ.redirectErrorMessages(); ImagePlus imp = openImagePlus(dir_name + next_file); if (null == imp) return null; if (0 == imp.getWidth() || 0 == imp.getHeight()) { Utils.showMessage("Can't import image of zero width or height."); flush(imp); return null; } String path = dir + "/" + next_file; Patch p = new Patch(project, imp.getTitle(), x, y, imp); addedPatchFrom(path, p); last_opened_path = path; // WARNING may be altered concurrently if (isMipMapsEnabled()) regenerateMipMaps(p); return p; } public Bureaucrat importStack(Layer first_layer, ImagePlus imp_stack_, boolean ask_for_data) { return importStack(first_layer, imp_stack_, ask_for_data, null); } public Bureaucrat importStack(final Layer first_layer, final ImagePlus imp_stack_, final boolean ask_for_data, final String filepath_) { return importStack(first_layer, 0, 0, imp_stack_, ask_for_data, filepath_, true); } /** Imports an image stack from a multitiff file and places each slice in the proper layer, creating new layers as it goes. If the given stack is null, popup a file dialog to choose one*/ public Bureaucrat importStack(final Layer first_layer, final double x, final double y, final ImagePlus imp_stack_, final boolean ask_for_data, final String filepath_, final boolean one_patch_per_layer_) { Utils.log2("Loader.importStack filepath: " + filepath_); if (null == first_layer) return null; Worker worker = new Worker("import stack") { public void run() { startedWorking(); try { String filepath = filepath_; boolean one_patch_per_layer = one_patch_per_layer_; /* On drag and drop the stack is not null! */ //Utils.log2("imp_stack_ is " + imp_stack_); ImagePlus[] stks = null; boolean choose = false; if (null == imp_stack_) { stks = Utils.findOpenStacks(); choose = null == stks || stks.length > 0; } else { stks = new ImagePlus[]{imp_stack_}; } ImagePlus imp_stack = null; // ask to open a stack if it's null if (null == stks) { imp_stack = openStack(); // choose one } else if (choose) { // choose one from the list GenericDialog gd = new GenericDialog("Choose one"); gd.addMessage("Choose a stack from the list or 'open...' to bring up a file chooser dialog:"); String[] list = new String[stks.length +1]; for (int i=0; i<list.length -1; i++) { list[i] = stks[i].getTitle(); } list[list.length-1] = "[ Open stack... ]"; gd.addChoice("choose stack: ", list, list[0]); gd.showDialog(); if (gd.wasCanceled()) { finishedWorking(); return; } int i_choice = gd.getNextChoiceIndex(); if (list.length-1 == i_choice) { // the open... command imp_stack = first_layer.getProject().getLoader().openStack(); } else { imp_stack = stks[i_choice]; } } else { imp_stack = imp_stack_; } // check: if (null == imp_stack) { finishedWorking(); return; } final String props = (String)imp_stack.getProperty("Info"); // check if it's amira labels stack to prevent missimports if (null != props && -1 != props.indexOf("Materials {")) { YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "Warning", "You are importing a stack of Amira labels as a regular image stack. Continue anyway?"); if (!yn.yesPressed()) { finishedWorking(); return; } } //String dir = imp_stack.getFileInfo().directory; double layer_width = first_layer.getLayerWidth(); double layer_height= first_layer.getLayerHeight(); double current_thickness = first_layer.getThickness(); double thickness = current_thickness; boolean expand_layer_set = false; boolean lock_stack = false; //int anchor = LayerSet.NORTHWEST; //default if (ask_for_data) { // ask for slice separation in pixels GenericDialog gd = new GenericDialog("Slice separation?"); gd.addMessage("Please enter the slice thickness, in pixels"); gd.addNumericField("slice_thickness: ", Math.abs(imp_stack.getCalibration().pixelDepth / imp_stack.getCalibration().pixelHeight), 3); // assuming pixelWidth == pixelHeight if (layer_width != imp_stack.getWidth() || layer_height != imp_stack.getHeight()) { gd.addCheckbox("Resize canvas to fit stack", true); //gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[0]); } gd.addCheckbox("Lock stack", false); final String[] importStackTypes = {"One slice per layer (Patches)", "Image volume (Stack)"}; if (imp_stack.getStack().isVirtual()) { one_patch_per_layer = true; } gd.addChoice("Import stack as:", importStackTypes, importStackTypes[0]); ((Component)gd.getChoices().get(0)).setEnabled(!imp_stack.getStack().isVirtual()); gd.showDialog(); if (gd.wasCanceled()) { if (null == stks) { // flush only if it was not open before flush(imp_stack); } finishedWorking(); return; } if (layer_width != imp_stack.getWidth() || layer_height != imp_stack.getHeight()) { expand_layer_set = gd.getNextBoolean(); //anchor = gd.getNextChoiceIndex(); } lock_stack = gd.getNextBoolean(); thickness = gd.getNextNumber(); // check provided thickness with that of the first layer: if (thickness != current_thickness) { if (1 == first_layer.getParent().size() && first_layer.isEmpty()) { YesNoCancelDialog yn = new YesNoCancelDialog(IJ.getInstance(), "Mismatch!", "The current layer's thickness is " + current_thickness + "\nwhich is " + (thickness < current_thickness ? "larger":"smaller") + " than\nthe desired " + thickness + " for each stack slice.\nAdjust current layer's thickness to " + thickness + " ?"); if (yn.cancelPressed()) { if (null != imp_stack_) flush(imp_stack); // was opened new finishedWorking(); return; } else if (yn.yesPressed()) { first_layer.setThickness(thickness); // The rest of layers, created new, will inherit the same thickness } } else { YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "WARNING", "There's more than one layer or the current layer is not empty\nso the thickness cannot be adjusted. Proceed anyway?"); if (!yn.yesPressed()) { finishedWorking(); return; } } } one_patch_per_layer = imp_stack.getStack().isVirtual() || 0 == gd.getNextChoiceIndex(); } if (null == imp_stack.getStack()) { Utils.showMessage("Not a stack."); finishedWorking(); return; } // WARNING: there are fundamental issues with calibration, because the Layer thickness is disconnected from the Calibration pixelDepth // set LayerSet calibration if there is no calibration boolean calibrate = true; if (ask_for_data && first_layer.getParent().isCalibrated()) { if (!ControlWindow.isGUIEnabled()) { Utils.log2("Loader.importStack: overriding LayerSet calibration with that of the imported stack."); } else { YesNoDialog yn = new YesNoDialog("Calibration", "The layer set is already calibrated. Override with the stack calibration values?"); if (!yn.yesPressed()) { calibrate = false; } } } if (calibrate) { first_layer.getParent().setCalibration(imp_stack.getCalibration()); } if (layer_width < imp_stack.getWidth() || layer_height < imp_stack.getHeight()) { expand_layer_set = true; } if (imp_stack.getStack().isVirtual()) { // do nothing } else if (null == filepath) { // try to get it from the original FileInfo final FileInfo fi = imp_stack.getOriginalFileInfo(); if (null != fi && null != fi.directory && null != fi.fileName) { filepath = fi.directory.replace('\\', '/'); if (!filepath.endsWith("/")) filepath += '/'; filepath += fi.fileName; } Utils.log2("Getting filepath from FileInfo: " + filepath); // check that file exists, otherwise save a copy in the storage folder if (null == filepath || (!filepath.startsWith("http://") && !new File(filepath).exists())) { filepath = handlePathlessImage(imp_stack); } } else { filepath = filepath.replace('\\', '/'); } // Import as Stack ZDisplayable object: if (!one_patch_per_layer) { Stack st = new Stack(first_layer.getProject(), new File(filepath).getName(), x, y, first_layer, filepath); first_layer.getParent().add(st); finishedWorking(); return; } // Place the first slice in the current layer, and then query the parent LayerSet for subsequent layers, and create them if not present. Patch last_patch = Loader.this.importStackAsPatches(first_layer.getProject(), first_layer, x, y, imp_stack, null != imp_stack_ && null != imp_stack_.getCanvas(), filepath); if (null != last_patch) { last_patch.setLocked(lock_stack); Display.updateCheckboxes(last_patch.getLinkedGroup(null), DisplayablePanel.LOCK_STATE, true); } if (expand_layer_set) { last_patch.getLayer().getParent().setMinimumDimensions(); } Utils.log2("props: " + props); // check if it's an amira stack, then ask to import labels if (null != props && -1 == props.indexOf("Materials {") && -1 != props.indexOf("CoordType")) { YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "Amira Importer", "Import labels as well?"); if (yn.yesPressed()) { // select labels Collection<AreaList> alis = AmiraImporter.importAmiraLabels(first_layer, last_patch.getX(), last_patch.getY(), imp_stack.getOriginalFileInfo().directory); if (null != alis) { // import all created AreaList as nodes in the ProjectTree under a new imported_segmentations node first_layer.getProject().getProjectTree().insertSegmentations(first_layer.getProject(), alis); // link them to the images for (final AreaList ali : alis) { ali.linkPatches(); } } } } // it is safe not to flush the imp_stack, because all its resources are being used anyway (all the ImageProcessor), and it has no awt.Image. Unless it's being shown in ImageJ, and then it will be flushed on its own when the user closes its window. } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; return Bureaucrat.createAndStart(worker, first_layer.getProject()); } public String handlePathlessImage(ImagePlus imp) { return null; } protected Patch importStackAsPatches(final Project project, final Layer first_layer, final ImagePlus stack, final boolean as_copy, String filepath) { return importStackAsPatches(project, first_layer, Double.MAX_VALUE, Double.MAX_VALUE, stack, as_copy, filepath); } abstract protected Patch importStackAsPatches(final Project project, final Layer first_layer, final double x, final double y, final ImagePlus stack, final boolean as_copy, String filepath); protected String export(Project project, File fxml) { return export(project, fxml, true); } /** Exports the project and its images (optional); if export_images is true, it will be asked for confirmation anyway -beware: for FSLoader, images are not exported since it doesn't own them; only their path.*/ protected String export(final Project project, final File fxml, boolean export_images) { releaseToFit(MIN_FREE_BYTES); String path = null; if (null == project || null == fxml) return null; try { if (export_images && !(this instanceof FSLoader)) { final YesNoCancelDialog yn = ini.trakem2.ControlWindow.makeYesNoCancelDialog("Export images?", "Export images as well?"); if (yn.cancelPressed()) return null; if (yn.yesPressed()) export_images = true; else export_images = false; // 'no' option } // 1 - get headers in DTD format StringBuffer sb_header = new StringBuffer("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<!DOCTYPE ").append(project.getDocType()).append(" [\n"); final HashSet hs = new HashSet(); project.exportDTD(sb_header, hs, "\t"); sb_header.append("] >\n\n"); // 2 - fill in the data String patches_dir = null; if (export_images) { patches_dir = makePatchesDir(fxml); } // Write first to a tmp file, then remove the existing XML and move the tmp to that name // In this way, if there is an error while writing, the existing XML is not destroyed. // EXCEPT for Windows, because java cannot rename the file in any of the ways I've tried (directly, deleting it first, deleting and waiting and then renaming). // See this amazingly old bug (1998): http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4017593 final File ftmp = IJ.isWindows() ? fxml : new File(new StringBuilder(fxml.getAbsolutePath()).append(".tmp").toString()); java.io.Writer writer = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(ftmp)), "8859_1"); try { writer.write(sb_header.toString()); sb_header = null; project.exportXML(writer, "", patches_dir); writer.flush(); // make sure all buffered chars are written // On success, rename .xml.tmp to .xml if (!IJ.isWindows()) { if (fxml.exists()) { if (!fxml.delete()) { Utils.logAll("ERROR: could not delete existing XML file!"); return null; } if (!ftmp.renameTo(fxml)) { Utils.logAll("ERROR: could not rename .xml.tmp file to .xml!"); return null; } } else if (!ftmp.renameTo(fxml)) { Utils.logAll("ERROR: could not rename .xml.tmp file to .xml!"); return null; } } // On successful renaming, then: setChanged(false); path = fxml.getAbsolutePath().replace('\\', '/'); } catch (Exception e) { Utils.log("FAILED to save the file at " + fxml); IJError.print(e); path = null; } finally { writer.close(); writer = null; } // Remove the patches_dir if empty (can happen when doing a "save" on a FSLoader project if no new Patch have been created that have no path. if (export_images) { File fpd = new File(patches_dir); if (fpd.exists() && fpd.isDirectory()) { // check if it contains any files File[] ff = fpd.listFiles(); boolean rm = true; for (int k=0; k<ff.length; k++) { if (!ff[k].isHidden()) { // one non-hidden file found. rm = false; break; } } if (rm) { try { fpd.delete(); } catch (Exception e) { Utils.log2("Could not delete empty directory " + patches_dir); IJError.print(e); } } } } } catch (Exception e) { IJError.print(e); } ControlWindow.updateTitle(project); return path; } static public long countObjects(final LayerSet ls) { // estimate total number of bytes: large estimate is 500 bytes of xml text for each object int count = 1; // the given LayerSet itself for (Layer la : (ArrayList<Layer>)ls.getLayers()) { count += la.getNDisplayables(); for (Object ls2 : la.getDisplayables(LayerSet.class)) { // can't cast ArrayList<Displayable> to ArrayList<LayerSet> ???? count += countObjects((LayerSet)ls2); } } return count; } /** Calls saveAs() unless overriden. Returns full path to the xml file. */ public String save(Project project) { // yes the project is the same project pointer, which for some reason I never committed myself to place it in the Loader class as a field. String path = saveAs(project); if (null != path) setChanged(false); return path; } /** Save the project under a different name by choosing from a dialog, and exporting all images (will popup a YesNoCancelDialog to confirm exporting images.) */ public String saveAs(Project project) { return saveAs(project, null, true); } /** Exports to an XML file chosen by the user in a dialog if @param xmlpath is null. Images exist already in the file system, so none are exported. Returns the full path to the xml file. */ public String saveAs(Project project, String xmlpath, boolean export_images) { long size = countObjects(project.getRootLayerSet()) * 500; releaseToFit(size > MIN_FREE_BYTES ? size : MIN_FREE_BYTES); String storage_dir = getStorageFolder(); String mipmaps_dir = getMipMapsFolder(); // Select a file to export to File fxml = null == xmlpath ? Utils.chooseFile(storage_dir, null, ".xml") : new File(xmlpath); Hashtable<Long,String> copy = null; if (null == fxml) return null; else { copy = getPathsCopy(); makeAllPathsRelativeTo(fxml.getAbsolutePath().replace('\\', '/'), project); } String path = export(project, fxml, export_images); if (null != path) setChanged(false); else { // failed, so restore paths restorePaths(copy, mipmaps_dir, storage_dir); } // return path; } protected void makeAllPathsRelativeTo(final String xml_path, final Project project) {} protected Hashtable<Long,String> getPathsCopy() { return null; } protected void restorePaths(final Hashtable<Long,String> copy, final String mipmaps_folder, final String storage_folder) {} /** Meant to be overriden -- as is, will call saveAs(project, path, export_images = getClass() != FSLoader.class ). */ public String saveAs(String path, boolean overwrite) { if (null == path) return null; return export(Project.findProject(this), new File(path), this.getClass() != FSLoader.class); } /** Parses the xml_path and returns the folder in the same directory that has the same name plus "_images". Note there isn't an ending backslash. */ private String extractRelativeFolderPath(final File fxml) { try { String patches_dir = Utils.fixDir(fxml.getParent()) + fxml.getName(); if (patches_dir.toLowerCase().lastIndexOf(".xml") == patches_dir.length() - 4) { patches_dir = patches_dir.substring(0, patches_dir.lastIndexOf('.')); } return patches_dir + "_images"; // NOTE: no ending backslash } catch (Exception e) { IJError.print(e); return null; } } protected String makePatchesDir(final File fxml) { // Create a directory to store the images String patches_dir = extractRelativeFolderPath(fxml); // WITHOUT ending backslash if (null == patches_dir) return null; File dir = new File(patches_dir); String patches_dir2 = null; int i = 1; while (dir.exists()) { patches_dir2 = patches_dir + "_" + Integer.toString(i); dir = new File(patches_dir2); i++; } if (null != patches_dir2) patches_dir = patches_dir2; if (null == patches_dir) return null; try { dir.mkdir(); } catch (Exception e) { IJError.print(e); Utils.showMessage("Could not create a directory for the images."); return null; } return Utils.fixDir(patches_dir); } public String exportImage(final Patch patch, final String path, final boolean overwrite) { return exportImage(patch, fetchImagePlus(patch), path, overwrite); } /** Returns the path to the saved image, or null if not saved. */ public String exportImage(final Patch patch, final ImagePlus imp, final String path, final boolean overwrite) { // if !overwrite, save only if not there already if (null == path || null == imp || (!overwrite && new File(path).exists())) return null; try { if (imp.getNSlices() > 1) new FileSaver(imp).saveAsTiffStack(path); else new FileSaver(imp).saveAsTiff(path); } catch (Exception e) { Utils.log("Could not save an image for Patch #" + patch.getId() + " at: " + path); IJError.print(e); return null; } return path; } /** Whether any changes need to be saved. */ public boolean hasChanges() { return this.changes; } public void setChanged(final boolean changed) { this.changes = changed; //Utils.printCaller(this, 7); } /** Returns null unless overriden. This is intended for FSLoader projects. */ public String getPath(final Patch patch) { return null; } /** Returns null unless overriden. This is intended for FSLoader projects. */ public String getAbsolutePath(final Patch patch) { return null; } /** Returns null unless overriden. This is intended for FSLoader projects. */ public String getImageFilePath(final Patch p) { return null; } /** Does nothing unless overriden. */ public void setupMenuItems(final JMenu menu, final Project project) {} /** Test whether this Loader needs recurrent calls to a "save" of some sort, such as for the FSLoader. */ public boolean isAsynchronous() { // in the future, DBLoader may also be asynchronous return this.getClass() == FSLoader.class; } /** Throw away all awts and snaps that depend on this image, so that they will be recreated next time they are needed. */ public void decache(final ImagePlus imp) { synchronized(db_lock) { lock(); try { final long id = imps.getId(imp); Utils.log2("decaching " + id); if (Long.MIN_VALUE == id) return; mawts.removeAndFlush(id); } catch (Exception e) { IJError.print(e); } finally { unlock(); } } } protected final void preProcess(final Patch p, ImagePlus imp) { if (null == p) return; try { String path = preprocessors.get(p); if (null == path) return; if (null != imp) { // Prepare image for pre-processing imp.getProcessor().setMinAndMax(p.getMin(), p.getMax()); // for 8-bit and RGB images, your problem: setting min and max will expand the range. } else { imp = new ImagePlus(); // uninitialized: the script may generate its data } // Run the script ini.trakem2.scripting.PatchScript.run(p, imp, path); // Update Patch image properties: cache(p, imp); p.updatePixelProperties(); } catch (Exception e) { IJError.print(e); } } /////////////////////// /** List of jobs running on this Loader. */ private ArrayList al_jobs = new ArrayList(); private JPopupMenu popup_jobs = null; private final Object popup_lock = new Object(); private boolean popup_locked = false; /** Adds a new job to monitor.*/ public void addJob(Bureaucrat burro) { synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; al_jobs.add(burro); popup_locked = false; popup_lock.notifyAll(); } } public void removeJob(Bureaucrat burro) { synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; if (null != popup_jobs && popup_jobs.isVisible()) { popup_jobs.setVisible(false); } al_jobs.remove(burro); popup_locked = false; popup_lock.notifyAll(); } } public JPopupMenu getJobsPopup(Display display) { synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; this.popup_jobs = new JPopupMenu("Cancel jobs:"); int i = 1; for (Iterator it = al_jobs.iterator(); it.hasNext(); ) { Bureaucrat burro = (Bureaucrat)it.next(); JMenuItem item = new JMenuItem("Job " + i + ": " + burro.getTaskName()); item.addActionListener(display); popup_jobs.add(item); i++; } popup_locked = false; popup_lock.notifyAll(); } return popup_jobs; } /** Names as generated for popup menu items in the getJobsPopup method. If the name is null, it will cancel the last one. Runs in a separate thread so that it can immediately return. */ public void quitJob(final String name) { new Thread () { public void run() { setPriority(Thread.NORM_PRIORITY); Object ob = null; synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; if (null == name && al_jobs.size() > 0) { ob = al_jobs.get(al_jobs.size()-1); } else { int i = Integer.parseInt(name.substring(4, name.indexOf(':'))); if (i >= 1 && i <= al_jobs.size()) ob = al_jobs.get(i-1); // starts at 1 } popup_locked = false; popup_lock.notifyAll(); } if (null != ob) { // will wait until worker returns ((Bureaucrat)ob).quit(); // will require the lock } synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; popup_jobs = null; popup_locked = false; popup_lock.notifyAll(); } Utils.showStatus("Job canceled.", false); }}.start(); } public final void printMemState() { Utils.log2(new StringBuffer("mem in use: ").append((IJ.currentMemory() * 100.0f) / max_memory).append('%') .append("\n\timps: ").append(imps.size()) .append("\n\tmawts: ").append(mawts.size()) .toString()); } /** Fixes paths before presenting them to the file system, in an OS-dependent manner. */ protected final ImagePlus openImage(String path) { if (null == path) return null; try { // supporting samba networks if (path.startsWith("//")) { path = path.replace('/', '\\'); } // debug: Utils.log2("opening image " + path); //Utils.printCaller(this, 25); return openImagePlus(path, 0); } catch (Exception e) { Utils.log("Could not open image at " + path); e.printStackTrace(); return null; } } /** Tries up to MAX_RETRIES to open an ImagePlus at path if there is an OutOfMemoryError. */ protected final ImagePlus openImagePlus(final String path) { return openImagePlus(path, 0); } private final ImagePlus openImagePlus(final String path, int retries) { while (retries < MAX_RETRIES) try { IJ.redirectErrorMessages(); final ImagePlus imp = opener.openImage(path); if (null != imp) { imp.killRoi(); // newer ImageJ may store ROI in the file! } return imp; // TODO: Use windowless LOCI to bypass Opener class completely } catch (OutOfMemoryError oome) { Utils.log2("openImagePlus: recovering from OutOfMemoryError"); recoverOOME(); // No need to unlock db_lock: all image loading calls are by design outside the db_lock. Thread.yield(); // Retry: retries++; } catch (Throwable t) { // Don't retry IJError.print(t); break; } return null; } /** Equivalent to File.getName(), does not subtract the slice info from it.*/ protected final String getInternalFileName(Patch p) { final String path = getAbsolutePath(p); if (null == path) return null; int i = path.length() -1; // Safer than lastIndexOf: never returns -1 while (i > -1) { if ('/' == path.charAt(i)) { break; } i--; } return path.substring(i+1); } /** Equivalent to File.getName(), but subtracts the slice info from it if any.*/ public final String getFileName(final Patch p) { String name = getInternalFileName(p); int i = name.lastIndexOf("-----#slice="); if (-1 == i) return name; return name.substring(0, i); } /** Check if an awt exists to paint as a snap. */ public boolean isSnapPaintable(final long id) { synchronized (db_lock) { lock(); if (mawts.contains(id)) { unlock(); return true; } unlock(); } return false; } /** If mipmaps regeneration is enabled or not. */ protected boolean mipmaps_regen = true; // used to prevent generating them when, for example, importing a montage public void setMipMapsRegeneration(boolean b) { mipmaps_regen = b; } /** Does nothing unless overriden. */ public void flushMipMaps(boolean forget_dir_mipmaps) {} /** Does nothing unless overriden. */ public void flushMipMaps(final long id) {} /** Does nothing and returns false unless overriden. */ protected boolean generateMipMaps(final Patch patch) { return false; } /** Does nothing unless overriden. */ public Future<Boolean> removeMipMaps(final Patch patch) { return null; } /** Returns generateMipMaps(al, false). */ public Bureaucrat generateMipMaps(final ArrayList al) { return generateMipMaps(al, false); } /** Does nothing and returns null unless overriden. */ public Bureaucrat generateMipMaps(final ArrayList al, boolean overwrite) { return null; } /** Does nothing and returns false unless overriden. */ public boolean isMipMapsEnabled() { return false; } /** Does nothing and returns zero unless overriden. */ public int getClosestMipMapLevel(final Patch patch, int level) {return 0;} /** Does nothing and returns null unless overriden. */ protected Image fetchMipMapAWT(final Patch patch, final int level, final long n_bytes) { return null; } /** Does nothing and returns false unless overriden. */ public boolean checkMipMapFileExists(Patch p, double magnification) { return false; } public void adjustChannels(final Patch p, final int old_channels) { /* if (0xffffffff == old_channels) { // reuse any loaded mipmaps Hashtable<Integer,Image> ht = null; synchronized (db_lock) { lock(); ht = mawts.getAll(p.getId()); unlock(); } for (Map.Entry<Integer,Image> entry : ht.entrySet()) { // key is level, value is awt final int level = entry.getKey(); PatchLoadingLock plock = null; synchronized (db_lock) { lock(); plock = getOrMakePatchLoadingLock(p, level); unlock(); } synchronized (plock) { plock.lock(); // block loading of this file Image awt = null; try { awt = p.adjustChannels(entry.getValue()); } catch (Exception e) { IJError.print(e); if (null == awt) continue; } synchronized (db_lock) { lock(); mawts.replace(p.getId(), awt, level); removePatchLoadingLock(plock); unlock(); } plock.unlock(); } } } else { */ // flush away any loaded mipmap for the id synchronized (db_lock) { lock(); mawts.removeAndFlush(p.getId()); unlock(); } // when reloaded, the channels will be adjusted //} } static public ImageProcessor scaleImage(final ImagePlus imp, double mag, final boolean quality) { if (mag > 1) mag = 1; ImageProcessor ip = imp.getProcessor(); if (Math.abs(mag - 1) < 0.000001) return ip; // else, make a properly scaled image: // - gaussian blurred for best quality when resizing with nearest neighbor // - direct nearest neighbor otherwise final int w = ip.getWidth(); final int h = ip.getHeight(); // TODO releseToFit ! if (quality) { // apply proper gaussian filter double sigma = Math.sqrt(Math.pow(2, getMipMapLevel(mag, Math.max(imp.getWidth(), imp.getHeight()))) - 0.25); // sigma = sqrt(level^2 - 0.5^2) ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.convertToFloat().getPixels(), w, h), (float)sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax()); ip = ip.resize((int)(w * mag), (int)(h * mag)); // better while float return Utils.convertTo(ip, imp.getType(), false); } else { return ip.resize((int)(w * mag), (int)(h * mag)); } } static public ImageProcessor scaleImage(final ImagePlus imp, final int level, final boolean quality) { if (level <= 0) return imp.getProcessor(); // else, make a properly scaled image: // - gaussian blurred for best quality when resizing with nearest neighbor // - direct nearest neighbor otherwise ImageProcessor ip = imp.getProcessor(); final int w = ip.getWidth(); final int h = ip.getHeight(); final double mag = 1 / Math.pow(2, level); // TODO releseToFit ! if (quality) { // apply proper gaussian filter double sigma = Math.sqrt(Math.pow(2, level) - 0.25); // sigma = sqrt(level^2 - 0.5^2) ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.convertToFloat().getPixels(), w, h), (float)sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax()); ip = ip.resize((int)(w * mag), (int)(h * mag)); // better while float return Utils.convertTo(ip, imp.getType(), false); } else { return ip.resize((int)(w * mag), (int)(h * mag)); } } /* =========================== */ /** Serializes the given object into the path. Returns false on failure. */ public boolean serialize(final Object ob, final String path) { try { // 1 - Check that the parent chain of folders exists, and attempt to create it when not: File fdir = new File(path).getParentFile(); if (null == fdir) return false; fdir.mkdirs(); if (!fdir.exists()) { Utils.log2("Could not create folder " + fdir.getAbsolutePath()); return false; } // 2 - Serialize the given object: final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path)); out.writeObject(ob); out.close(); return true; } catch (Exception e) { IJError.print(e); } return false; } /** Attempts to find a file containing a serialized object. Returns null if no suitable file is found, or an error occurs while deserializing. */ public Object deserialize(final String path) { try { if (!new File(path).exists()) return null; final ObjectInputStream in = new ObjectInputStream(new FileInputStream(path)); final Object ob = in.readObject(); in.close(); return ob; } catch (Exception e) { //IJError.print(e); // too much output if a whole set is wrong e.printStackTrace(); } return null; } public void insertXMLOptions(StringBuffer sb_body, String indent) {} /** Homogenize contrast layer-wise, for all given layers. */ public Bureaucrat enhanceContrast(final Collection<Layer> layers) { if (null == layers || 0 == layers.size()) return null; return Bureaucrat.createAndStart(new Worker.Task("Enhancing contrast") { public void exec() { ContrastEnhancerWrapper cew = new ContrastEnhancerWrapper(); if (!cew.showDialog()) return; cew.applyLayerWise(layers); cew.shutdown(); } }, layers.iterator().next().getProject()); } /** Homogenize contrast for all patches, optionally using the @param reference Patch (can be null). */ public Bureaucrat enhanceContrast(final Collection<Displayable> patches, final Patch reference) { if (null == patches || 0 == patches.size()) return null; return Bureaucrat.createAndStart(new Worker.Task("Enhancing contrast") { public void exec() { ContrastEnhancerWrapper cew = new ContrastEnhancerWrapper(reference); if (!cew.showDialog()) return; cew.apply(patches); cew.shutdown(); } }, patches.iterator().next().getProject()); } public Bureaucrat setMinAndMax(final Collection<? extends Displayable> patches, final double min, final double max) { Worker worker = new Worker("Set min and max") { public void run() { try { startedWorking(); if (Double.isNaN(min) || Double.isNaN(max)) { Utils.log("WARNING:\nUnacceptable min and max values: " + min + ", " + max); finishedWorking(); return; } ArrayList<Future> fus = new ArrayList<Future>(); for (final Displayable d : patches) { if (d.getClass() != Patch.class) continue; Patch p = (Patch)d; p.setMinAndMax(min, max); fus.add(regenerateMipMaps(p)); } Utils.wait(fus); } catch (Exception e) { IJError.print(e); } finally { finishedWorking(); } } }; return Bureaucrat.createAndStart(worker, Project.findProject(this)); } public long estimateImageFileSize(final Patch p, final int level) { if (0 == level) { return (long)(p.getWidth() * p.getHeight() * 5 + 1024); // conservative } // else, compute scale final double scale = 1 / Math.pow(2, level); return (long)(p.getWidth() * scale * p.getHeight() * scale * 5 + 1024); // conservative } // Dummy class to provide access the notifyListeners from Image static private final class ImagePlusAccess extends ImagePlus { final int CLOSE = CLOSED; // from super class ImagePlus final int OPEN = OPENED; final int UPDATE = UPDATED; private Vector<ij.ImageListener> my_listeners; public ImagePlusAccess() { super(); try { java.lang.reflect.Field f = ImagePlus.class.getDeclaredField("listeners"); f.setAccessible(true); this.my_listeners = (Vector<ij.ImageListener>)f.get(this); } catch (Exception e) { IJError.print(e); } } public final void notifyListeners(final ImagePlus imp, final int action) { try { for (ij.ImageListener listener : my_listeners) { switch (action) { case CLOSED: listener.imageClosed(imp); break; case OPENED: listener.imageOpened(imp); break; case UPDATED: listener.imageUpdated(imp); break; } } } catch (Exception e) {} } } static private final ImagePlusAccess ipa = new ImagePlusAccess(); /** Workaround for ImageJ's ImagePlus.flush() method which calls the System.gc() unnecessarily.<br /> * A null pointer as argument is accepted. */ static public final void flush(final ImagePlus imp) { if (null == imp) return; final Roi roi = imp.getRoi(); if (null != roi) roi.setImage(null); //final ImageProcessor ip = imp.getProcessor(); // the nullifying makes no difference, and in low memory situations some bona fide imagepluses may end up failing on the calling method because of lack of time to grab the processor etc. //if (null != ip) ip.setPixels(null); ipa.notifyListeners(imp, ipa.CLOSE); } /** Returns the user's home folder unless overriden. */ public String getStorageFolder() { return System.getProperty("user.home").replace('\\', '/'); } public String getImageStorageFolder() { return getStorageFolder(); } /** Returns null unless overriden. */ public String getMipMapsFolder() { return null; } public Patch addNewImage(final ImagePlus imp) { return addNewImage(imp, 0, 0); } /** Mipmaps for this image are generated asynchronously. */ public Patch addNewImage(final ImagePlus imp, final double x, final double y) { String filename = imp.getTitle(); if (!filename.toLowerCase().endsWith(".tif")) filename += ".tif"; String path = getStorageFolder() + "/" + filename; new FileSaver(imp).saveAsTiff(path); Patch pa = new Patch(Project.findProject(this), imp.getTitle(), x, y, imp); addedPatchFrom(path, pa); if (isMipMapsEnabled()) regenerateMipMaps(pa); return pa; } public String makeProjectName() { return "Untitled " + ControlWindow.getTabIndex(Project.findProject(this)); } /** Will preload in the background as many as possible of the given images for the given magnification, if and only if (1) there is more than one CPU core available [and only the extra ones will be used], and (2) there is more than 1 image to preload. */ static private ExecutorService preloader = null; static private Collection<FutureTask> preloads = new Vector<FutureTask>(); static public final void setupPreloader(final ControlWindow master) { if (null == preloader) { int n = Runtime.getRuntime().availableProcessors()-1; if (0 == n) n = 1; // !@#$%^ preloader = Utils.newFixedThreadPool(n, "preloader"); } } static public final void destroyPreloader(final ControlWindow master) { preloads.clear(); if (null != preloader) { preloader.shutdownNow(); preloader = null; } } static public void preload(final Collection<Patch> patches, final double mag, final boolean repaint) { if (null == preloader) setupPreloader(null); synchronized (preloads) { for (final FutureTask fu : preloads) fu.cancel(false); } preloads.clear(); preloader.submit(new Runnable() { public void run() { for (final Patch p : patches) preload(p, mag, repaint); }}); } static public final FutureTask<Image> preload(final Patch p, final double mag, final boolean repaint) { final FutureTask[] fu = new FutureTask[1]; fu[0] = new FutureTask<Image>(new Callable<Image>() { public Image call() { //Utils.log2("preloading " + mag + " :: " + repaint + " :: " + p); try { if (p.getProject().getLoader().hs_unloadable.contains(p)) return null; if (repaint) { if (Display.willPaint(p, mag)) { final Image awt = p.getProject().getLoader().fetchImage(p, mag); if (null != awt) Display.repaint(p.getLayer(), p, p.getBoundingBox(null), 1, false); // not the navigator return awt; } } else { // just load it into the cache if possible return p.getProject().getLoader().fetchImage(p, mag); } } catch (Throwable t) { IJError.print(t); } finally { preloads.remove(fu[0]); } return null; } }); preloads.add(fu[0]); preloader.submit(fu[0]); return fu[0]; } /** Returns the highest mipmap level for which a mipmap image may have been generated given the dimensions of the Patch. The minimum that this method may return is zero. */ public static final int getHighestMipMapLevel(final Patch p) { /* int level = 0; int w = (int)p.getWidth(); int h = (int)p.getHeight(); while (w >= 64 && h >= 64) { w /= 2; h /= 2; level++; } return level; */ // Analytically: // For images of width or height of at least 32 pixels, need to test for log(64) like in the loop above // because this is NOT a do/while but a while, so we need to stop one step earlier. return (int)(0.5 + (Math.log(Math.min(p.getWidth(), p.getHeight())) - Math.log(64)) / Math.log(2)); // Same as: // return getHighestMipMapLevel(Math.min(p.getWidth(), p.getHeight())); } public static final int getHighestMipMapLevel(final double size) { return (int)(0.5 + (Math.log(size) - Math.log(64)) / Math.log(2)); } static public final int NEAREST_NEIGHBOR = 0; static public final int BILINEAR = 1; static public final int BICUBIC = 2; static public final int GAUSSIAN = 3; static public final int AREA_AVERAGING = 4; static public final String[] modes = new String[]{"Nearest neighbor", "Bilinear", "Bicubic", "Gaussian"}; //, "Area averaging"}; static public final int getMode(final String mode) { for (int i=0; i<modes.length; i++) { if (mode.equals(modes[i])) return i; } return 0; } /** Does nothing unless overriden. */ public Bureaucrat generateLayerMipMaps(final Layer[] la, final int starting_level) { return null; } /** Recover from an OutOfMemoryError: release 1/2 of all memory AND execute the garbage collector. */ public void recoverOOME() { releaseToFit(IJ.maxMemory() / 2); long start = System.currentTimeMillis(); long end = start; for (int i=0; i<3; i++) { System.gc(); Thread.yield(); end = System.currentTimeMillis(); if (end - start > 2000) break; // garbage collecion catched and is running. start = end; } } static public boolean canReadAndWriteTo(final String dir) { final File fsf = new File(dir); return fsf.canWrite() && fsf.canRead(); } /** Does nothing and returns null unless overridden. */ public String setImageFile(Patch p, ImagePlus imp) { return null; } public boolean isUnloadable(final Displayable p) { return hs_unloadable.contains(p); } public void removeFromUnloadable(final Displayable p) { hs_unloadable.remove(p); } protected static final BufferedImage createARGBImage(final int width, final int height, final int[] pix) { final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // In one step, set pixels that contain the alpha byte already: bi.setRGB( 0, 0, width, height, pix, 0, width ); return bi; } /** Embed the alpha-byte into an int[], changes the int[] in place and returns it */ protected static final int[] embedAlpha( final int[] pix, final byte[] alpha){ return embedAlpha(pix, alpha, null); } protected static final int[] embedAlpha( final int[] pix, final byte[] alpha, final byte[] outside) { if (null == outside) { if (null == alpha) return pix; for (int i=0; i<pix.length; ++i) pix[i] = (pix[i]&0x00ffffff) | ((alpha[i]&0xff)<<24); } else { for (int i=0; i<pix.length; ++i) { pix[i] = (pix[i]&0x00ffffff) | ( (outside[i]&0xff) != 255 ? 0 : ((alpha[i]&0xff)<<24) ); } } return pix; } /** Does nothing unless overriden. */ public void queueForMipmapRemoval(final Patch p, boolean yes) {} /** Does nothing unless overriden. */ public void tagForMipmapRemoval(final Patch p, boolean yes) {} /** Get the Universal Near-Unique Id for the project hosted by this loader. */ public String getUNUId() { // FSLoader overrides this method return Long.toString(System.currentTimeMillis()); } // FSLoader overrides this method public String getUNUIdFolder() { return "trakem2." + getUNUId() + "/"; } /** Does nothing and returns null unless overriden. */ public Future<Boolean> regenerateMipMaps(final Patch patch) { return null; } /** Does nothing and returns null unless overriden. */ public Bureaucrat regenerateMipMaps(final Collection<? extends Displayable> patches) { return null; } /** Read out the width,height of an image using LOCI BioFormats. */ static public Dimension getDimensions(final String path) { IFormatReader fr = null; try { fr = new ChannelSeparator(); fr.setId(path); return new Dimension(fr.getSizeX(), fr.getSizeY()); } catch (FormatException fe) { Utils.log("Error in reading image file at " + path + "\n" + fe); } catch (Exception e) { IJError.print(e); } finally { if (null != fr) try { fr.close(); } catch (IOException ioe) { Utils.log2("Could not close IFormatReader: " + ioe); } } return null; } public Dimension getDimensions(final Patch p) { String path = getAbsolutePath(p); int i = path.lastIndexOf("-----#slice="); if (-1 != i) path = path.substring(0, i); return Loader.getDimensions(path); } /** Table of preprocessor scripts. */ private Hashtable<Patch,String> preprocessors = new Hashtable<Patch,String>(); /** Set a preprocessor script that will be executed on the ImagePlus of the Patch when loading it, before TrakEM2 sees it at all. Automatically regenerates mipmaps * To remove the script, set it to null. */ public void setPreprocessorScriptPath(final Patch p, final String path) { setPreprocessorScriptPathSilently( p, path ); // If the ImagePlus is cached, it will not be preProcessed. // Merely running the preProcess on the cached image is no guarantee; threading competition may result in an unprocessed, newly loaded image. // Hence, decache right after setting the script, then update mipmaps decacheImagePlus(p.getId()); regenerateMipMaps(p); // queued } /** Set a preprocessor script that will be executed on the ImagePlus of the Patch when loading it, before TrakEM2 sees it at all. * To remove the script, set it to null. */ public void setPreprocessorScriptPathSilently(final Patch p, final String path) { if (null == path) preprocessors.remove(p); else preprocessors.put(p, path); } public String getPreprocessorScriptPath(final Patch p) { return preprocessors.get(p); } /** Returns @param path unless overriden. */ public String makeRelativePath(String path) { return path; } /** Does nothing unless overriden. */ public String getParentFolder() { return null; } // Will be shut down by Loader.destroy() private final ExecutorService exec = Utils.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), "loader-do-later"); public < T > Future< T > doLater( final Callable< T > fn ) { return exec.submit( fn ); } // Will be shut down by Loader.destroy() private final Dispatcher guiExec = new Dispatcher("GUI Executor"); /** Execute a GUI-related task later; it's the fn's responsability to do the call via SwingUtilities.invokeLater if necesary. */ public void doGUILater( final boolean swing, final Runnable fn ) { guiExec.exec( fn, swing ); } /** Make the border have an alpha of zero. */ public Bureaucrat maskBordersLayerWise(final Collection<Layer> layers, final int left, final int top, final int right, final int bottom) { return Bureaucrat.createAndStart(new Worker.Task("Crop borders") { public void exec() { ArrayList<Future> fus = new ArrayList<Future>(); for (final Layer layer : layers) { fus.addAll(maskBorders(left, top, right, bottom, layer.getDisplayables(Patch.class))); } Utils.wait(fus); } }, layers.iterator().next().getProject()); } /** Make the border have an alpha of zero. */ public Bureaucrat maskBorders(final Collection<Displayable> patches, final int left, final int top, final int right, final int bottom) { return Bureaucrat.createAndStart(new Worker.Task("Crop borders") { public void exec() { Utils.wait(maskBorders(left, top, right, bottom, patches)); } }, patches.iterator().next().getProject()); } /** Make the border have an alpha of zero. * @return the list of Future that represent the regeneration of the mipmaps of each Patch. */ public ArrayList<Future> maskBorders(final int left, final int top, final int right, final int bottom, final Collection<Displayable> patches) { ArrayList<Future> fus = new ArrayList<Future>(); for (final Displayable d : patches) { if (d.getClass() != Patch.class) continue; Patch p = (Patch) d; if (p.maskBorder(left, top, right, bottom)) { fus.add(regenerateMipMaps(p)); } } return fus; } /** Returns an ImageStack, one slice per region. */ public ImagePlus createFlyThrough(final List<Region> regions, final double magnification, final int type, final String dir) { final ExecutorService ex = Utils.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), "fly-through"); List<Future<ImagePlus>> fus = new ArrayList<Future<ImagePlus>>(); for (final Region r : regions) { fus.add(ex.submit(new Callable<ImagePlus>() { public ImagePlus call() { return getFlatImage(r.layer, r.r, magnification, 0xffffffff, type, Displayable.class, null, true, Color.black); } })); } Region r = regions.get(0); int w = (int)(r.r.width * magnification), h = (int)(r.r.height * magnification), size = regions.size(); ImageStack stack = null == dir ? new ImageStack(w, h) : new VirtualStack(w, h, null, dir); int digits = Integer.toString(size).length(); for (int i=0; i<size; i++) { try { if (Thread.currentThread().isInterrupted()) { ex.shutdownNow(); return null; } if (null == dir) { stack.addSlice(regions.get(i).layer.toString(), fus.get(i).get().getProcessor()); } else { StringBuilder name = new StringBuilder().append(i); while (name.length() < digits) name.insert(0, '0'); name.append(".png"); String filename = name.toString(); new FileSaver(fus.get(i).get()).saveAsPng(dir + filename); ((VirtualStack)stack).addSlice(filename); } } catch (Throwable t) { IJError.print(t); } } ex.shutdown(); return new ImagePlus("Fly-Through", stack); } }
true
true
static public final int getMipMapLevel(final double mag, final double size) { // check parameters if (mag > 1) return 0; // there is no level for mag > 1, so use mag = 1 if (mag <= 0 || Double.isNaN(mag)) { Utils.log2("ERROR: mag is " + mag); return 0; // survive } final int level = (int)(0.0001 + Math.log(1/mag) / Math.log(2)); // compensating numerical instability: 1/0.25 should be 2 eaxctly final int max_level = getHighestMipMapLevel(size); /* if (max_level > 6) { Utils.log2("ERROR max_level > 6: " + max_level + ", size: " + size); } */ return Math.min(level, max_level); /* int level = 0; double scale; static private ExecutorService exec = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors() ); while (true) { scale = 1 / Math.pow(2, level); //Utils.log2("scale, mag, level: " + scale + ", " + mag + ", " + level); if (Math.abs(scale - mag) < 0.00000001) { //if (scale == mag) { // floating-point typical behaviour break; } else if (scale < mag) { // provide the previous one level--; break; } // else, continue search level++; } return level; */ } public static final double maxDim(final Displayable d) { return Math.max(d.getWidth(), d.getHeight()); } public boolean isImagePlusCached(final Patch p) { synchronized (db_lock) { try { lock(); return null != imps.get(p.getId()); } catch (Exception e) { IJError.print(e); return false; } finally { unlock(); } } } /** Returns true if there is a cached awt image for the given mag and Patch id. */ public boolean isCached(final Patch p, final double mag) { synchronized (db_lock) { try { lock(); return mawts.contains(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); } catch (Exception e) { IJError.print(e); return false; } finally { unlock(); } } } public Image getCached(final long id, final int level) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestAbove(id, level); unlock(); } return awt; } /** Above or equal in size. */ public Image getCachedClosestAboveImage(final Patch p, final double mag) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestAbove(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); } return awt; } /** Below, not equal. */ public Image getCachedClosestBelowImage(final Patch p, final double mag) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestBelow(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); } return awt; } protected final class ImageLoadingLock extends Lock { final String key; ImageLoadingLock(final String key) { this.key = key; } } /** Table of dynamic locks, a single one per Patch if any. */ private final Hashtable<String,ImageLoadingLock> ht_plocks = new Hashtable<String,ImageLoadingLock>(); protected final ImageLoadingLock getOrMakeImageLoadingLock(final long id, final int level) { final String key = new StringBuffer().append(id).append('.').append(level).toString(); ImageLoadingLock plock = ht_plocks.get(key); if (null != plock) return plock; plock = new ImageLoadingLock(key); ht_plocks.put(key, plock); return plock; } protected final void removeImageLoadingLock(final ImageLoadingLock pl) { ht_plocks.remove(pl.key); } /** Calls fetchImage(p, mag) unless overriden. */ public Image fetchDataImage(Patch p, double mag) { return fetchImage(p, mag); } public Image fetchImage(Patch p) { return fetchImage(p, 1.0); } /** Fetch a suitable awt.Image for the given mag(nification). * If the mag is bigger than 1.0, it will return as if was 1.0. * Will return Loader.NOT_FOUND if, err, not found (probably an Exception will print along). */ public Image fetchImage(final Patch p, double mag) { if (mag > 1.0) mag = 1.0; // Don't want to create gigantic images! final int level = Loader.getMipMapLevel(mag, maxDim(p)); final int max_level = Loader.getHighestMipMapLevel(p); return fetchAWTImage(p, level > max_level ? max_level : level); } final public Image fetchAWTImage(final Patch p, int level) { // Below, the complexity of the synchronized blocks is to provide sufficient granularity. Keep in mind that only one thread at at a time can access a synchronized block for the same object (in this case, the db_lock), and thus calling lock() and unlock() is not enough. One needs to break the statement in as many synch blocks as possible for maximizing the number of threads concurrently accessing different parts of this function. // find an equal or larger existing pyramid awt final long id = p.getId(); ImageLoadingLock plock = null; synchronized (db_lock) { lock(); try { if (null == mawts) { return NOT_FOUND; // when lazy repainting after closing a project, the awts is null } if (level >= 0 && isMipMapsEnabled()) { // 1 - check if the exact level is cached final Image mawt = mawts.get(id, level); if (null != mawt) { //Utils.log2("returning cached exact mawt for level " + level); return mawt; } // releaseMemory2(); plock = getOrMakeImageLoadingLock(p.getId(), level); } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } Image mawt = null; long n_bytes = 0; // 2 - check if the exact file is present for the desired level if (level >= 0 && isMipMapsEnabled()) { synchronized (plock) { plock.lock(); synchronized (db_lock) { lock(); mawt = mawts.get(id, level); unlock(); } if (null != mawt) { plock.unlock(); return mawt; // was loaded by a different thread } // going to load: synchronized (db_lock) { lock(); n_bytes = estimateImageFileSize(p, level); alterMaxMem(-n_bytes); unlock(); } try { // Locks on db_lock to release memory when needed mawt = fetchMipMapAWT(p, level, n_bytes); } catch (Throwable t) { IJError.print(t); mawt = null; } synchronized (db_lock) { try { lock(); alterMaxMem(n_bytes); if (null != mawt) { //Utils.log2("returning exact mawt from file for level " + level); if (REGENERATING != mawt) { mawts.put(id, mawt, level); Display.repaintSnapshot(p); } return mawt; } // 3 - else, load closest level to it but still giving a larger image final int lev = getClosestMipMapLevel(p, level); // finds the file for the returned level, otherwise returns zero //Utils.log2("closest mipmap level is " + lev); if (lev >= 0) { mawt = mawts.getClosestAbove(id, lev); boolean newly_cached = false; if (null == mawt) { // reload existing scaled file mawt = fetchMipMapAWT2(p, lev, n_bytes); if (null != mawt) { mawts.put(id, mawt, lev); newly_cached = true; // means: cached was false, now it is } // else if null, the file did not exist or could not be regenerated or regeneration is off } //Utils.log2("from getClosestMipMapLevel: mawt is " + mawt); if (null != mawt) { if (newly_cached) Display.repaintSnapshot(p); //Utils.log2("returning from getClosestMipMapAWT with level " + lev); return mawt; } } else if (ERROR_PATH_NOT_FOUND == lev) { mawt = NOT_FOUND; } } catch (Exception e) { IJError.print(e); } finally { removeImageLoadingLock(plock); unlock(); plock.unlock(); } } } } // level is zero or nonsensically lower than zero, or was not found //Utils.log2("not found!"); synchronized (db_lock) { try { lock(); // 4 - check if any suitable level is cached (whithout mipmaps, it may be the large image) mawt = mawts.getClosestAbove(id, level); if (null != mawt) { //Utils.log2("returning from getClosest with level " + level); return mawt; } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } // 5 - else, fetch the (perhaps) transformed ImageProcessor and make an image from it of the proper size and quality if (hs_unloadable.contains(p)) return NOT_FOUND; synchronized (db_lock) { try { lock(); releaseMemory2(); plock = getOrMakeImageLoadingLock(p.getId(), level); } catch (Exception e) { return NOT_FOUND; } finally { unlock(); } } synchronized (plock) { try { plock.lock(); // Check if a previous call made it while waiting: mawt = mawts.getClosestAbove(id, level); if (null != mawt) { synchronized (db_lock) { lock(); removeImageLoadingLock(plock); unlock(); } return mawt; } // Else, create the mawt: plock.unlock(); Patch.PatchImage pai = p.createTransformedImage(); plock.lock(); if (null != pai && null != pai.target) { final ImageProcessor ip = pai.target; ip.setMinAndMax(p.getMin(), p.getMax()); ByteProcessor alpha_mask = pai.mask; // can be null; final ByteProcessor outside_mask = pai.outside; // can be null if (null == alpha_mask) { alpha_mask = outside_mask; } pai = null; if (null != alpha_mask) { mawt = createARGBImage(ip.getWidth(), ip.getHeight(), embedAlpha((int[])ip.convertToRGB().getPixels(), (byte[])alpha_mask.getPixels(), null == outside_mask ? null : (byte[])outside_mask.getPixels())); } else { mawt = ip.createImage(); } } } catch (Exception e) { Utils.log2("Could not create an image for Patch " + p); mawt = null; } finally { plock.unlock(); } } synchronized (db_lock) { try { lock(); if (null != mawt) { mawts.put(id, mawt, level); Display.repaintSnapshot(p); //Utils.log2("Created mawt from scratch."); return mawt; } } catch (Exception e) { IJError.print(e); } finally { removeImageLoadingLock(plock); unlock(); } } return NOT_FOUND; } /** Returns null.*/ public ByteProcessor fetchImageMask(final Patch p) { return null; } public String getAlphaPath(final Patch p) { return null; } /** Does nothing unless overriden. */ public void storeAlphaMask(final Patch p, final ByteProcessor fp) {} /** Does nothing unless overriden. */ public boolean removeAlphaMask(final Patch p) { return false; } /** Must be called within synchronized db_lock. */ private final Image fetchMipMapAWT2(final Patch p, final int level, final long n_bytes) { final long size = estimateImageFileSize(p, level); alterMaxMem(-size); unlock(); Image mawt = null; try { mawt = fetchMipMapAWT(p, level, n_bytes); // locks on db_lock } catch (Throwable e) { IJError.print(e); } lock(); alterMaxMem(size); return mawt; } /** Simply reads from the cache, does no reloading at all. If the ImagePlus is not found in the cache, it returns null and the burden is on the calling method to do reconstruct it if necessary. This is intended for the LayerStack. */ public ImagePlus getCachedImagePlus(final long id) { synchronized(db_lock) { ImagePlus imp = null; lock(); imp = imps.get(id); unlock(); return imp; } } abstract public ImagePlus fetchImagePlus(Patch p); /** Returns null unless overriden. */ public ImageProcessor fetchImageProcessor(Patch p) { return null; } public ImagePlus fetchImagePlus( Stack p ) { return null; } abstract public Object[] fetchLabel(DLabel label); /**Returns the ImagePlus as a zipped InputStream of bytes; the InputStream has to be closed by whoever is calling this method. */ protected InputStream createZippedStream(ImagePlus imp) throws Exception { FileInfo fi = imp.getFileInfo(); Object info = imp.getProperty("Info"); if (info != null && (info instanceof String)) { fi.info = (String)info; } if (null == fi.description) { fi.description = new ij.io.FileSaver(imp).getDescriptionString(); } //see whether this is a stack or not /* //never the case in my program if (fi.nImages > 1) { IJ.log("saving a stack!"); //virtual stacks would be supported? I don't think so because the FileSaver.saveAsTiffStack(String path) doesn't. if (fi.pixels == null && imp.getStack().isVirtual()) { //don't save it! IJ.showMessage("Virtual stacks not supported."); return false; } //setup stack things as in FileSaver.saveAsTiffStack(String path) fi.sliceLabels = imp.getStack().getSliceLabels(); } */ TiffEncoder te = new TiffEncoder(fi); ByteArrayInputStream i_stream = null; ByteArrayOutputStream o_bytes = new ByteArrayOutputStream(); DataOutputStream o_stream = null; try { /* // works, but not significantly faster and breaks older databases (can't read zipped images properly) byte[] bytes = null; // compress in RAM o_stream = new DataOutputStream(new BufferedOutputStream(o_bytes)); te.write(o_stream); o_stream.flush(); o_stream.close(); Deflater defl = new Deflater(); byte[] unzipped_bytes = o_bytes.toByteArray(); defl.setInput(unzipped_bytes); defl.finish(); bytes = new byte[unzipped_bytes.length]; // this length *should* be enough int length = defl.deflate(bytes); if (length < unzipped_bytes.length) { byte[] bytes2 = new byte[length]; System.arraycopy(bytes, 0, bytes2, 0, length); bytes = bytes2; } */ // old, creates temp file o_bytes = new ByteArrayOutputStream(); // clearing ZipOutputStream zos = new ZipOutputStream(o_bytes); o_stream = new DataOutputStream(new BufferedOutputStream(zos)); zos.putNextEntry(new ZipEntry(imp.getTitle())); te.write(o_stream); o_stream.flush(); //this was missing and was 1) truncating the Path images and 2) preventing the snapshots (which are very small) to be saved at all!! o_stream.close(); // this should ensure the flush above anyway. This can work because closing a ByteArrayOutputStream has no effect. byte[] bytes = o_bytes.toByteArray(); //Utils.showStatus("Zipping " + bytes.length + " bytes...", false); //Utils.debug("Zipped ImagePlus byte array size = " + bytes.length); i_stream = new ByteArrayInputStream(bytes); } catch (Exception e) { Utils.log("Loader: ImagePlus NOT zipped! Problems at writing the ImagePlus using the TiffEncoder.write(dos) :\n " + e); //attempt to cleanup: try { if (null != o_stream) o_stream.close(); if (null != i_stream) i_stream.close(); } catch (IOException ioe) { Utils.log("Loader: Attempt to clean up streams failed."); IJError.print(ioe); } return null; } return i_stream; } /** A dialog to open a stack, making sure there is enough memory for it. */ synchronized public ImagePlus openStack() { final OpenDialog od = new OpenDialog("Select stack", OpenDialog.getDefaultDirectory(), null); String file_name = od.getFileName(); if (null == file_name || file_name.toLowerCase().startsWith("null")) return null; String dir = od.getDirectory().replace('\\', '/'); if (!dir.endsWith("/")) dir += "/"; File f = new File(dir + file_name); if (!f.exists()) { Utils.showMessage("File " + dir + file_name + " does not exist."); return null; } // avoid opening trakem2 projects if (file_name.toLowerCase().endsWith(".xml")) { Utils.showMessage("Cannot import " + file_name + " as a stack."); return null; } // estimate file size: assumes an uncompressed tif, or a zipped tif with an average compression ratio of 2.5 long size = f.length() / 1024; // in megabytes if (file_name.length() -4 == file_name.toLowerCase().lastIndexOf(".zip")) { size = (long)(size * 2.5); // 2.5 is a reasonable compression ratio estimate based on my experience } int max_iterations = 15; while (enoughFreeMemory(size)) { if (0 == max_iterations) { // leave it to the Opener class to throw an OutOfMemoryError if so. break; } max_iterations--; releaseMemory(); } ImagePlus imp_stack = null; try { IJ.redirectErrorMessages(); imp_stack = openImagePlus(f.getCanonicalPath()); } catch (Exception e) { IJError.print(e); return null; } if (null == imp_stack) { Utils.showMessage("Can't open the stack."); return null; } else if (1 == imp_stack.getStackSize()) { Utils.showMessage("Not a stack!"); return null; } return imp_stack; // the open... command } public Bureaucrat importSequenceAsGrid(Layer layer) { return importSequenceAsGrid(layer, null); } public Bureaucrat importSequenceAsGrid(final Layer layer, String dir) { return importSequenceAsGrid(layer, dir, null); } /** Open one of the images to find out the dimensions, and get a good guess at what is the desirable scale for doing phase- and cross-correlations with about 512x512 images. */ private int getCCScaleGuess(final File images_dir, final String[] all_images) { try { if (null != all_images && all_images.length > 0) { Utils.showStatus("Opening one image ... ", false); String sdir = images_dir.getAbsolutePath().replace('\\', '/'); if (!sdir.endsWith("/")) sdir += "/"; IJ.redirectErrorMessages(); ImagePlus imp = openImagePlus(sdir + all_images[0]); if (null != imp) { int w = imp.getWidth(); int h = imp.getHeight(); flush(imp); imp = null; int cc_scale = (int)((512.0 / (w > h ? w : h)) * 100); if (cc_scale > 100) return 100; return cc_scale; } } } catch (Exception e) { Utils.log2("Could not get an estimate for the optimal scale."); } return 25; } /** Import a sequence of images as a grid, and put them in the layer. If the directory (@param dir) is null, it'll be asked for. The image_file_names can be null, and in any case it's only the names, not the paths. */ public Bureaucrat importSequenceAsGrid(final Layer first_layer, String dir, final String[] image_file_names) { String[] all_images = null; String file = null; // first file File images_dir = null; if (null != dir && null != image_file_names) { all_images = image_file_names; images_dir = new File(dir); } else if (null == dir) { String[] dn = Utils.selectFile("Select first image"); if (null == dn) return null; dir = dn[0]; file = dn[1]; images_dir = new File(dir); } else { images_dir = new File(dir); if (!(images_dir.exists() && images_dir.isDirectory())) { Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir); return null; } } if (null == image_file_names) all_images = images_dir.list(new ini.trakem2.io.ImageFileFilter("", null)); if (null == file && all_images.length > 0) { file = all_images[0]; } int n_max = all_images.length; // reasonable estimate int side = (int)Math.floor(Math.sqrt(n_max)); GenericDialog gd = new GenericDialog("Conventions"); gd.addStringField("file_name_matches: ", ""); gd.addNumericField("first_image: ", 1, 0); gd.addNumericField("last_image: ", n_max, 0); gd.addCheckbox("Reverse list order", false); gd.addNumericField("number_of_rows: ", side, 0); gd.addNumericField("number_of_columns: ", side, 0); gd.addNumericField("number_of_slices: ", 1, 0); gd.addMessage("The top left coordinate for the imported grid:"); gd.addNumericField("base_x: ", 0, 3); gd.addNumericField("base_y: ", 0, 3); gd.addMessage("Amount of image overlap, in pixels"); gd.addNumericField("bottom-top overlap: ", 0, 2); //as asked by Joachim Walter gd.addNumericField("left-right overlap: ", 0, 2); gd.addCheckbox("link images", false); gd.addCheckbox("montage", true); gd.addChoice("stitching_rule: ", StitchingTEM.rules, StitchingTEM.rules[0]); gd.addCheckbox("homogenize_contrast", false); final Component[] c = { //(Component)gd.getSliders().get(gd.getSliders().size()-2), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-2), //(Component)gd.getSliders().get(gd.getSliders().size()-1), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-1), (Component)gd.getChoices().get(gd.getChoices().size()-1) }; // enable the checkbox to control the slider and its associated numeric field: Utils.addEnablerListener((Checkbox)gd.getCheckboxes().get(gd.getCheckboxes().size()-2), c, null); //gd.addCheckbox("Apply non-linear deformation", false); gd.showDialog(); if (gd.wasCanceled()) return null; final String regex = gd.getNextString(); Utils.log2(new StringBuffer("using regex: ").append(regex).toString()); // avoid destroying backslashes int first = (int)gd.getNextNumber(); if (first < 1) first = 1; int last = (int)gd.getNextNumber(); if (last < 1) last = 1; if (last < first) { Utils.showMessage("Last is smaller that first!"); return null; } final boolean reverse_order = gd.getNextBoolean(); final int n_rows = (int)gd.getNextNumber(); final int n_cols = (int)gd.getNextNumber(); final int n_slices = (int)gd.getNextNumber(); final double bx = gd.getNextNumber(); final double by = gd.getNextNumber(); double bt_overlap = gd.getNextNumber(); double lr_overlap = gd.getNextNumber(); final boolean link_images = gd.getNextBoolean(); final boolean stitch_tiles = gd.getNextBoolean(); final boolean homogenize_contrast = gd.getNextBoolean(); final int stitching_rule = gd.getNextChoiceIndex(); //boolean apply_non_linear_def = gd.getNextBoolean(); // Ensure tiles overlap if using SIFT if (StitchingTEM.FREE_RULE == stitching_rule) { if (bt_overlap <= 0) bt_overlap = 1; if (lr_overlap <= 0) lr_overlap = 1; } String[] file_names = null; if (null == image_file_names) { file_names = images_dir.list(new ini.trakem2.io.ImageFileFilter(regex, null)); Arrays.sort(file_names); //assumes 001, 002, 003 ... that style, since it does binary sorting of strings if (reverse_order) { // flip in place for (int i=file_names.length/2; i>-1; i--) { String tmp = file_names[i]; int j = file_names.length -1 -i; file_names[i] = file_names[j]; file_names[j] = tmp; } } } else { file_names = all_images; } if (0 == file_names.length) { Utils.showMessage("No images found."); return null; } // check if the selected image is in the list. Otherwise, shift selected image to the first of the included ones. boolean found_first = false; for (int i=0; i<file_names.length; i++) { if (file.equals(file_names[i])) { found_first = true; break; } } if (!found_first) { file = file_names[0]; Utils.log("Using " + file + " as the reference image for size."); } // crop list if (last > file_names.length) last = file_names.length -1; if (first < 1) first = 1; if (1 != first || last != file_names.length) { Utils.log("Cropping list."); String[] file_names2 = new String[last - first + 1]; System.arraycopy(file_names, first -1, file_names2, 0, file_names2.length); file_names = file_names2; } // should be multiple of rows and cols and slices if (file_names.length != n_rows * n_cols * n_slices) { Utils.log("ERROR: rows * cols * slices does not match with the number of selected images."); Utils.log("n_images:" + file_names.length + " rows,cols,slices : " + n_rows + "," + n_cols + "," + n_slices + " total=" + n_rows*n_cols*n_slices); return null; } // I luv java final String[] file_names_ = file_names; final String dir_ = dir; final String file_ = file; // the first file final double bt_overlap_ = bt_overlap; final double lr_overlap_ = lr_overlap; return Bureaucrat.createAndStart(new Worker.Task("Importing", true) { public void exec() { StitchingTEM.PhaseCorrelationParam pc_param = null; // Slice up list: for (int sl=0; sl<n_slices; sl++) { if (Thread.currentThread().isInterrupted() || hasQuitted()) return; Utils.log("Importing " + (sl+1) + "/" + n_slices); int start = sl * n_rows * n_cols; ArrayList cols = new ArrayList(); for (int i=0; i<n_cols; i++) { String[] col = new String[n_rows]; for (int j=0; j<n_rows; j++) { col[j] = file_names_[start + j*n_cols + i]; } cols.add(col); } Layer layer = 0 == sl ? first_layer : first_layer.getParent().getLayer(first_layer.getZ() + first_layer.getThickness() * sl, first_layer.getThickness(), true); if (stitch_tiles && null == pc_param) { pc_param = new StitchingTEM.PhaseCorrelationParam(); pc_param.setup(layer); } insertGrid(layer, dir_, file_, n_rows*n_cols, cols, bx, by, bt_overlap_, lr_overlap_, link_images, stitch_tiles, homogenize_contrast, stitching_rule, pc_param, this); } } }, first_layer.getProject()); } public Bureaucrat importGrid(Layer layer) { return importGrid(layer, null); } /** Import a grid of images and put them in the layer. If the directory (@param dir) is null, it'll be asked for. */ public Bureaucrat importGrid(final Layer layer, String dir) { try { String file = null; if (null == dir) { String[] dn = Utils.selectFile("Select first image"); if (null == dn) return null; dir = dn[0]; file = dn[1]; } String convention = "cdd"; // char digit digit boolean chars_are_columns = true; // examine file name /* if (file.matches("\\A[a-zA-Z]\\d\\d.*")) { // one letter, 2 numbers //means: // \A - beggining of input // [a-zA-Z] - any letter upper or lower case // \d\d - two consecutive digits // .* - any row of chars ini_grid_convention = true; } */ // ask for chars->rows, numbers->columns or viceversa GenericDialog gd = new GenericDialog("Conventions"); gd.addStringField("file_name_contains:", ""); gd.addNumericField("base_x: ", 0, 3); gd.addNumericField("base_y: ", 0, 3); gd.addMessage("Use: x(any), c(haracter), d(igit)"); gd.addStringField("convention: ", convention); final String[] cr = new String[]{"columns", "rows"}; gd.addChoice("characters are: ", cr, cr[0]); gd.addMessage("[File extension ignored]"); gd.addNumericField("bottom-top overlap: ", 0, 3); //as asked by Joachim Walter gd.addNumericField("left-right overlap: ", 0, 3); gd.addCheckbox("link_images", false); gd.addCheckbox("montage", false); gd.addChoice("stitching_rule: ", StitchingTEM.rules, StitchingTEM.rules[0]); gd.addCheckbox("homogenize_contrast", true); final Component[] c = { (Component)gd.getSliders().get(gd.getSliders().size()-2), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-2), (Component)gd.getSliders().get(gd.getSliders().size()-1), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-1), (Component)gd.getChoices().get(gd.getChoices().size()-1) }; // enable the checkbox to control the slider and its associated numeric field: Utils.addEnablerListener((Checkbox)gd.getCheckboxes().get(gd.getCheckboxes().size()-1), c, null); //gd.addCheckbox("Apply non-linear deformation", false); gd.showDialog(); if (gd.wasCanceled()) { return null; } //collect data final String regex = gd.getNextString(); // filter away files not containing this tag // the base x,y of the whole grid final double bx = gd.getNextNumber(); final double by = gd.getNextNumber(); //if (!ini_grid_convention) { convention = gd.getNextString().toLowerCase(); //} if (/*!ini_grid_convention && */ (null == convention || convention.equals("") || -1 == convention.indexOf('c') || -1 == convention.indexOf('d'))) { // TODO check that the convention has only 'cdx' chars and also that there is an island of 'c's and of 'd's only. Utils.showMessage("Convention '" + convention + "' needs both c(haracters) and d(igits), optionally 'x', and nothing else!"); return null; } chars_are_columns = (0 == gd.getNextChoiceIndex()); double bt_overlap = gd.getNextNumber(); double lr_overlap = gd.getNextNumber(); final boolean link_images = gd.getNextBoolean(); final boolean stitch_tiles = gd.getNextBoolean(); final boolean homogenize_contrast = gd.getNextBoolean(); final int stitching_rule = gd.getNextChoiceIndex(); //boolean apply_non_linear_def = gd.getNextBoolean(); // Ensure tiles overlap if using SIFT if (StitchingTEM.FREE_RULE == stitching_rule) { if (bt_overlap <= 0) bt_overlap = 1; if (lr_overlap <= 0) lr_overlap = 1; } //start magic //get ImageJ-openable files that comply with the convention File images_dir = new File(dir); if (!(images_dir.exists() && images_dir.isDirectory())) { Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir); return null; } final String[] file_names = images_dir.list(new ImageFileFilter(regex, convention)); if (null == file && file_names.length > 0) { // the 'selected' file file = file_names[0]; } Utils.showStatus("Adding " + file_names.length + " patches.", false); if (0 == file_names.length) { Utils.log("Zero files match the convention '" + convention + "'"); return null; } // How to: select all files, and order their names in a double array as they should be placed in the Display. Then place them, displacing by offset, and resizing if necessary. // gather image files: final Montage montage = new Montage(convention, chars_are_columns); montage.addAll(file_names); final ArrayList cols = montage.getCols(); // an array of Object[] arrays, of unequal length maybe, each containing a column of image file names // !@#$%^&* final String dir_ = dir; final double bt_overlap_ = bt_overlap; final double lr_overlap_ = lr_overlap; final String file_ = file; return Bureaucrat.createAndStart(new Worker.Task("Insert grid", true) { public void exec() { StitchingTEM.PhaseCorrelationParam pc_param = null; if (stitch_tiles) { pc_param = new StitchingTEM.PhaseCorrelationParam(); pc_param.setup(layer); } insertGrid(layer, dir_, file_, file_names.length, cols, bx, by, bt_overlap_, lr_overlap_, link_images, stitch_tiles, homogenize_contrast, stitching_rule, pc_param, this); }}, layer.getProject()); } catch (Exception e) { IJError.print(e); } return null; }
static public final int getMipMapLevel(final double mag, final double size) { // check parameters if (mag > 1) return 0; // there is no level for mag > 1, so use mag = 1 if (mag <= 0 || Double.isNaN(mag)) { Utils.log2("ERROR: mag is " + mag); return 0; // survive } final int level = (int)(0.0001 + Math.log(1/mag) / Math.log(2)); // compensating numerical instability: 1/0.25 should be 2 eaxctly final int max_level = getHighestMipMapLevel(size); /* if (max_level > 6) { Utils.log2("ERROR max_level > 6: " + max_level + ", size: " + size); } */ return Math.min(level, max_level); /* int level = 0; double scale; static private ExecutorService exec = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors() ); while (true) { scale = 1 / Math.pow(2, level); //Utils.log2("scale, mag, level: " + scale + ", " + mag + ", " + level); if (Math.abs(scale - mag) < 0.00000001) { //if (scale == mag) { // floating-point typical behaviour break; } else if (scale < mag) { // provide the previous one level--; break; } // else, continue search level++; } return level; */ } public static final double maxDim(final Displayable d) { return Math.max(d.getWidth(), d.getHeight()); } public boolean isImagePlusCached(final Patch p) { synchronized (db_lock) { try { lock(); return null != imps.get(p.getId()); } catch (Exception e) { IJError.print(e); return false; } finally { unlock(); } } } /** Returns true if there is a cached awt image for the given mag and Patch id. */ public boolean isCached(final Patch p, final double mag) { synchronized (db_lock) { try { lock(); return mawts.contains(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); } catch (Exception e) { IJError.print(e); return false; } finally { unlock(); } } } public Image getCached(final long id, final int level) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestAbove(id, level); unlock(); } return awt; } /** Above or equal in size. */ public Image getCachedClosestAboveImage(final Patch p, final double mag) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestAbove(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); } return awt; } /** Below, not equal. */ public Image getCachedClosestBelowImage(final Patch p, final double mag) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestBelow(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); } return awt; } protected final class ImageLoadingLock extends Lock { final String key; ImageLoadingLock(final String key) { this.key = key; } } /** Table of dynamic locks, a single one per Patch if any. */ private final Hashtable<String,ImageLoadingLock> ht_plocks = new Hashtable<String,ImageLoadingLock>(); protected final ImageLoadingLock getOrMakeImageLoadingLock(final long id, final int level) { final String key = new StringBuffer().append(id).append('.').append(level).toString(); ImageLoadingLock plock = ht_plocks.get(key); if (null != plock) return plock; plock = new ImageLoadingLock(key); ht_plocks.put(key, plock); return plock; } protected final void removeImageLoadingLock(final ImageLoadingLock pl) { ht_plocks.remove(pl.key); } /** Calls fetchImage(p, mag) unless overriden. */ public Image fetchDataImage(Patch p, double mag) { return fetchImage(p, mag); } public Image fetchImage(Patch p) { return fetchImage(p, 1.0); } /** Fetch a suitable awt.Image for the given mag(nification). * If the mag is bigger than 1.0, it will return as if was 1.0. * Will return Loader.NOT_FOUND if, err, not found (probably an Exception will print along). */ public Image fetchImage(final Patch p, double mag) { if (mag > 1.0) mag = 1.0; // Don't want to create gigantic images! final int level = Loader.getMipMapLevel(mag, maxDim(p)); final int max_level = Loader.getHighestMipMapLevel(p); return fetchAWTImage(p, level > max_level ? max_level : level); } final public Image fetchAWTImage(final Patch p, int level) { // Below, the complexity of the synchronized blocks is to provide sufficient granularity. Keep in mind that only one thread at at a time can access a synchronized block for the same object (in this case, the db_lock), and thus calling lock() and unlock() is not enough. One needs to break the statement in as many synch blocks as possible for maximizing the number of threads concurrently accessing different parts of this function. // find an equal or larger existing pyramid awt final long id = p.getId(); ImageLoadingLock plock = null; synchronized (db_lock) { lock(); try { if (null == mawts) { return NOT_FOUND; // when lazy repainting after closing a project, the awts is null } if (level >= 0 && isMipMapsEnabled()) { // 1 - check if the exact level is cached final Image mawt = mawts.get(id, level); if (null != mawt) { //Utils.log2("returning cached exact mawt for level " + level); return mawt; } // releaseMemory2(); plock = getOrMakeImageLoadingLock(p.getId(), level); } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } Image mawt = null; long n_bytes = 0; // 2 - check if the exact file is present for the desired level if (level >= 0 && isMipMapsEnabled()) { synchronized (plock) { plock.lock(); synchronized (db_lock) { lock(); mawt = mawts.get(id, level); unlock(); } if (null != mawt) { plock.unlock(); return mawt; // was loaded by a different thread } // going to load: synchronized (db_lock) { lock(); n_bytes = estimateImageFileSize(p, level); alterMaxMem(-n_bytes); unlock(); } try { // Locks on db_lock to release memory when needed mawt = fetchMipMapAWT(p, level, n_bytes); } catch (Throwable t) { IJError.print(t); mawt = null; } synchronized (db_lock) { try { lock(); alterMaxMem(n_bytes); if (null != mawt) { //Utils.log2("returning exact mawt from file for level " + level); if (REGENERATING != mawt) { mawts.put(id, mawt, level); Display.repaintSnapshot(p); } return mawt; } // 3 - else, load closest level to it but still giving a larger image final int lev = getClosestMipMapLevel(p, level); // finds the file for the returned level, otherwise returns zero //Utils.log2("closest mipmap level is " + lev); if (lev >= 0) { mawt = mawts.getClosestAbove(id, lev); boolean newly_cached = false; if (null == mawt) { // reload existing scaled file mawt = fetchMipMapAWT2(p, lev, n_bytes); if (null != mawt) { mawts.put(id, mawt, lev); newly_cached = true; // means: cached was false, now it is } // else if null, the file did not exist or could not be regenerated or regeneration is off } //Utils.log2("from getClosestMipMapLevel: mawt is " + mawt); if (null != mawt) { if (newly_cached) Display.repaintSnapshot(p); //Utils.log2("returning from getClosestMipMapAWT with level " + lev); return mawt; } } else if (ERROR_PATH_NOT_FOUND == lev) { mawt = NOT_FOUND; } } catch (Exception e) { IJError.print(e); } finally { removeImageLoadingLock(plock); unlock(); plock.unlock(); } } } } // level is zero or nonsensically lower than zero, or was not found //Utils.log2("not found!"); synchronized (db_lock) { try { lock(); // 4 - check if any suitable level is cached (whithout mipmaps, it may be the large image) mawt = mawts.getClosestAbove(id, level); if (null != mawt) { //Utils.log2("returning from getClosest with level " + level); return mawt; } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } // 5 - else, fetch the (perhaps) transformed ImageProcessor and make an image from it of the proper size and quality if (hs_unloadable.contains(p)) return NOT_FOUND; synchronized (db_lock) { try { lock(); releaseMemory2(); plock = getOrMakeImageLoadingLock(p.getId(), level); } catch (Exception e) { return NOT_FOUND; } finally { unlock(); } } synchronized (plock) { try { plock.lock(); // Check if a previous call made it while waiting: mawt = mawts.getClosestAbove(id, level); if (null != mawt) { synchronized (db_lock) { lock(); removeImageLoadingLock(plock); unlock(); } return mawt; } // Else, create the mawt: plock.unlock(); Patch.PatchImage pai = p.createTransformedImage(); plock.lock(); if (null != pai && null != pai.target) { final ImageProcessor ip = pai.target; ip.setMinAndMax(p.getMin(), p.getMax()); ByteProcessor alpha_mask = pai.mask; // can be null; final ByteProcessor outside_mask = pai.outside; // can be null if (null == alpha_mask) { alpha_mask = outside_mask; } pai = null; if (null != alpha_mask) { mawt = createARGBImage(ip.getWidth(), ip.getHeight(), embedAlpha((int[])ip.convertToRGB().getPixels(), (byte[])alpha_mask.getPixels(), null == outside_mask ? null : (byte[])outside_mask.getPixels())); } else { mawt = ip.createImage(); } } } catch (Exception e) { Utils.log2("Could not create an image for Patch " + p); mawt = null; } finally { plock.unlock(); } } synchronized (db_lock) { try { lock(); if (null != mawt) { mawts.put(id, mawt, level); Display.repaintSnapshot(p); //Utils.log2("Created mawt from scratch."); return mawt; } } catch (Exception e) { IJError.print(e); } finally { removeImageLoadingLock(plock); unlock(); } } return NOT_FOUND; } /** Returns null.*/ public ByteProcessor fetchImageMask(final Patch p) { return null; } public String getAlphaPath(final Patch p) { return null; } /** Does nothing unless overriden. */ public void storeAlphaMask(final Patch p, final ByteProcessor fp) {} /** Does nothing unless overriden. */ public boolean removeAlphaMask(final Patch p) { return false; } /** Must be called within synchronized db_lock. */ private final Image fetchMipMapAWT2(final Patch p, final int level, final long n_bytes) { final long size = estimateImageFileSize(p, level); alterMaxMem(-size); unlock(); Image mawt = null; try { mawt = fetchMipMapAWT(p, level, n_bytes); // locks on db_lock } catch (Throwable e) { IJError.print(e); } lock(); alterMaxMem(size); return mawt; } /** Simply reads from the cache, does no reloading at all. If the ImagePlus is not found in the cache, it returns null and the burden is on the calling method to do reconstruct it if necessary. This is intended for the LayerStack. */ public ImagePlus getCachedImagePlus(final long id) { synchronized(db_lock) { ImagePlus imp = null; lock(); imp = imps.get(id); unlock(); return imp; } } abstract public ImagePlus fetchImagePlus(Patch p); /** Returns null unless overriden. */ public ImageProcessor fetchImageProcessor(Patch p) { return null; } public ImagePlus fetchImagePlus( Stack p ) { return null; } abstract public Object[] fetchLabel(DLabel label); /**Returns the ImagePlus as a zipped InputStream of bytes; the InputStream has to be closed by whoever is calling this method. */ protected InputStream createZippedStream(ImagePlus imp) throws Exception { FileInfo fi = imp.getFileInfo(); Object info = imp.getProperty("Info"); if (info != null && (info instanceof String)) { fi.info = (String)info; } if (null == fi.description) { fi.description = new ij.io.FileSaver(imp).getDescriptionString(); } //see whether this is a stack or not /* //never the case in my program if (fi.nImages > 1) { IJ.log("saving a stack!"); //virtual stacks would be supported? I don't think so because the FileSaver.saveAsTiffStack(String path) doesn't. if (fi.pixels == null && imp.getStack().isVirtual()) { //don't save it! IJ.showMessage("Virtual stacks not supported."); return false; } //setup stack things as in FileSaver.saveAsTiffStack(String path) fi.sliceLabels = imp.getStack().getSliceLabels(); } */ TiffEncoder te = new TiffEncoder(fi); ByteArrayInputStream i_stream = null; ByteArrayOutputStream o_bytes = new ByteArrayOutputStream(); DataOutputStream o_stream = null; try { /* // works, but not significantly faster and breaks older databases (can't read zipped images properly) byte[] bytes = null; // compress in RAM o_stream = new DataOutputStream(new BufferedOutputStream(o_bytes)); te.write(o_stream); o_stream.flush(); o_stream.close(); Deflater defl = new Deflater(); byte[] unzipped_bytes = o_bytes.toByteArray(); defl.setInput(unzipped_bytes); defl.finish(); bytes = new byte[unzipped_bytes.length]; // this length *should* be enough int length = defl.deflate(bytes); if (length < unzipped_bytes.length) { byte[] bytes2 = new byte[length]; System.arraycopy(bytes, 0, bytes2, 0, length); bytes = bytes2; } */ // old, creates temp file o_bytes = new ByteArrayOutputStream(); // clearing ZipOutputStream zos = new ZipOutputStream(o_bytes); o_stream = new DataOutputStream(new BufferedOutputStream(zos)); zos.putNextEntry(new ZipEntry(imp.getTitle())); te.write(o_stream); o_stream.flush(); //this was missing and was 1) truncating the Path images and 2) preventing the snapshots (which are very small) to be saved at all!! o_stream.close(); // this should ensure the flush above anyway. This can work because closing a ByteArrayOutputStream has no effect. byte[] bytes = o_bytes.toByteArray(); //Utils.showStatus("Zipping " + bytes.length + " bytes...", false); //Utils.debug("Zipped ImagePlus byte array size = " + bytes.length); i_stream = new ByteArrayInputStream(bytes); } catch (Exception e) { Utils.log("Loader: ImagePlus NOT zipped! Problems at writing the ImagePlus using the TiffEncoder.write(dos) :\n " + e); //attempt to cleanup: try { if (null != o_stream) o_stream.close(); if (null != i_stream) i_stream.close(); } catch (IOException ioe) { Utils.log("Loader: Attempt to clean up streams failed."); IJError.print(ioe); } return null; } return i_stream; } /** A dialog to open a stack, making sure there is enough memory for it. */ synchronized public ImagePlus openStack() { final OpenDialog od = new OpenDialog("Select stack", OpenDialog.getDefaultDirectory(), null); String file_name = od.getFileName(); if (null == file_name || file_name.toLowerCase().startsWith("null")) return null; String dir = od.getDirectory().replace('\\', '/'); if (!dir.endsWith("/")) dir += "/"; File f = new File(dir + file_name); if (!f.exists()) { Utils.showMessage("File " + dir + file_name + " does not exist."); return null; } // avoid opening trakem2 projects if (file_name.toLowerCase().endsWith(".xml")) { Utils.showMessage("Cannot import " + file_name + " as a stack."); return null; } // estimate file size: assumes an uncompressed tif, or a zipped tif with an average compression ratio of 2.5 long size = f.length() / 1024; // in megabytes if (file_name.length() -4 == file_name.toLowerCase().lastIndexOf(".zip")) { size = (long)(size * 2.5); // 2.5 is a reasonable compression ratio estimate based on my experience } int max_iterations = 15; while (enoughFreeMemory(size)) { if (0 == max_iterations) { // leave it to the Opener class to throw an OutOfMemoryError if so. break; } max_iterations--; releaseMemory(); } ImagePlus imp_stack = null; try { IJ.redirectErrorMessages(); imp_stack = openImagePlus(f.getCanonicalPath()); } catch (Exception e) { IJError.print(e); return null; } if (null == imp_stack) { Utils.showMessage("Can't open the stack."); return null; } else if (1 == imp_stack.getStackSize()) { Utils.showMessage("Not a stack!"); return null; } return imp_stack; // the open... command } public Bureaucrat importSequenceAsGrid(Layer layer) { return importSequenceAsGrid(layer, null); } public Bureaucrat importSequenceAsGrid(final Layer layer, String dir) { return importSequenceAsGrid(layer, dir, null); } /** Open one of the images to find out the dimensions, and get a good guess at what is the desirable scale for doing phase- and cross-correlations with about 512x512 images. */ private int getCCScaleGuess(final File images_dir, final String[] all_images) { try { if (null != all_images && all_images.length > 0) { Utils.showStatus("Opening one image ... ", false); String sdir = images_dir.getAbsolutePath().replace('\\', '/'); if (!sdir.endsWith("/")) sdir += "/"; IJ.redirectErrorMessages(); ImagePlus imp = openImagePlus(sdir + all_images[0]); if (null != imp) { int w = imp.getWidth(); int h = imp.getHeight(); flush(imp); imp = null; int cc_scale = (int)((512.0 / (w > h ? w : h)) * 100); if (cc_scale > 100) return 100; return cc_scale; } } } catch (Exception e) { Utils.log2("Could not get an estimate for the optimal scale."); } return 25; } /** Import a sequence of images as a grid, and put them in the layer. If the directory (@param dir) is null, it'll be asked for. The image_file_names can be null, and in any case it's only the names, not the paths. */ public Bureaucrat importSequenceAsGrid(final Layer first_layer, String dir, final String[] image_file_names) { String[] all_images = null; String file = null; // first file File images_dir = null; if (null != dir && null != image_file_names) { all_images = image_file_names; images_dir = new File(dir); } else if (null == dir) { String[] dn = Utils.selectFile("Select first image"); if (null == dn) return null; dir = dn[0]; file = dn[1]; images_dir = new File(dir); } else { images_dir = new File(dir); if (!(images_dir.exists() && images_dir.isDirectory())) { Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir); return null; } } if (null == image_file_names) all_images = images_dir.list(new ini.trakem2.io.ImageFileFilter("", null)); if (null == file && all_images.length > 0) { file = all_images[0]; } int n_max = all_images.length; // reasonable estimate int side = (int)Math.floor(Math.sqrt(n_max)); GenericDialog gd = new GenericDialog("Conventions"); gd.addStringField("file_name_matches: ", ""); gd.addNumericField("first_image: ", 1, 0); gd.addNumericField("last_image: ", n_max, 0); gd.addCheckbox("Reverse list order", false); gd.addNumericField("number_of_rows: ", side, 0); gd.addNumericField("number_of_columns: ", side, 0); gd.addNumericField("number_of_slices: ", 1, 0); gd.addMessage("The top left coordinate for the imported grid:"); gd.addNumericField("base_x: ", 0, 3); gd.addNumericField("base_y: ", 0, 3); gd.addMessage("Amount of image overlap, in pixels"); gd.addNumericField("bottom-top overlap: ", 0, 2); //as asked by Joachim Walter gd.addNumericField("left-right overlap: ", 0, 2); gd.addCheckbox("link images", false); gd.addCheckbox("montage", true); gd.addChoice("stitching_rule: ", StitchingTEM.rules, StitchingTEM.rules[0]); gd.addCheckbox("homogenize_contrast", false); final Component[] c = { //(Component)gd.getSliders().get(gd.getSliders().size()-2), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-2), //(Component)gd.getSliders().get(gd.getSliders().size()-1), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-1), (Component)gd.getChoices().get(gd.getChoices().size()-1) }; //gd.addCheckbox("Apply non-linear deformation", false); gd.showDialog(); if (gd.wasCanceled()) return null; final String regex = gd.getNextString(); Utils.log2(new StringBuffer("using regex: ").append(regex).toString()); // avoid destroying backslashes int first = (int)gd.getNextNumber(); if (first < 1) first = 1; int last = (int)gd.getNextNumber(); if (last < 1) last = 1; if (last < first) { Utils.showMessage("Last is smaller that first!"); return null; } final boolean reverse_order = gd.getNextBoolean(); final int n_rows = (int)gd.getNextNumber(); final int n_cols = (int)gd.getNextNumber(); final int n_slices = (int)gd.getNextNumber(); final double bx = gd.getNextNumber(); final double by = gd.getNextNumber(); double bt_overlap = gd.getNextNumber(); double lr_overlap = gd.getNextNumber(); final boolean link_images = gd.getNextBoolean(); final boolean stitch_tiles = gd.getNextBoolean(); final boolean homogenize_contrast = gd.getNextBoolean(); final int stitching_rule = gd.getNextChoiceIndex(); //boolean apply_non_linear_def = gd.getNextBoolean(); // Ensure tiles overlap if using SIFT if (StitchingTEM.FREE_RULE == stitching_rule) { if (bt_overlap <= 0) bt_overlap = 1; if (lr_overlap <= 0) lr_overlap = 1; } String[] file_names = null; if (null == image_file_names) { file_names = images_dir.list(new ini.trakem2.io.ImageFileFilter(regex, null)); Arrays.sort(file_names); //assumes 001, 002, 003 ... that style, since it does binary sorting of strings if (reverse_order) { // flip in place for (int i=file_names.length/2; i>-1; i--) { String tmp = file_names[i]; int j = file_names.length -1 -i; file_names[i] = file_names[j]; file_names[j] = tmp; } } } else { file_names = all_images; } if (0 == file_names.length) { Utils.showMessage("No images found."); return null; } // check if the selected image is in the list. Otherwise, shift selected image to the first of the included ones. boolean found_first = false; for (int i=0; i<file_names.length; i++) { if (file.equals(file_names[i])) { found_first = true; break; } } if (!found_first) { file = file_names[0]; Utils.log("Using " + file + " as the reference image for size."); } // crop list if (last > file_names.length) last = file_names.length -1; if (first < 1) first = 1; if (1 != first || last != file_names.length) { Utils.log("Cropping list."); String[] file_names2 = new String[last - first + 1]; System.arraycopy(file_names, first -1, file_names2, 0, file_names2.length); file_names = file_names2; } // should be multiple of rows and cols and slices if (file_names.length != n_rows * n_cols * n_slices) { Utils.log("ERROR: rows * cols * slices does not match with the number of selected images."); Utils.log("n_images:" + file_names.length + " rows,cols,slices : " + n_rows + "," + n_cols + "," + n_slices + " total=" + n_rows*n_cols*n_slices); return null; } // I luv java final String[] file_names_ = file_names; final String dir_ = dir; final String file_ = file; // the first file final double bt_overlap_ = bt_overlap; final double lr_overlap_ = lr_overlap; return Bureaucrat.createAndStart(new Worker.Task("Importing", true) { public void exec() { StitchingTEM.PhaseCorrelationParam pc_param = null; // Slice up list: for (int sl=0; sl<n_slices; sl++) { if (Thread.currentThread().isInterrupted() || hasQuitted()) return; Utils.log("Importing " + (sl+1) + "/" + n_slices); int start = sl * n_rows * n_cols; ArrayList cols = new ArrayList(); for (int i=0; i<n_cols; i++) { String[] col = new String[n_rows]; for (int j=0; j<n_rows; j++) { col[j] = file_names_[start + j*n_cols + i]; } cols.add(col); } Layer layer = 0 == sl ? first_layer : first_layer.getParent().getLayer(first_layer.getZ() + first_layer.getThickness() * sl, first_layer.getThickness(), true); if (stitch_tiles && null == pc_param) { pc_param = new StitchingTEM.PhaseCorrelationParam(); pc_param.setup(layer); } insertGrid(layer, dir_, file_, n_rows*n_cols, cols, bx, by, bt_overlap_, lr_overlap_, link_images, stitch_tiles, homogenize_contrast, stitching_rule, pc_param, this); } } }, first_layer.getProject()); } public Bureaucrat importGrid(Layer layer) { return importGrid(layer, null); } /** Import a grid of images and put them in the layer. If the directory (@param dir) is null, it'll be asked for. */ public Bureaucrat importGrid(final Layer layer, String dir) { try { String file = null; if (null == dir) { String[] dn = Utils.selectFile("Select first image"); if (null == dn) return null; dir = dn[0]; file = dn[1]; } String convention = "cdd"; // char digit digit boolean chars_are_columns = true; // examine file name /* if (file.matches("\\A[a-zA-Z]\\d\\d.*")) { // one letter, 2 numbers //means: // \A - beggining of input // [a-zA-Z] - any letter upper or lower case // \d\d - two consecutive digits // .* - any row of chars ini_grid_convention = true; } */ // ask for chars->rows, numbers->columns or viceversa GenericDialog gd = new GenericDialog("Conventions"); gd.addStringField("file_name_contains:", ""); gd.addNumericField("base_x: ", 0, 3); gd.addNumericField("base_y: ", 0, 3); gd.addMessage("Use: x(any), c(haracter), d(igit)"); gd.addStringField("convention: ", convention); final String[] cr = new String[]{"columns", "rows"}; gd.addChoice("characters are: ", cr, cr[0]); gd.addMessage("[File extension ignored]"); gd.addNumericField("bottom-top overlap: ", 0, 3); //as asked by Joachim Walter gd.addNumericField("left-right overlap: ", 0, 3); gd.addCheckbox("link_images", false); gd.addCheckbox("montage", false); gd.addChoice("stitching_rule: ", StitchingTEM.rules, StitchingTEM.rules[0]); gd.addCheckbox("homogenize_contrast", true); final Component[] c = { (Component)gd.getSliders().get(gd.getSliders().size()-2), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-2), (Component)gd.getSliders().get(gd.getSliders().size()-1), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-1), (Component)gd.getChoices().get(gd.getChoices().size()-1) }; // enable the checkbox to control the slider and its associated numeric field: Utils.addEnablerListener((Checkbox)gd.getCheckboxes().get(gd.getCheckboxes().size()-1), c, null); //gd.addCheckbox("Apply non-linear deformation", false); gd.showDialog(); if (gd.wasCanceled()) { return null; } //collect data final String regex = gd.getNextString(); // filter away files not containing this tag // the base x,y of the whole grid final double bx = gd.getNextNumber(); final double by = gd.getNextNumber(); //if (!ini_grid_convention) { convention = gd.getNextString().toLowerCase(); //} if (/*!ini_grid_convention && */ (null == convention || convention.equals("") || -1 == convention.indexOf('c') || -1 == convention.indexOf('d'))) { // TODO check that the convention has only 'cdx' chars and also that there is an island of 'c's and of 'd's only. Utils.showMessage("Convention '" + convention + "' needs both c(haracters) and d(igits), optionally 'x', and nothing else!"); return null; } chars_are_columns = (0 == gd.getNextChoiceIndex()); double bt_overlap = gd.getNextNumber(); double lr_overlap = gd.getNextNumber(); final boolean link_images = gd.getNextBoolean(); final boolean stitch_tiles = gd.getNextBoolean(); final boolean homogenize_contrast = gd.getNextBoolean(); final int stitching_rule = gd.getNextChoiceIndex(); //boolean apply_non_linear_def = gd.getNextBoolean(); // Ensure tiles overlap if using SIFT if (StitchingTEM.FREE_RULE == stitching_rule) { if (bt_overlap <= 0) bt_overlap = 1; if (lr_overlap <= 0) lr_overlap = 1; } //start magic //get ImageJ-openable files that comply with the convention File images_dir = new File(dir); if (!(images_dir.exists() && images_dir.isDirectory())) { Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir); return null; } final String[] file_names = images_dir.list(new ImageFileFilter(regex, convention)); if (null == file && file_names.length > 0) { // the 'selected' file file = file_names[0]; } Utils.showStatus("Adding " + file_names.length + " patches.", false); if (0 == file_names.length) { Utils.log("Zero files match the convention '" + convention + "'"); return null; } // How to: select all files, and order their names in a double array as they should be placed in the Display. Then place them, displacing by offset, and resizing if necessary. // gather image files: final Montage montage = new Montage(convention, chars_are_columns); montage.addAll(file_names); final ArrayList cols = montage.getCols(); // an array of Object[] arrays, of unequal length maybe, each containing a column of image file names // !@#$%^&* final String dir_ = dir; final double bt_overlap_ = bt_overlap; final double lr_overlap_ = lr_overlap; final String file_ = file; return Bureaucrat.createAndStart(new Worker.Task("Insert grid", true) { public void exec() { StitchingTEM.PhaseCorrelationParam pc_param = null; if (stitch_tiles) { pc_param = new StitchingTEM.PhaseCorrelationParam(); pc_param.setup(layer); } insertGrid(layer, dir_, file_, file_names.length, cols, bx, by, bt_overlap_, lr_overlap_, link_images, stitch_tiles, homogenize_contrast, stitching_rule, pc_param, this); }}, layer.getProject()); } catch (Exception e) { IJError.print(e); } return null; }
diff --git a/src/nl/rug/gad/practicum2/AugmentingPath.java b/src/nl/rug/gad/practicum2/AugmentingPath.java index 7c24483..c5e6a6a 100644 --- a/src/nl/rug/gad/practicum2/AugmentingPath.java +++ b/src/nl/rug/gad/practicum2/AugmentingPath.java @@ -1,94 +1,97 @@ package nl.rug.gad.practicum2; import java.util.LinkedList; import java.util.List; import java.util.Queue; import nl.rug.gad.practicum2.Edge.EdgeStatus; import nl.rug.gad.practicum2.Vertex.VertexStatus; public class AugmentingPath { /* * g = graph s = source t = sink */ public static List<Edge> getAugmentedPathDFS(Graph g, Vertex s, Vertex t) { LinkedList<Edge> augmentedPath = new LinkedList<Edge>(); s.status = VertexStatus.EXPLORED; for (Edge e : s.outgoingEdges) { if (e.flow < e.capacity) { Vertex w = g.opposite(s, e); if (w.status == VertexStatus.UNEXPLORED) { e.status = EdgeStatus.DISCOVERY; e.forward = true; augmentedPath.add(e); augmentedPath.addAll(getAugmentedPathDFS(g, w, t)); } else { e.status = EdgeStatus.BACK; augmentedPath.remove(e); } } } for (Edge e : s.incomingEdges) { if (e.flow > 0) { // TODO: Non zero flow toch? Vertex w = g.opposite(s, e); if (w.status == VertexStatus.UNEXPLORED) { e.status = EdgeStatus.DISCOVERY; e.forward = false; augmentedPath.add(e); augmentedPath.addAll(getAugmentedPathDFS(g, w, t)); } else { e.status = EdgeStatus.BACK; augmentedPath.remove(e); } } } return augmentedPath; } public static List<Edge> getAugmentedPathBFS(Graph g, Vertex s, Vertex t) { List<Edge> path = new LinkedList<Edge>(); Queue<Vertex> vertexQueue = new LinkedList<Vertex>(); s.status = VertexStatus.EXPLORED; vertexQueue.add(s); Vertex w; while (!vertexQueue.isEmpty()) { w = vertexQueue.poll(); for (Edge e : w.outgoingEdges) { if (e.flow < e.capacity) { Vertex x = g.opposite(w, e); if (x.status == VertexStatus.UNEXPLORED) { vertexQueue.add(x); e.status = EdgeStatus.DISCOVERY; e.forward = true; path.add(e); - } + } else { + e.status = EdgeStatus.BACK; + augmentedPath.remove(e); + } } } for(Edge e : s.incomingEdges) { if(e.flow > 0) { //TODO:Verify. Vertex x = g.opposite(w, e); if(x.status == VertexStatus.UNEXPLORED) { e.status = EdgeStatus.DISCOVERY; e.forward = false; path.add(e); vertexQueue.add(x); } else { e.status = EdgeStatus.BACK; path.remove(e); } } } } return path; } }
true
true
public static List<Edge> getAugmentedPathBFS(Graph g, Vertex s, Vertex t) { List<Edge> path = new LinkedList<Edge>(); Queue<Vertex> vertexQueue = new LinkedList<Vertex>(); s.status = VertexStatus.EXPLORED; vertexQueue.add(s); Vertex w; while (!vertexQueue.isEmpty()) { w = vertexQueue.poll(); for (Edge e : w.outgoingEdges) { if (e.flow < e.capacity) { Vertex x = g.opposite(w, e); if (x.status == VertexStatus.UNEXPLORED) { vertexQueue.add(x); e.status = EdgeStatus.DISCOVERY; e.forward = true; path.add(e); } } } for(Edge e : s.incomingEdges) { if(e.flow > 0) { //TODO:Verify. Vertex x = g.opposite(w, e); if(x.status == VertexStatus.UNEXPLORED) { e.status = EdgeStatus.DISCOVERY; e.forward = false; path.add(e); vertexQueue.add(x); } else { e.status = EdgeStatus.BACK; path.remove(e); } } } } return path; }
public static List<Edge> getAugmentedPathBFS(Graph g, Vertex s, Vertex t) { List<Edge> path = new LinkedList<Edge>(); Queue<Vertex> vertexQueue = new LinkedList<Vertex>(); s.status = VertexStatus.EXPLORED; vertexQueue.add(s); Vertex w; while (!vertexQueue.isEmpty()) { w = vertexQueue.poll(); for (Edge e : w.outgoingEdges) { if (e.flow < e.capacity) { Vertex x = g.opposite(w, e); if (x.status == VertexStatus.UNEXPLORED) { vertexQueue.add(x); e.status = EdgeStatus.DISCOVERY; e.forward = true; path.add(e); } else { e.status = EdgeStatus.BACK; augmentedPath.remove(e); } } } for(Edge e : s.incomingEdges) { if(e.flow > 0) { //TODO:Verify. Vertex x = g.opposite(w, e); if(x.status == VertexStatus.UNEXPLORED) { e.status = EdgeStatus.DISCOVERY; e.forward = false; path.add(e); vertexQueue.add(x); } else { e.status = EdgeStatus.BACK; path.remove(e); } } } } return path; }
diff --git a/src/org/broeuschmeul/android/gps/bluetooth/provider/BlueetoothGpsManager.java b/src/org/broeuschmeul/android/gps/bluetooth/provider/BlueetoothGpsManager.java index c3f16ec..dbcc249 100644 --- a/src/org/broeuschmeul/android/gps/bluetooth/provider/BlueetoothGpsManager.java +++ b/src/org/broeuschmeul/android/gps/bluetooth/provider/BlueetoothGpsManager.java @@ -1,827 +1,833 @@ /* * Copyright (C) 2010, 2011 Herbert von Broeuschmeul * Copyright (C) 2010, 2011 BluetoothGPS4Droid Project * * This file is part of BluetoothGPS4Droid. * * BluetoothGPS4Droid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BluetoothGPS4Droid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BluetoothGPS4Droid. If not, see <http://www.gnu.org/licenses/>. */ package org.broeuschmeul.android.gps.bluetooth.provider; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.broeuschmeul.android.gps.internal.provider.R; import org.broeuschmeul.android.gps.nmea.util.NmeaParser; import org.broeuschmeul.android.gps.sirf.util.SirfUtils; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; //import android.bluetooth.BluetoothAdapter; //import android.bluetooth.BluetoothDevice; //import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.SharedPreferences; import android.content.Intent; import android.location.LocationManager; import android.location.GpsStatus.NmeaListener; import android.preference.PreferenceManager; import android.provider.Settings; import android.os.SystemClock; import android.util.Log; /** * This class is used to establish and manage the connection with the bluetooth GPS. * * @author Herbert von Broeuschmeul * */ public class BlueetoothGpsManager { /** * Tag used for log messages */ private static final String LOG_TAG = "BlueGPS"; /** * A utility class used to manage the communication with the bluetooth GPS whn the connection has been established. * It is used to read NMEA data from the GPS or to send SIRF III binary commands or SIRF III NMEA commands to the GPS. * You should run the main read loop in one thread and send the commands in a separate one. * * @author Herbert von Broeuschmeul * */ private class ConnectedGps extends Thread { /** * GPS bluetooth socket used for communication. */ private final File gpsDev ; /** * GPS InputStream from which we read data. */ private final InputStream in; /** * GPS output stream to which we send data (SIRF III binary commands). */ //private final OutputStream out; /** * GPS output stream to which we send data (SIRF III NMEA commands). */ //private final PrintStream out2; /** * A boolean which indicates if the GPS is ready to receive data. * In fact we consider that the GPS is ready when it begins to sends data... */ private boolean ready = false; public ConnectedGps(File gpsDev) { this.gpsDev = gpsDev; InputStream tmpIn = null; //OutputStream tmpOut = null; //PrintStream tmpOut2 = null; try { tmpIn = new FileInputStream(gpsDev); //tmpOut = new FileOutputStream(gpsDev); //if (tmpOut != null){ // tmpOut2 = new PrintStream(tmpOut, false, "US-ASCII"); //} } catch (IOException e) { Log.e(LOG_TAG, "error while getting socket streams", e); } in = tmpIn; //out = tmpOut; //out2 = tmpOut2; } public boolean isReady(){ return ready; } public void run() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(in,"US-ASCII")); String s; long now = SystemClock.uptimeMillis(); long lastRead = now; while((enabled) && (now < lastRead+30000 )){ if (reader.ready()){ s = reader.readLine(); Log.v(LOG_TAG, "data: "+System.currentTimeMillis()+" "+s); notifyNmeaSentence(s+"\r\n"); ready = true; lastRead = SystemClock.uptimeMillis(); } else { Log.d(LOG_TAG, "data: not ready "+System.currentTimeMillis()); SystemClock.sleep(500); } now = SystemClock.uptimeMillis(); } } catch (IOException e) { Log.e(LOG_TAG, "error while getting data", e); setMockLocationProviderOutOfService(); } finally { // cleanly closing everything... this.close(); disableIfNeeded(); } } /** * Write to the connected OutStream. * @param buffer The bytes to write */ // public void write(byte[] buffer) { // try { // do { // Thread.sleep(100); // } while ((enabled) && (! ready)); // if ((enabled) && (ready)){ // out.write(buffer); // out.flush(); // } // } catch (IOException e) { // Log.e(LOG_TAG, "Exception during write", e); // } catch (InterruptedException e) { // Log.e(LOG_TAG, "Exception during write", e); // } // } /** * Write to the connected OutStream. * @param buffer The data to write */ // public void write(String buffer) { // try { // do { // Thread.sleep(100); // } while ((enabled) && (! ready)); // if ((enabled) && (ready)){ // out2.print(buffer); // out2.flush(); // } // } catch (InterruptedException e) { // Log.e(LOG_TAG, "Exception during write", e); // } // } public void close(){ ready = false; try { Log.d(LOG_TAG, "closing Bluetooth GPS output sream"); in.close(); } catch (IOException e) { Log.e(LOG_TAG, "error while closing GPS NMEA output stream", e); } finally { // try { // Log.d(LOG_TAG, "closing Bluetooth GPS input streams"); // out2.close(); // out.close(); // } catch (IOException e) { // Log.e(LOG_TAG, "error while closing GPS input streams", e); // } finally { // try { // Log.d(LOG_TAG, "closing Bluetooth GPS socket"); // socket.close(); // } catch (IOException e) { // Log.e(LOG_TAG, "error while closing GPS socket", e); // } // } } } } private Service callingService; // private BluetoothSocket gpsSocket; private File gpsDev ; private String gpsDeviceAddress; private NmeaParser parser = new NmeaParser(10f); private boolean enabled = false; private ExecutorService notificationPool; private ScheduledExecutorService connectionAndReadingPool; private List<NmeaListener> nmeaListeners = Collections.synchronizedList(new LinkedList<NmeaListener>()); private LocationManager locationManager; private SharedPreferences sharedPreferences; private ConnectedGps connectedGps; private int disableReason = 0; private Notification connectionProblemNotification; private Notification serviceStoppedNotification; private Context appContext; private NotificationManager notificationManager; private int maxConnectionRetries; private int nbRetriesRemaining; private boolean connected = false; /** * @param callingService * @param deviceAddress * @param maxRetries */ public BlueetoothGpsManager(Service callingService, String deviceAddress, int maxRetries) { this.gpsDeviceAddress = deviceAddress; this.callingService = callingService; this.maxConnectionRetries = maxRetries; this.nbRetriesRemaining = 1+maxRetries; this.appContext = callingService.getApplicationContext(); locationManager = (LocationManager)callingService.getSystemService(Context.LOCATION_SERVICE); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(callingService); notificationManager = (NotificationManager)callingService.getSystemService(Context.NOTIFICATION_SERVICE); parser.setLocationManager(locationManager); connectionProblemNotification = new Notification(); connectionProblemNotification.icon = R.drawable.ic_stat_notify; Intent stopIntent = new Intent(BluetoothGpsProviderService.ACTION_STOP_GPS_PROVIDER); // PendingIntent stopPendingIntent = PendingIntent.getService(appContext, 0, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT); PendingIntent stopPendingIntent = PendingIntent.getService(appContext, 0, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT); connectionProblemNotification.contentIntent = stopPendingIntent; serviceStoppedNotification = new Notification(); serviceStoppedNotification.icon=R.drawable.ic_stat_notify; Intent restartIntent = new Intent(BluetoothGpsProviderService.ACTION_START_GPS_PROVIDER); PendingIntent restartPendingIntent = PendingIntent.getService(appContext, 0, restartIntent, PendingIntent.FLAG_CANCEL_CURRENT); serviceStoppedNotification.setLatestEventInfo(appContext, appContext.getString(R.string.service_closed_because_connection_problem_notification_title), appContext.getString(R.string.service_closed_because_connection_problem_notification), restartPendingIntent); } private void setDisableReason(int reasonId){ disableReason = reasonId; } /** * @return */ public int getDisableReason(){ return disableReason; } /** * @return true if the bluetooth GPS is enabled */ public synchronized boolean isEnabled() { return enabled; } /** * Enables the bluetooth GPS Provider. * @return */ public synchronized boolean enable() { notificationManager.cancel(R.string.service_closed_because_connection_problem_notification_title); if (! enabled){ Log.d(LOG_TAG, "enabling Bluetooth GPS manager"); // final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // if (bluetoothAdapter == null) { // // Device does not support Bluetooth // Log.e(LOG_TAG, "Device does not support Bluetooth"); // disable(R.string.msg_bluetooth_unsupported); // } else if (!bluetoothAdapter.isEnabled()) { // // Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // // startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); // Log.e(LOG_TAG, "Bluetooth is not enabled"); // disable(R.string.msg_bluetooth_disabled); // } else if (Settings.Secure.getInt(callingService.getContentResolver(),Settings.Secure.ALLOW_MOCK_LOCATION, 0)==0){ Log.e(LOG_TAG, "Mock location provider OFF"); disable(R.string.msg_mock_location_disabled); // } else if ( (! locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) // && (sharedPreferences.getBoolean(BluetoothGpsProviderService.PREF_REPLACE_STD_GPS, true)) // ) { // Log.e(LOG_TAG, "GPS location provider OFF"); // disable(R.string.msg_gps_provider_disabled); } else { // final BluetoothDevice gpsDevice = bluetoothAdapter.getRemoteDevice(gpsDeviceAddress); final String gpsDevice = gpsDeviceAddress; if (gpsDevice == null){ Log.e(LOG_TAG, "GPS device not found"); disable(R.string.msg_bluetooth_gps_unavaible); } else { Log.e(LOG_TAG, "current device: "+gpsDevice ); // try { // gpsSocket = gpsDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); gpsDev = new File(gpsDeviceAddress); // } catch (IOException e) { // Log.e(LOG_TAG, "Error during connection", e); // gpsDev = null; // } if (gpsDev == null){ Log.e(LOG_TAG, "Error while establishing connection: no socket"); disable(R.string.msg_bluetooth_gps_unavaible); } else { Runnable connectThread = new Runnable() { @Override public void run() { try { connected = false; Log.v(LOG_TAG, "current device: "+gpsDevice); if (/*(bluetoothAdapter.isEnabled()) && */(nbRetriesRemaining > 0 )){ // try { if (connectedGps != null){ connectedGps.close(); } // if ((gpsDev != null) && ((connectedGps == null) || (connectedGps.gpsDev != gpsDev))){ // Log.d(LOG_TAG, "trying to close old socket"); // gpsSocket.close(); // } // } catch (IOException e) { // Log.e(LOG_TAG, "Error during disconnection", e); // } // try { // gpsSocket = gpsDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); gpsDev = new File(gpsDeviceAddress); // verify if we have enough rights.. - if (gpsDev.isFile()){ + Log.v(LOG_TAG, "Will verify if device exists and is a file: "+gpsDev.getAbsolutePath()); + if (gpsDev.exists()){ + Log.v(LOG_TAG, "Device exists and is a file: "+gpsDev.getAbsolutePath()); if (! gpsDev.canRead()){ + Log.v(LOG_TAG, "Device is not readable, will try chmod 666 "+gpsDev.getAbsolutePath()); try { // Try to get root privileges Process p = Runtime.getRuntime().exec("su"); // change device rights PrintStream os = new PrintStream(p.getOutputStream(),true); os.println("chmod 666 "+ gpsDev.getAbsolutePath()); // exit os.println("exit"); try { p.waitFor(); // if (p.exitValue() != 255) { // } // else { // } } catch (InterruptedException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); } finally { p.destroy(); } } catch (IOException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); gpsDev = null; } catch (SecurityException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); gpsDev = null; } + } else { + Log.v(LOG_TAG, "Device is readable: "+gpsDev.getAbsolutePath()); } } else { + Log.e(LOG_TAG, "Device doesn't exist: "+gpsDev.getAbsolutePath()); gpsDev = null; } // } catch (IOException e) { // Log.e(LOG_TAG, "Error during connection", e); // gpsDev = null; // } if (gpsDev == null){ Log.e(LOG_TAG, "Error while establishing connection: no device"); disable(R.string.msg_bluetooth_gps_unavaible); } else { // start GPS device try { File gpsControl = new File("/sys/devices/platform/gps_control/enable"); if (gpsControl.isFile()){ if (gpsControl.canWrite()){ OutputStream os = new FileOutputStream(gpsControl); os.write('1'); os.flush(); os.close(); } } } catch (FileNotFoundException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } catch (IOException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } catch (SecurityException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } // Cancel discovery because it will slow down the connection // bluetoothAdapter.cancelDiscovery(); // we increment the number of connection tries // Connect the device through the socket. This will block // until it succeeds or throws an exception Log.v(LOG_TAG, "connecting to socket"); // gpsDev.connect(); Log.d(LOG_TAG, "connected to socket"); connected = true; // reset eventual disabling cause // setDisableReason(0); // connection obtained so reset the number of connection try nbRetriesRemaining = 1+maxConnectionRetries ; notificationManager.cancel(R.string.connection_problem_notification_title); Log.v(LOG_TAG, "starting socket reading task"); connectedGps = new ConnectedGps(gpsDev); connectionAndReadingPool.execute(connectedGps); Log.v(LOG_TAG, "socket reading thread started"); } // } else if (! bluetoothAdapter.isEnabled()) { // setDisableReason(R.string.msg_bluetooth_disabled); } // } catch (IOException connectException) { // // Unable to connect // Log.e(LOG_TAG, "error while connecting to socket", connectException); // // disable(R.string.msg_bluetooth_gps_unavaible); } finally { nbRetriesRemaining--; if (! connected) { disableIfNeeded(); } } } }; this.enabled = true; Log.d(LOG_TAG, "Bluetooth GPS manager enabled"); Log.v(LOG_TAG, "starting notification thread"); notificationPool = Executors.newSingleThreadExecutor(); Log.v(LOG_TAG, "starting connection and reading thread"); connectionAndReadingPool = Executors.newSingleThreadScheduledExecutor(); Log.v(LOG_TAG, "starting connection to socket task"); connectionAndReadingPool.scheduleWithFixedDelay(connectThread, 5000, 60000, TimeUnit.MILLISECONDS); } } } } return this.enabled; } /** * Disables the bluetooth GPS Provider if the maximal number of connection retries is exceeded. * This is used when there are possibly non fatal connection problems. * In these cases the provider will try to reconnect with the bluetooth device * and only after a given retries number will give up and shutdown the service. */ private synchronized void disableIfNeeded(){ if (enabled){ if (nbRetriesRemaining > 0){ // Unable to connect Log.e(LOG_TAG, "Unable to establish connection"); connectionProblemNotification.when = System.currentTimeMillis(); String pbMessage = appContext.getResources().getQuantityString(R.plurals.connection_problem_notification, nbRetriesRemaining, nbRetriesRemaining); connectionProblemNotification.setLatestEventInfo(appContext, appContext.getString(R.string.connection_problem_notification_title), pbMessage, connectionProblemNotification.contentIntent); connectionProblemNotification.number = 1 + maxConnectionRetries - nbRetriesRemaining; notificationManager.notify(R.string.connection_problem_notification_title, connectionProblemNotification); } else { // notificationManager.cancel(R.string.connection_problem_notification_title); // serviceStoppedNotification.when = System.currentTimeMillis(); // notificationManager.notify(R.string.service_closed_because_connection_problem_notification_title, serviceStoppedNotification); disable(R.string.msg_two_many_connection_problems); } } } /** * Disables the bluetooth GPS provider. * * It will: * <ul> * <li>close the connection with the bluetooth device</li> * <li>disable the Mock Location Provider used for the bluetooth GPS</li> * <li>stop the BlueGPS4Droid service</li> * </ul> * The reasonId parameter indicates the reason to close the bluetooth provider. * If its value is zero, it's a normal shutdown (normally, initiated by the user). * If it's non-zero this value should correspond a valid localized string id (res/values..../...) * which will be used to display a notification. * * @param reasonId the reason to close the bluetooth provider. */ public synchronized void disable(int reasonId) { Log.d(LOG_TAG, "disabling Bluetooth GPS manager reason: "+callingService.getString(reasonId)); setDisableReason(reasonId); disable(); } /** * Disables the bluetooth GPS provider. * * It will: * <ul> * <li>close the connection with the bluetooth device</li> * <li>disable the Mock Location Provider used for the bluetooth GPS</li> * <li>stop the BlueGPS4Droid service</li> * </ul> * If the bluetooth provider is closed because of a problem, a notification is displayed. */ public synchronized void disable() { notificationManager.cancel(R.string.connection_problem_notification_title); if (getDisableReason() != 0){ serviceStoppedNotification.when = System.currentTimeMillis(); serviceStoppedNotification.setLatestEventInfo(appContext, appContext.getString(R.string.service_closed_because_connection_problem_notification_title), appContext.getString(R.string.service_closed_because_connection_problem_notification, appContext.getString(getDisableReason())), serviceStoppedNotification.contentIntent); notificationManager.notify(R.string.service_closed_because_connection_problem_notification_title, serviceStoppedNotification); } if (enabled){ Log.d(LOG_TAG, "disabling Bluetooth GPS manager"); enabled = false; connectionAndReadingPool.shutdown(); // stop GPS device try { File gpsControl = new File("/sys/devices/platform/gps_control/enable"); if (gpsControl.isFile()){ if (gpsControl.canWrite()){ OutputStream os = new FileOutputStream(gpsControl); os.write('0'); os.flush(); os.close(); } } } catch (FileNotFoundException e) { // TODO update message Log.e(LOG_TAG, "Error while stoping GPS: ", e); } catch (IOException e) { // TODO update message Log.e(LOG_TAG, "Error while stoping GPS: ", e); } catch (SecurityException e) { // TODO update message Log.e(LOG_TAG, "Error while stoping GPS: ", e); } Runnable closeAndShutdown = new Runnable() { @Override public void run(){ try { connectionAndReadingPool.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } if (!connectionAndReadingPool.isTerminated()){ connectionAndReadingPool.shutdownNow(); if (connectedGps != null){ connectedGps.close(); } // if ((gpsDev != null) && ((connectedGps == null) || (connectedGps.gpsDev != gpsDev))){ // try { // Log.d(LOG_TAG, "closing Bluetooth GPS socket"); // gpsDev.close(); // } catch (IOException closeException) { // Log.e(LOG_TAG, "error while closing socket", closeException); // } // } } } }; notificationPool.execute(closeAndShutdown); nmeaListeners.clear(); disableMockLocationProvider(); notificationPool.shutdown(); // connectionAndReadingPool.shutdown(); callingService.stopSelf(); Log.d(LOG_TAG, "Bluetooth GPS manager disabled"); } } /** * Enables the Mock GPS Location Provider used for the bluetooth GPS. * In fact, it delegates to the NMEA parser. * * @see NmeaParser#enableMockLocationProvider(java.lang.String) * @param gpsName the name of the Location Provider to use for the bluetooth GPS * @param force true if we want to force auto-activation of the mock location provider (and bypass user preference). */ public void enableMockLocationProvider(String gpsName, boolean force){ if (parser != null){ Log.d(LOG_TAG, "enabling mock locations provider: "+gpsName); parser.enableMockLocationProvider(gpsName, force); } } /** * Enables the Mock GPS Location Provider used for the bluetooth GPS. * In fact, it delegates to the NMEA parser. * * @see NmeaParser#enableMockLocationProvider(java.lang.String) * @param gpsName the name of the Location Provider to use for the bluetooth GPS */ public void enableMockLocationProvider(String gpsName){ if (parser != null){ Log.d(LOG_TAG, "enabling mock locations provider: "+gpsName); boolean force = sharedPreferences.getBoolean(BluetoothGpsProviderService.PREF_FORCE_ENABLE_PROVIDER, false); parser.enableMockLocationProvider(gpsName, force); } } /** * Disables the current Mock GPS Location Provider used for the bluetooth GPS. * In fact, it delegates to the NMEA parser. * * @see NmeaParser#disableMockLocationProvider() */ public void disableMockLocationProvider(){ if (parser != null){ Log.d(LOG_TAG, "disabling mock locations provider"); parser.disableMockLocationProvider(); } } /** * Getter use to know if the Mock GPS Listener used for the bluetooth GPS is enabled or not. * In fact, it delegates to the NMEA parser. * * @see NmeaParser#isMockGpsEnabled() * * @return true if the Mock GPS Listener used for the bluetooth GPS is enabled. */ public boolean isMockGpsEnabled() { boolean mockGpsEnabled = false; if (parser != null){ mockGpsEnabled = parser.isMockGpsEnabled(); } return mockGpsEnabled; } /** * Getter for the name of the current Mock Location Provider in use. * In fact, it delegates to the NMEA parser. * * @see NmeaParser#getMockLocationProvider() * * @return the Mock Location Provider name used for the bluetooth GPS */ public String getMockLocationProvider() { String mockLocationProvider = null; if (parser != null){ mockLocationProvider = parser.getMockLocationProvider(); } return mockLocationProvider; } /** * Indicates that the bluetooth GPS Provider is out of service. * In fact, it delegates to the NMEA parser. * * @see NmeaParser#setMockLocationProviderOutOfService() */ private void setMockLocationProviderOutOfService(){ if (parser != null){ parser.setMockLocationProviderOutOfService(); } } /** * Adds an NMEA listener. * In fact, it delegates to the NMEA parser. * * @see NmeaParser#addNmeaListener(NmeaListener) * @param listener a {@link NmeaListener} object to register * @return true if the listener was successfully added */ public boolean addNmeaListener(NmeaListener listener){ if (!nmeaListeners.contains(listener)){ Log.d(LOG_TAG, "adding new NMEA listener"); nmeaListeners.add(listener); } return true; } /** * Removes an NMEA listener. * In fact, it delegates to the NMEA parser. * * @see NmeaParser#removeNmeaListener(NmeaListener) * @param listener a {@link NmeaListener} object to remove */ public void removeNmeaListener(NmeaListener listener){ Log.d(LOG_TAG, "removing NMEA listener"); nmeaListeners.remove(listener); } /** * Notifies the reception of a NMEA sentence from the bluetooth GPS to registered NMEA listeners. * * @param nmeaSentence the complete NMEA sentence received from the bluetooth GPS (i.e. $....*XY where XY is the checksum) */ private void notifyNmeaSentence(final String nmeaSentence){ if (enabled){ Log.v(LOG_TAG, "parsing and notifying NMEA sentence: "+nmeaSentence); String sentence = null; try { sentence = parser.parseNmeaSentence(nmeaSentence); } catch (SecurityException e){ Log.e(LOG_TAG, "error while parsing NMEA sentence: "+nmeaSentence, e); // a priori Mock Location is disabled sentence = null; disable(R.string.msg_mock_location_disabled); } final String recognizedSentence = sentence; final long timestamp = System.currentTimeMillis(); if (recognizedSentence != null){ Log.v(LOG_TAG, "notifying NMEA sentence: "+recognizedSentence); synchronized(nmeaListeners) { for(final NmeaListener listener : nmeaListeners){ notificationPool.execute(new Runnable(){ @Override public void run() { listener.onNmeaReceived(timestamp, recognizedSentence); } }); } } } } } /** * Sends a NMEA sentence to the bluetooth GPS. * * @param command the complete NMEA sentence (i.e. $....*XY where XY is the checksum). */ public void sendPackagedNmeaCommand(final String command){ Log.e(LOG_TAG, "Disabled .... sending NMEA sentence: "+command); // if (isEnabled()){ // notificationPool.execute( new Runnable() { // @Override // public void run() { // while ((enabled) && ((!connected) || (connectedGps == null) || (!connectedGps.isReady()))){ // Log.v(LOG_TAG, "writing thread is not ready"); // SystemClock.sleep(500); // } // if (isEnabled() && (connectedGps != null)){ // connectedGps.write(command); // Log.d(LOG_TAG, "sent NMEA sentence: "+command); // } // } // }); // } } /** * Sends a SIRF III binary command to the bluetooth GPS. * * @param commandHexa an hexadecimal string representing a complete binary command * (i.e. with the <em>Start Sequence</em>, <em>Payload Length</em>, <em>Payload</em>, <em>Message Checksum</em> and <em>End Sequence</em>). */ public void sendPackagedSirfCommand(final String commandHexa){ Log.d(LOG_TAG, "Disabled sending SIRF sentence: "+commandHexa); // if (isEnabled()){ // final byte[] command = SirfUtils.genSirfCommand(commandHexa); // notificationPool.execute( new Runnable() { // @Override // public void run() { // while ((enabled) && ((!connected) || (connectedGps == null) || (!connectedGps.isReady()))){ // Log.v(LOG_TAG, "writing thread is not ready"); // SystemClock.sleep(500); // } // if (isEnabled() && (connectedGps != null)){ // connectedGps.write(command); // Log.d(LOG_TAG, "sent SIRF sentence: "+commandHexa); // } // } // }); // } } /** * Sends a NMEA sentence to the bluetooth GPS. * * @param sentence the NMEA sentence without the first "$", the last "*" and the checksum. */ public void sendNmeaCommand(String sentence){ String command = String.format((Locale)null,"$%s*%X\r\n", sentence, parser.computeChecksum(sentence)); sendPackagedNmeaCommand(command); } /** * Sends a SIRF III binary command to the bluetooth GPS. * * @param payload an hexadecimal string representing the payload of the binary command * (i.e. without <em>Start Sequence</em>, <em>Payload Length</em>, <em>Message Checksum</em> and <em>End Sequence</em>). */ public void sendSirfCommand(String payload){ String command = SirfUtils.createSirfCommandFromPayload(payload); sendPackagedSirfCommand(command); } }
false
true
public synchronized boolean enable() { notificationManager.cancel(R.string.service_closed_because_connection_problem_notification_title); if (! enabled){ Log.d(LOG_TAG, "enabling Bluetooth GPS manager"); // final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // if (bluetoothAdapter == null) { // // Device does not support Bluetooth // Log.e(LOG_TAG, "Device does not support Bluetooth"); // disable(R.string.msg_bluetooth_unsupported); // } else if (!bluetoothAdapter.isEnabled()) { // // Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // // startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); // Log.e(LOG_TAG, "Bluetooth is not enabled"); // disable(R.string.msg_bluetooth_disabled); // } else if (Settings.Secure.getInt(callingService.getContentResolver(),Settings.Secure.ALLOW_MOCK_LOCATION, 0)==0){ Log.e(LOG_TAG, "Mock location provider OFF"); disable(R.string.msg_mock_location_disabled); // } else if ( (! locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) // && (sharedPreferences.getBoolean(BluetoothGpsProviderService.PREF_REPLACE_STD_GPS, true)) // ) { // Log.e(LOG_TAG, "GPS location provider OFF"); // disable(R.string.msg_gps_provider_disabled); } else { // final BluetoothDevice gpsDevice = bluetoothAdapter.getRemoteDevice(gpsDeviceAddress); final String gpsDevice = gpsDeviceAddress; if (gpsDevice == null){ Log.e(LOG_TAG, "GPS device not found"); disable(R.string.msg_bluetooth_gps_unavaible); } else { Log.e(LOG_TAG, "current device: "+gpsDevice ); // try { // gpsSocket = gpsDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); gpsDev = new File(gpsDeviceAddress); // } catch (IOException e) { // Log.e(LOG_TAG, "Error during connection", e); // gpsDev = null; // } if (gpsDev == null){ Log.e(LOG_TAG, "Error while establishing connection: no socket"); disable(R.string.msg_bluetooth_gps_unavaible); } else { Runnable connectThread = new Runnable() { @Override public void run() { try { connected = false; Log.v(LOG_TAG, "current device: "+gpsDevice); if (/*(bluetoothAdapter.isEnabled()) && */(nbRetriesRemaining > 0 )){ // try { if (connectedGps != null){ connectedGps.close(); } // if ((gpsDev != null) && ((connectedGps == null) || (connectedGps.gpsDev != gpsDev))){ // Log.d(LOG_TAG, "trying to close old socket"); // gpsSocket.close(); // } // } catch (IOException e) { // Log.e(LOG_TAG, "Error during disconnection", e); // } // try { // gpsSocket = gpsDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); gpsDev = new File(gpsDeviceAddress); // verify if we have enough rights.. if (gpsDev.isFile()){ if (! gpsDev.canRead()){ try { // Try to get root privileges Process p = Runtime.getRuntime().exec("su"); // change device rights PrintStream os = new PrintStream(p.getOutputStream(),true); os.println("chmod 666 "+ gpsDev.getAbsolutePath()); // exit os.println("exit"); try { p.waitFor(); // if (p.exitValue() != 255) { // } // else { // } } catch (InterruptedException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); } finally { p.destroy(); } } catch (IOException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); gpsDev = null; } catch (SecurityException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); gpsDev = null; } } } else { gpsDev = null; } // } catch (IOException e) { // Log.e(LOG_TAG, "Error during connection", e); // gpsDev = null; // } if (gpsDev == null){ Log.e(LOG_TAG, "Error while establishing connection: no device"); disable(R.string.msg_bluetooth_gps_unavaible); } else { // start GPS device try { File gpsControl = new File("/sys/devices/platform/gps_control/enable"); if (gpsControl.isFile()){ if (gpsControl.canWrite()){ OutputStream os = new FileOutputStream(gpsControl); os.write('1'); os.flush(); os.close(); } } } catch (FileNotFoundException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } catch (IOException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } catch (SecurityException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } // Cancel discovery because it will slow down the connection // bluetoothAdapter.cancelDiscovery(); // we increment the number of connection tries // Connect the device through the socket. This will block // until it succeeds or throws an exception Log.v(LOG_TAG, "connecting to socket"); // gpsDev.connect(); Log.d(LOG_TAG, "connected to socket"); connected = true; // reset eventual disabling cause // setDisableReason(0); // connection obtained so reset the number of connection try nbRetriesRemaining = 1+maxConnectionRetries ; notificationManager.cancel(R.string.connection_problem_notification_title); Log.v(LOG_TAG, "starting socket reading task"); connectedGps = new ConnectedGps(gpsDev); connectionAndReadingPool.execute(connectedGps); Log.v(LOG_TAG, "socket reading thread started"); } // } else if (! bluetoothAdapter.isEnabled()) { // setDisableReason(R.string.msg_bluetooth_disabled); } // } catch (IOException connectException) { // // Unable to connect // Log.e(LOG_TAG, "error while connecting to socket", connectException); // // disable(R.string.msg_bluetooth_gps_unavaible); } finally { nbRetriesRemaining--; if (! connected) { disableIfNeeded(); } } } }; this.enabled = true; Log.d(LOG_TAG, "Bluetooth GPS manager enabled"); Log.v(LOG_TAG, "starting notification thread"); notificationPool = Executors.newSingleThreadExecutor(); Log.v(LOG_TAG, "starting connection and reading thread"); connectionAndReadingPool = Executors.newSingleThreadScheduledExecutor(); Log.v(LOG_TAG, "starting connection to socket task"); connectionAndReadingPool.scheduleWithFixedDelay(connectThread, 5000, 60000, TimeUnit.MILLISECONDS); } } } } return this.enabled; }
public synchronized boolean enable() { notificationManager.cancel(R.string.service_closed_because_connection_problem_notification_title); if (! enabled){ Log.d(LOG_TAG, "enabling Bluetooth GPS manager"); // final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // if (bluetoothAdapter == null) { // // Device does not support Bluetooth // Log.e(LOG_TAG, "Device does not support Bluetooth"); // disable(R.string.msg_bluetooth_unsupported); // } else if (!bluetoothAdapter.isEnabled()) { // // Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // // startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); // Log.e(LOG_TAG, "Bluetooth is not enabled"); // disable(R.string.msg_bluetooth_disabled); // } else if (Settings.Secure.getInt(callingService.getContentResolver(),Settings.Secure.ALLOW_MOCK_LOCATION, 0)==0){ Log.e(LOG_TAG, "Mock location provider OFF"); disable(R.string.msg_mock_location_disabled); // } else if ( (! locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) // && (sharedPreferences.getBoolean(BluetoothGpsProviderService.PREF_REPLACE_STD_GPS, true)) // ) { // Log.e(LOG_TAG, "GPS location provider OFF"); // disable(R.string.msg_gps_provider_disabled); } else { // final BluetoothDevice gpsDevice = bluetoothAdapter.getRemoteDevice(gpsDeviceAddress); final String gpsDevice = gpsDeviceAddress; if (gpsDevice == null){ Log.e(LOG_TAG, "GPS device not found"); disable(R.string.msg_bluetooth_gps_unavaible); } else { Log.e(LOG_TAG, "current device: "+gpsDevice ); // try { // gpsSocket = gpsDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); gpsDev = new File(gpsDeviceAddress); // } catch (IOException e) { // Log.e(LOG_TAG, "Error during connection", e); // gpsDev = null; // } if (gpsDev == null){ Log.e(LOG_TAG, "Error while establishing connection: no socket"); disable(R.string.msg_bluetooth_gps_unavaible); } else { Runnable connectThread = new Runnable() { @Override public void run() { try { connected = false; Log.v(LOG_TAG, "current device: "+gpsDevice); if (/*(bluetoothAdapter.isEnabled()) && */(nbRetriesRemaining > 0 )){ // try { if (connectedGps != null){ connectedGps.close(); } // if ((gpsDev != null) && ((connectedGps == null) || (connectedGps.gpsDev != gpsDev))){ // Log.d(LOG_TAG, "trying to close old socket"); // gpsSocket.close(); // } // } catch (IOException e) { // Log.e(LOG_TAG, "Error during disconnection", e); // } // try { // gpsSocket = gpsDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); gpsDev = new File(gpsDeviceAddress); // verify if we have enough rights.. Log.v(LOG_TAG, "Will verify if device exists and is a file: "+gpsDev.getAbsolutePath()); if (gpsDev.exists()){ Log.v(LOG_TAG, "Device exists and is a file: "+gpsDev.getAbsolutePath()); if (! gpsDev.canRead()){ Log.v(LOG_TAG, "Device is not readable, will try chmod 666 "+gpsDev.getAbsolutePath()); try { // Try to get root privileges Process p = Runtime.getRuntime().exec("su"); // change device rights PrintStream os = new PrintStream(p.getOutputStream(),true); os.println("chmod 666 "+ gpsDev.getAbsolutePath()); // exit os.println("exit"); try { p.waitFor(); // if (p.exitValue() != 255) { // } // else { // } } catch (InterruptedException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); } finally { p.destroy(); } } catch (IOException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); gpsDev = null; } catch (SecurityException e) { // TODO update message Log.e(LOG_TAG, "Error while establishing connection: ", e); gpsDev = null; } } else { Log.v(LOG_TAG, "Device is readable: "+gpsDev.getAbsolutePath()); } } else { Log.e(LOG_TAG, "Device doesn't exist: "+gpsDev.getAbsolutePath()); gpsDev = null; } // } catch (IOException e) { // Log.e(LOG_TAG, "Error during connection", e); // gpsDev = null; // } if (gpsDev == null){ Log.e(LOG_TAG, "Error while establishing connection: no device"); disable(R.string.msg_bluetooth_gps_unavaible); } else { // start GPS device try { File gpsControl = new File("/sys/devices/platform/gps_control/enable"); if (gpsControl.isFile()){ if (gpsControl.canWrite()){ OutputStream os = new FileOutputStream(gpsControl); os.write('1'); os.flush(); os.close(); } } } catch (FileNotFoundException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } catch (IOException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } catch (SecurityException e) { // TODO update message Log.e(LOG_TAG, "Error while starting GPS: ", e); } // Cancel discovery because it will slow down the connection // bluetoothAdapter.cancelDiscovery(); // we increment the number of connection tries // Connect the device through the socket. This will block // until it succeeds or throws an exception Log.v(LOG_TAG, "connecting to socket"); // gpsDev.connect(); Log.d(LOG_TAG, "connected to socket"); connected = true; // reset eventual disabling cause // setDisableReason(0); // connection obtained so reset the number of connection try nbRetriesRemaining = 1+maxConnectionRetries ; notificationManager.cancel(R.string.connection_problem_notification_title); Log.v(LOG_TAG, "starting socket reading task"); connectedGps = new ConnectedGps(gpsDev); connectionAndReadingPool.execute(connectedGps); Log.v(LOG_TAG, "socket reading thread started"); } // } else if (! bluetoothAdapter.isEnabled()) { // setDisableReason(R.string.msg_bluetooth_disabled); } // } catch (IOException connectException) { // // Unable to connect // Log.e(LOG_TAG, "error while connecting to socket", connectException); // // disable(R.string.msg_bluetooth_gps_unavaible); } finally { nbRetriesRemaining--; if (! connected) { disableIfNeeded(); } } } }; this.enabled = true; Log.d(LOG_TAG, "Bluetooth GPS manager enabled"); Log.v(LOG_TAG, "starting notification thread"); notificationPool = Executors.newSingleThreadExecutor(); Log.v(LOG_TAG, "starting connection and reading thread"); connectionAndReadingPool = Executors.newSingleThreadScheduledExecutor(); Log.v(LOG_TAG, "starting connection to socket task"); connectionAndReadingPool.scheduleWithFixedDelay(connectThread, 5000, 60000, TimeUnit.MILLISECONDS); } } } } return this.enabled; }
diff --git a/src/org/osm/keypadmapper/KeypadMapper.java b/src/org/osm/keypadmapper/KeypadMapper.java index c5254f1..c27c43e 100644 --- a/src/org/osm/keypadmapper/KeypadMapper.java +++ b/src/org/osm/keypadmapper/KeypadMapper.java @@ -1,81 +1,83 @@ package org.osm.keypadmapper; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.Date; import junit.framework.Assert; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.TextView; import org.osm.keypadmapper.R; public class KeypadMapper extends Activity { /* private int ids[] = { R.id.button_0, R.id.button_1, R.id.button_2, R.id.button_3, R.id.button_4, R.id.button_5, R.id.button_6, R.id.button_7, R.id.button_8, R.id.button_9, R.id.button_C, R.id.button_DEL, R.id.button_L, R.id.button_F, R.id.button_R };*/ private String val = ""; void SetButtons (ViewGroup btnGroup) { for (int i = 0; i < btnGroup.getChildCount(); i++) { if (ViewGroup.class.isInstance(btnGroup.getChildAt(i))) { SetButtons ((ViewGroup) btnGroup.getChildAt(i)); } else if (Button.class.isInstance(btnGroup.getChildAt(i))){ Button button = (Button) btnGroup.getChildAt(i);//findViewById (ids[i]); button.setOnClickListener(new Button.OnClickListener() { private void Do (String s) { PrintWriter out = null; Date d = new Date (); try { out = new PrintWriter (new FileOutputStream ( "/sdcard/keypadmapper", true)); out.print (d.getTime()); out.print (s); out.println (val); } catch (FileNotFoundException e) { Assert.assertNotNull ("Error writing the file!", out); } finally { if (out != null) out.close (); Assert.assertNotNull ("Error writing the file!", out); } /*if (out == null) AlertDialog.Builder(mContext) .setIcon(R.drawable.alert_dialog_icon) .setTitle("Error writing file !")*/ /*.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); */ //.create (); val = ""; } public void onClick (View v) { if (v == findViewById (R.id.button_C)) val = ""; - else if (v == findViewById (R.id.button_DEL)) val = val.substring(0, val.length()-1); + else if (v == findViewById (R.id.button_DEL)) { + if (val.length() > 0) val = val.substring(0, val.length()-1); + } else if (v == findViewById (R.id.button_L)) Do ("L"); else if (v == findViewById (R.id.button_F)) Do ("F"); else if (v == findViewById (R.id.button_R)) Do ("R"); else val = val + v.getTag(); TextView tw = (TextView) findViewById (R.id.text); tw.setText (val); } }); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); SetButtons ((ViewGroup) findViewById (R.id.buttonGroup)); } }
true
true
void SetButtons (ViewGroup btnGroup) { for (int i = 0; i < btnGroup.getChildCount(); i++) { if (ViewGroup.class.isInstance(btnGroup.getChildAt(i))) { SetButtons ((ViewGroup) btnGroup.getChildAt(i)); } else if (Button.class.isInstance(btnGroup.getChildAt(i))){ Button button = (Button) btnGroup.getChildAt(i);//findViewById (ids[i]); button.setOnClickListener(new Button.OnClickListener() { private void Do (String s) { PrintWriter out = null; Date d = new Date (); try { out = new PrintWriter (new FileOutputStream ( "/sdcard/keypadmapper", true)); out.print (d.getTime()); out.print (s); out.println (val); } catch (FileNotFoundException e) { Assert.assertNotNull ("Error writing the file!", out); } finally { if (out != null) out.close (); Assert.assertNotNull ("Error writing the file!", out); } /*if (out == null) AlertDialog.Builder(mContext) .setIcon(R.drawable.alert_dialog_icon) .setTitle("Error writing file !")*/ /*.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); */ //.create (); val = ""; } public void onClick (View v) { if (v == findViewById (R.id.button_C)) val = ""; else if (v == findViewById (R.id.button_DEL)) val = val.substring(0, val.length()-1); else if (v == findViewById (R.id.button_L)) Do ("L"); else if (v == findViewById (R.id.button_F)) Do ("F"); else if (v == findViewById (R.id.button_R)) Do ("R"); else val = val + v.getTag(); TextView tw = (TextView) findViewById (R.id.text); tw.setText (val); } }); } }
void SetButtons (ViewGroup btnGroup) { for (int i = 0; i < btnGroup.getChildCount(); i++) { if (ViewGroup.class.isInstance(btnGroup.getChildAt(i))) { SetButtons ((ViewGroup) btnGroup.getChildAt(i)); } else if (Button.class.isInstance(btnGroup.getChildAt(i))){ Button button = (Button) btnGroup.getChildAt(i);//findViewById (ids[i]); button.setOnClickListener(new Button.OnClickListener() { private void Do (String s) { PrintWriter out = null; Date d = new Date (); try { out = new PrintWriter (new FileOutputStream ( "/sdcard/keypadmapper", true)); out.print (d.getTime()); out.print (s); out.println (val); } catch (FileNotFoundException e) { Assert.assertNotNull ("Error writing the file!", out); } finally { if (out != null) out.close (); Assert.assertNotNull ("Error writing the file!", out); } /*if (out == null) AlertDialog.Builder(mContext) .setIcon(R.drawable.alert_dialog_icon) .setTitle("Error writing file !")*/ /*.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); */ //.create (); val = ""; } public void onClick (View v) { if (v == findViewById (R.id.button_C)) val = ""; else if (v == findViewById (R.id.button_DEL)) { if (val.length() > 0) val = val.substring(0, val.length()-1); } else if (v == findViewById (R.id.button_L)) Do ("L"); else if (v == findViewById (R.id.button_F)) Do ("F"); else if (v == findViewById (R.id.button_R)) Do ("R"); else val = val + v.getTag(); TextView tw = (TextView) findViewById (R.id.text); tw.setText (val); } }); } }
diff --git a/src/java/com/sun/facelets/impl/DefaultFaceletContext.java b/src/java/com/sun/facelets/impl/DefaultFaceletContext.java index 0383bc3..5be6450 100644 --- a/src/java/com/sun/facelets/impl/DefaultFaceletContext.java +++ b/src/java/com/sun/facelets/impl/DefaultFaceletContext.java @@ -1,362 +1,363 @@ /** * Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.com/cddl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.sun.facelets.impl; import com.sun.facelets.FaceletContext; import com.sun.facelets.FaceletException; import com.sun.facelets.TemplateClient; import com.sun.facelets.el.DefaultVariableMapper; import com.sun.facelets.el.ELAdaptor; import javax.el.*; import javax.faces.FacesException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import java.io.IOException; import java.net.URL; import java.util.*; /** * Default FaceletContext implementation. * * A single FaceletContext is used for all Facelets involved in an invocation of * {@link com.sun.facelets.Facelet#apply(FacesContext, UIComponent) Facelet#apply(FacesContext, UIComponent)}. * This means that included Facelets are treated the same as the JSP include * directive. * * @author Jacob Hookom * @version $Id: DefaultFaceletContext.java,v 1.4.4.3 2006/03/25 01:01:53 jhook * Exp $ */ final class DefaultFaceletContext extends FaceletContext { private final FacesContext faces; private final ELContext ctx; private final DefaultFacelet facelet; private final List faceletHierarchy; private VariableMapper varMapper; private FunctionMapper fnMapper; private final Map ids; private final Map prefixes; private String prefix; //TODO: change to StringBuilder when JDK1.5 support is available in Facelets private final StringBuffer uniqueIdBuilder=new StringBuffer(30); public DefaultFaceletContext(DefaultFaceletContext ctx, DefaultFacelet facelet) { this.ctx = ctx.ctx; this.clients = ctx.clients; this.faces = ctx.faces; this.fnMapper = ctx.fnMapper; this.ids = ctx.ids; this.prefixes = ctx.prefixes; this.varMapper = ctx.varMapper; this.faceletHierarchy = new ArrayList(ctx.faceletHierarchy.size()+1); this.faceletHierarchy.addAll(ctx.faceletHierarchy); this.faceletHierarchy.add(facelet); this.facelet=facelet; } public DefaultFaceletContext(FacesContext faces, DefaultFacelet facelet) { this.ctx = ELAdaptor.getELContext(faces); this.ids = new HashMap(); this.prefixes = new HashMap(); this.clients = new ArrayList(5); this.faces = faces; this.faceletHierarchy = new ArrayList(1); this.faceletHierarchy.add(facelet); this.facelet = facelet; this.varMapper = this.ctx.getVariableMapper(); if (this.varMapper == null) { this.varMapper = new DefaultVariableMapper(); } this.fnMapper = this.ctx.getFunctionMapper(); } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#getFacesContext() */ public FacesContext getFacesContext() { return this.faces; } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#getExpressionFactory() */ public ExpressionFactory getExpressionFactory() { return this.facelet.getExpressionFactory(); } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#setVariableMapper(javax.el.VariableMapper) */ public void setVariableMapper(VariableMapper varMapper) { // Assert.param("varMapper", varMapper); this.varMapper = varMapper; } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#setFunctionMapper(javax.el.FunctionMapper) */ public void setFunctionMapper(FunctionMapper fnMapper) { // Assert.param("fnMapper", fnMapper); this.fnMapper = fnMapper; } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#includeFacelet(javax.faces.component.UIComponent, * java.lang.String) */ public void includeFacelet(UIComponent parent, String relativePath) throws IOException, FacesException, ELException { this.facelet.include(this, parent, relativePath); } /* * (non-Javadoc) * * @see javax.el.ELContext#getFunctionMapper() */ public FunctionMapper getFunctionMapper() { return this.fnMapper; } /* * (non-Javadoc) * * @see javax.el.ELContext#getVariableMapper() */ public VariableMapper getVariableMapper() { return this.varMapper; } /* * (non-Javadoc) * * @see javax.el.ELContext#getContext(java.lang.Class) */ public Object getContext(Class key) { return this.ctx.getContext(key); } /* * (non-Javadoc) * * @see javax.el.ELContext#putContext(java.lang.Class, java.lang.Object) */ public void putContext(Class key, Object contextObject) { this.ctx.putContext(key, contextObject); } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#generateUniqueId(java.lang.String) */ public String generateUniqueId(String base) { if(prefix==null) { - StringBuilder builder = new StringBuilder(faceletHierarchy.size()*30); + //TODO: change to StringBuilder when JDK1.5 support is available + StringBuffer builder = new StringBuffer(faceletHierarchy.size()*30); for(int i=0; i< faceletHierarchy.size(); i++) { DefaultFacelet facelet = (DefaultFacelet) faceletHierarchy.get(i); builder.append(facelet.getAlias()); } Integer prefixInt = new Integer(builder.toString().hashCode()); Integer cnt = (Integer) prefixes.get(prefixInt); if(cnt==null) { this.prefixes.put(prefixInt,new Integer(0)); prefix = prefixInt.toString(); } else { int i=cnt.intValue()+1; this.prefixes.put(prefixInt,new Integer(i)); prefix = prefixInt+"_"+i; } } Integer cnt = (Integer) this.ids.get(base); if (cnt == null) { this.ids.put(base, new Integer(0)); uniqueIdBuilder.delete(0,uniqueIdBuilder.length()); uniqueIdBuilder.append(prefix); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(base); return uniqueIdBuilder.toString(); } else { int i = cnt.intValue() + 1; this.ids.put(base, new Integer(i)); uniqueIdBuilder.delete(0,uniqueIdBuilder.length()); uniqueIdBuilder.append(prefix); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(base); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(i); return uniqueIdBuilder.toString(); } } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#getAttribute(java.lang.String) */ public Object getAttribute(String name) { if (this.varMapper != null) { ValueExpression ve = this.varMapper.resolveVariable(name); if (ve != null) { return ve.getValue(this); } } return null; } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#setAttribute(java.lang.String, * java.lang.Object) */ public void setAttribute(String name, Object value) { if (this.varMapper != null) { if (value == null) { this.varMapper.setVariable(name, null); } else { this.varMapper.setVariable(name, this.facelet .getExpressionFactory().createValueExpression(value, Object.class)); } } } /* * (non-Javadoc) * * @see com.sun.facelets.FaceletContext#includeFacelet(javax.faces.component.UIComponent, * java.net.URL) */ public void includeFacelet(UIComponent parent, URL absolutePath) throws IOException, FacesException, ELException { this.facelet.include(this, parent, absolutePath); } public ELResolver getELResolver() { return this.ctx.getELResolver(); } private final List clients; public void popClient(TemplateClient client) { if (!this.clients.isEmpty()) { Iterator itr = this.clients.iterator(); while (itr.hasNext()) { if (itr.next().equals(client)) { itr.remove(); return; } } } throw new IllegalStateException(client + " not found"); } public void pushClient(final TemplateClient client) { this.clients.add(0, new TemplateManager(this.facelet, client, true)); } public void extendClient(final TemplateClient client) { this.clients.add(new TemplateManager(this.facelet, client, false)); } public boolean includeDefinition(UIComponent parent, String name) throws IOException, FaceletException, FacesException, ELException { boolean found = false; TemplateManager client; for (int i = 0, size = this.clients.size(); i < size && !found; i++) { client = ((TemplateManager) this.clients.get(i)); if (client.equals(this.facelet)) continue; found = client.apply(this, parent, name); } return found; } private final static class TemplateManager implements TemplateClient { private final DefaultFacelet owner; private final TemplateClient target; private final boolean root; private final Set names = new HashSet(); public TemplateManager(DefaultFacelet owner, TemplateClient target, boolean root) { this.owner = owner; this.target = target; this.root = root; } public boolean apply(FaceletContext ctx, UIComponent parent, String name) throws IOException, FacesException, FaceletException, ELException { String testName = (name != null) ? name : "facelets._NULL_DEF_"; if (this.names.contains(testName)) { return false; } else { this.names.add(testName); boolean found = false; found = this.target.apply(new DefaultFaceletContext( (DefaultFaceletContext) ctx, this.owner), parent, name); this.names.remove(testName); return found; } } public boolean equals(Object o) { // System.out.println(this.owner.getAlias() + " == " + // ((DefaultFacelet) o).getAlias()); return this.owner == o || this.target == o; } public boolean isRoot() { return this.root; } } public boolean isPropertyResolved() { return this.ctx.isPropertyResolved(); } public void setPropertyResolved(boolean resolved) { this.ctx.setPropertyResolved(resolved); } }
true
true
public String generateUniqueId(String base) { if(prefix==null) { StringBuilder builder = new StringBuilder(faceletHierarchy.size()*30); for(int i=0; i< faceletHierarchy.size(); i++) { DefaultFacelet facelet = (DefaultFacelet) faceletHierarchy.get(i); builder.append(facelet.getAlias()); } Integer prefixInt = new Integer(builder.toString().hashCode()); Integer cnt = (Integer) prefixes.get(prefixInt); if(cnt==null) { this.prefixes.put(prefixInt,new Integer(0)); prefix = prefixInt.toString(); } else { int i=cnt.intValue()+1; this.prefixes.put(prefixInt,new Integer(i)); prefix = prefixInt+"_"+i; } } Integer cnt = (Integer) this.ids.get(base); if (cnt == null) { this.ids.put(base, new Integer(0)); uniqueIdBuilder.delete(0,uniqueIdBuilder.length()); uniqueIdBuilder.append(prefix); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(base); return uniqueIdBuilder.toString(); } else { int i = cnt.intValue() + 1; this.ids.put(base, new Integer(i)); uniqueIdBuilder.delete(0,uniqueIdBuilder.length()); uniqueIdBuilder.append(prefix); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(base); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(i); return uniqueIdBuilder.toString(); } }
public String generateUniqueId(String base) { if(prefix==null) { //TODO: change to StringBuilder when JDK1.5 support is available StringBuffer builder = new StringBuffer(faceletHierarchy.size()*30); for(int i=0; i< faceletHierarchy.size(); i++) { DefaultFacelet facelet = (DefaultFacelet) faceletHierarchy.get(i); builder.append(facelet.getAlias()); } Integer prefixInt = new Integer(builder.toString().hashCode()); Integer cnt = (Integer) prefixes.get(prefixInt); if(cnt==null) { this.prefixes.put(prefixInt,new Integer(0)); prefix = prefixInt.toString(); } else { int i=cnt.intValue()+1; this.prefixes.put(prefixInt,new Integer(i)); prefix = prefixInt+"_"+i; } } Integer cnt = (Integer) this.ids.get(base); if (cnt == null) { this.ids.put(base, new Integer(0)); uniqueIdBuilder.delete(0,uniqueIdBuilder.length()); uniqueIdBuilder.append(prefix); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(base); return uniqueIdBuilder.toString(); } else { int i = cnt.intValue() + 1; this.ids.put(base, new Integer(i)); uniqueIdBuilder.delete(0,uniqueIdBuilder.length()); uniqueIdBuilder.append(prefix); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(base); uniqueIdBuilder.append("_"); uniqueIdBuilder.append(i); return uniqueIdBuilder.toString(); } }
diff --git a/src/main/java/org/quantumbadger/redreader/adapters/PostListingAdapter.java b/src/main/java/org/quantumbadger/redreader/adapters/PostListingAdapter.java index d18309b..4a5a9a4 100644 --- a/src/main/java/org/quantumbadger/redreader/adapters/PostListingAdapter.java +++ b/src/main/java/org/quantumbadger/redreader/adapters/PostListingAdapter.java @@ -1,117 +1,117 @@ package org.quantumbadger.redreader.adapters; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import org.holoeverywhere.widget.ListView; import org.quantumbadger.redreader.common.General; import org.quantumbadger.redreader.fragments.PostListingFragment; import org.quantumbadger.redreader.reddit.prepared.RedditPreparedPost; import org.quantumbadger.redreader.views.RedditPostView; import java.util.ArrayList; import java.util.HashSet; public final class PostListingAdapter extends BaseAdapter { private final ArrayList<RedditPreparedPost> postsToReport = new ArrayList<RedditPreparedPost>(50); private final ArrayList<RedditPreparedPost> posts = new ArrayList<RedditPreparedPost>(50); private final HashSet<String> postIds = new HashSet<String>(100); private final ListView listViewParent; private final PostListingFragment fragmentParent; private final Handler postAddedHandler; public PostListingAdapter(final ListView listViewParent, final PostListingFragment fragmentParent) { this.listViewParent = listViewParent; this.fragmentParent = fragmentParent; postAddedHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(final Message msg) { final RedditPreparedPost post = (RedditPreparedPost)msg.obj; if(!postIds.add(post.idAlone)) return; posts.add(post); - if(listViewParent.getLastVisiblePosition() + 1 >= posts.size()) { + if(listViewParent.getLastVisiblePosition() + 1 >= postsToReport.size()) { updatePosts(); } } }; } private void updatePosts() { postsToReport.clear(); postsToReport.addAll(posts); notifyDataSetChanged(); } public void onScroll() { if(posts.size() != postsToReport.size()) { updatePosts(); } } public void onPostDownloaded(final RedditPreparedPost post) { postAddedHandler.sendMessage(General.handlerMessage(0, post)); } public int getCount() { return postsToReport.size(); } public Object getItem(final int i) { return null; } public long getItemId(final int i) { return i; } @Override public boolean hasStableIds() { return true; } @Override public int getItemViewType(final int position) { return 0; } @Override public int getViewTypeCount() { return 1; } public RedditPostView getView(final int i, View convertView, final ViewGroup viewGroup) { if(convertView == null) { convertView = new RedditPostView(viewGroup.getContext(), listViewParent, fragmentParent); } final RedditPostView rpv = (RedditPostView)convertView; rpv.reset(postsToReport.get(i)); return rpv; } @Override public boolean areAllItemsEnabled() { return true; } public int getDownloadedCount() { return posts.size(); } }
true
true
public PostListingAdapter(final ListView listViewParent, final PostListingFragment fragmentParent) { this.listViewParent = listViewParent; this.fragmentParent = fragmentParent; postAddedHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(final Message msg) { final RedditPreparedPost post = (RedditPreparedPost)msg.obj; if(!postIds.add(post.idAlone)) return; posts.add(post); if(listViewParent.getLastVisiblePosition() + 1 >= posts.size()) { updatePosts(); } } }; }
public PostListingAdapter(final ListView listViewParent, final PostListingFragment fragmentParent) { this.listViewParent = listViewParent; this.fragmentParent = fragmentParent; postAddedHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(final Message msg) { final RedditPreparedPost post = (RedditPreparedPost)msg.obj; if(!postIds.add(post.idAlone)) return; posts.add(post); if(listViewParent.getLastVisiblePosition() + 1 >= postsToReport.size()) { updatePosts(); } } }; }
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java index 661e7a66..1112acdf 100644 --- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java +++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java @@ -1,1537 +1,1537 @@ package jp.ac.osaka_u.ist.sel.metricstool.main; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.csharp.CSharpAntlrAstTranslator; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.databuilder.ASTParseException; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.java.Java13AntlrAstTranslator; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.java.Java14AntlrAstTranslator; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.java.Java15AntlrAstTranslator; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.java.JavaAstVisitorManager; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.visitor.AstVisitorManager; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.visitor.antlr.AntlrAstVisitor; import jp.ac.osaka_u.ist.sel.metricstool.main.data.DataManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.ClassMetricsInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.FieldMetricsInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.FileMetricsInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.MethodMetricsInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.MetricNotRegisteredException; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.BlockInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.CallableUnitInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassTypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ConditionalBlockInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ConditionalClauseInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ConstructorCallInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExpressionInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExternalClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldUsageInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FileInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.LocalSpaceInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodCallInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.StatementInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetConstructorInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFile; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFileManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetInnerClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetMethodInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeParameterInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.UnknownTypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.VariableUsageInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedBlockInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedCallInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedClassInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedClassTypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedConditionalBlockInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedConstructorInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedFieldInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedLocalSpaceInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedMethodInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedStatementInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedTypeParameterInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedVariableUsageInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVClassMetricsWriter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVFileMetricsWriter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVMethodMetricsWriter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.DefaultMessagePrinter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageEvent; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageListener; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePool; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageSource; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter.MESSAGE_TYPE; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.CSharpLexer; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.CSharpParser; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.CommonASTWithLineNumber; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.Java14Lexer; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.Java14Parser; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.Java15Lexer; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.Java15Parser; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.MasuAstFactory; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.AbstractPlugin; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.DefaultPluginLauncher; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.PluginLauncher; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.PluginManager; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.AbstractPlugin.PluginInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.loader.DefaultPluginLoader; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.loader.PluginLoadException; import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager; import jp.ac.osaka_u.ist.sel.metricstool.main.util.LANGUAGE; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import antlr.ASTFactory; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.collections.AST; /** * * @author higo * * MetricsTool�̃��C���N���X�D ���݂͉������D * * since 2006.11.12 * */ public class MetricsTool { /** * * @param args �Ώۃt�@�C���̃t�@�C���p�X * * ���݉������D �Ώۃt�@�C���̃f�[�^���i�[������C�\����͂��s���D */ public static void main(String[] args) { // ���\���p�̃��X�i���쐬 final MessageListener outListener = new MessageListener() { public void messageReceived(MessageEvent event) { System.out.print(event.getSource().getMessageSourceName() + " > " + event.getMessage()); } }; final MessageListener errListener = new MessageListener() { public void messageReceived(MessageEvent event) { System.out.print(event.getSource().getMessageSourceName() + " > " + event.getMessage()); } }; MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(outListener); MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(errListener); final Options options = new Options(); { final Option h = new Option("h", "help", false, "display usage"); h.setRequired(false); options.addOption(h); } { final Option v = new Option("v", "verbose", false, "output progress verbosely"); v.setRequired(false); options.addOption(v); } { final Option d = new Option("d", "directory", true, "specify target directory"); d.setArgName("directory"); d.setArgs(1); d.setRequired(false); options.addOption(d); } { final Option i = new Option("i", "input", true, "specify the input that contains the list of target files"); i.setArgName("input"); i.setArgs(1); i.setRequired(false); options.addOption(i); } { final Option l = new Option("l", "language", true, "specify programming language"); l.setArgName("input"); l.setArgs(1); l.setRequired(false); options.addOption(l); } { final Option m = new Option("m", "metrics", true, "specify measured metrics with comma separeted format (e.g., -m rfc,dit,lcom)"); m.setArgName("metrics"); m.setArgs(1); m.setRequired(false); options.addOption(m); } { final Option F = new Option("F", "FileMetricsFile", true, "specify file that measured FILE metrics were stored into"); F.setArgName("file metrics file"); F.setArgs(1); F.setRequired(false); options.addOption(F); } { final Option C = new Option("C", "ClassMetricsFile", true, "specify file that measured CLASS metrics were stored into"); C.setArgName("class metrics file"); C.setArgs(1); C.setRequired(false); options.addOption(C); } { final Option M = new Option("M", "MethodMetricsFile", true, "specify file that measured METHOD metrics were stored into"); M.setArgName("method metrics file"); M.setArgs(1); M.setRequired(false); options.addOption(M); } { final Option A = new Option("A", "AttributeMetricsFile", true, "specify file that measured ATTRIBUTE metrics were stored into"); A.setArgName("attribute metrics file"); A.setArgs(1); A.setRequired(false); options.addOption(A); } final MetricsTool metricsTool = new MetricsTool(); try { final CommandLineParser parser = new PosixParser(); final CommandLine cmd = parser.parse(options, args); // "-h"���w�肳��Ă���ꍇ�̓w���v��\�����ďI�� // ���̂Ƃ��C���̃I�v�V�����͑S�Ė�������� - if (cmd.hasOption("h")) { + if (cmd.hasOption("h") || (0 == args.length)) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("MetricsTool", options, true); // -l �Ō��ꂪ�w�肳��Ă��Ȃ��ꍇ�́C��͉”\����ꗗ��\�� if (!cmd.hasOption("l")) { err.println("Available languages;"); for (final LANGUAGE language : LANGUAGE.values()) { err.println("\t" + language.getName() + ": can be specified with term \"" + language.getIdentifierName() + "\""); } // -l �Ō��ꂪ�w�肳��Ă���ꍇ�́C���̃v���O���~���O����Ŏg�p�”\�ȃ��g���N�X�ꗗ��\�� } else { Settings.getInstance().setLanguage(cmd.getOptionValue("l")); err.println("Available metrics for " + Settings.getInstance().getLanguage().getName()); metricsTool.loadPlugins(Settings.getInstance().getMetrics()); for (final AbstractPlugin plugin : DataManager.getInstance().getPluginManager() .getPlugins()) { final PluginInfo pluginInfo = plugin.getPluginInfo(); if (pluginInfo.isMeasurable(Settings.getInstance().getLanguage())) { err.println("\t" + pluginInfo.getMetricName()); } } } System.exit(0); } Settings.getInstance().setVerbose(cmd.hasOption("v")); if (cmd.hasOption("d")) { Settings.getInstance().setTargetDirectory(cmd.getOptionValue("d")); } if (cmd.hasOption("i")) { Settings.getInstance().setListFile(cmd.getOptionValue("i")); } Settings.getInstance().setLanguage(cmd.getOptionValue("l")); if (cmd.hasOption("m")) { Settings.getInstance().setMetrics(cmd.getOptionValue("m")); } if (cmd.hasOption("F")) { Settings.getInstance().setFileMetricsFile(cmd.getOptionValue("F")); } if (cmd.hasOption("C")) { Settings.getInstance().setClassMetricsFile(cmd.getOptionValue("C")); } if (cmd.hasOption("M")) { Settings.getInstance().setMethodMetricsFile(cmd.getOptionValue("M")); } if (cmd.hasOption("A")) { Settings.getInstance().setFieldMetricsFile(cmd.getOptionValue("A")); } metricsTool.loadPlugins(Settings.getInstance().getMetrics()); // �R�}���h���C�����������������ǂ����`�F�b�N���� { // -d �� -i �̂ǂ�����w�肳��Ă���͕̂s�� if (!cmd.hasOption("d") && !cmd.hasOption("l")) { err.println("-d and/or -i must be specified in the analysis mode!"); System.exit(0); } // ���ꂪ�w�肳��Ȃ������͕̂s�� if (!cmd.hasOption("l")) { err.println("-l must be specified for analysis"); System.exit(0); } { // �t�@�C�����g���N�X���v������ꍇ�� -F �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getFileMetricPlugins() .size()) && !cmd.hasOption("F")) { err.println("-F must be specified for file metrics!"); System.exit(0); } // �N���X���g���N�X���v������ꍇ�� -C �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getClassMetricPlugins() .size()) && !cmd.hasOption("C")) { err.println("-C must be specified for class metrics!"); System.exit(0); } // ���\�b�h���g���N�X���v������ꍇ�� -M �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getMethodMetricPlugins() .size()) && !cmd.hasOption("M")) { err.println("-M must be specified for method metrics!"); System.exit(0); } // �t�B�[���h���g���N�X���v������ꍇ�� -A �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getFieldMetricPlugins() .size()) && !cmd.hasOption("A")) { err.println("-A must be specified for field metrics!"); System.exit(0); } } { // �t�@�C�����g���N�X���v�����Ȃ��̂� -F�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getFileMetricPlugins() .size()) && cmd.hasOption("F")) { err.println("No file metric is specified. -F is ignored."); } // �N���X���g���N�X���v�����Ȃ��̂� -C�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getClassMetricPlugins() .size()) && cmd.hasOption("C")) { err.println("No class metric is specified. -C is ignored."); } // ���\�b�h���g���N�X���v�����Ȃ��̂� -M�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getMethodMetricPlugins() .size()) && cmd.hasOption("M")) { err.println("No method metric is specified. -M is ignored."); } // �t�B�[���h���g���N�X���v�����Ȃ��̂� -A�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getFieldMetricPlugins() .size()) && cmd.hasOption("A")) { err.println("No field metric is specified. -A is ignored."); } } } } catch (ParseException e) { System.out.println(e.getMessage()); System.exit(0); } final long start = System.nanoTime(); metricsTool.readTargetFiles(); metricsTool.analyzeTargetFiles(); metricsTool.launchPlugins(); metricsTool.writeMetrics(); out.println("successfully finished."); final long end = System.nanoTime(); if (Settings.getInstance().isVerbose()) { out.println("elapsed time: " + (end - start) / 1000000000 + " seconds"); out.println("number of analyzed files: " + DataManager.getInstance().getFileInfoManager().getFileInfos().size()); int loc = 0; for (final FileInfo file : DataManager.getInstance().getFileInfoManager() .getFileInfos()) { loc += file.getLOC(); } out.println("analyzed lines of code: " + loc); } MessagePool.getInstance(MESSAGE_TYPE.OUT).removeMessageListener(outListener); MessagePool.getInstance(MESSAGE_TYPE.ERROR).removeMessageListener(errListener); } /** * ���������R���X�g���N�^�D �Z�L�����e�B�}�l�[�W���̏��������s���D */ public MetricsTool() { initSecurityManager(); } /** * {@link #readTargetFiles()} �œǂݍ��񂾑Ώۃt�@�C���Q����͂���. * */ public void analyzeTargetFiles() { // �Ώۃt�@�C������� AstVisitorManager<AST> visitorManager = null; switch (Settings.getInstance().getLanguage()) { case JAVA15: visitorManager = new JavaAstVisitorManager<AST>(new AntlrAstVisitor( new Java15AntlrAstTranslator())); break; case JAVA14: visitorManager = new JavaAstVisitorManager<AST>(new AntlrAstVisitor( new Java14AntlrAstTranslator())); break; case JAVA13: visitorManager = new JavaAstVisitorManager<AST>(new AntlrAstVisitor( new Java13AntlrAstTranslator())); break; case CSHARP: visitorManager = new JavaAstVisitorManager<AST>(new AntlrAstVisitor( new CSharpAntlrAstTranslator())); break; default: assert false : "here shouldn't be reached!"; } // �Ώۃt�@�C����AST���疢�����N���X�C�t�B�[���h�C���\�b�h�����擾 { out.println("parsing all target files."); final int totalFileNumber = DataManager.getInstance().getTargetFileManager().size(); int currentFileNumber = 1; final StringBuffer fileInformationBuffer = new StringBuffer(); for (final TargetFile targetFile : DataManager.getInstance().getTargetFileManager()) { try { final String name = targetFile.getName(); final FileInfo fileInfo = new FileInfo(name); DataManager.getInstance().getFileInfoManager().add(fileInfo); if (Settings.getInstance().isVerbose()) { fileInformationBuffer.delete(0, fileInformationBuffer.length()); fileInformationBuffer.append("parsing "); fileInformationBuffer.append(name); fileInformationBuffer.append(" ["); fileInformationBuffer.append(currentFileNumber++); fileInformationBuffer.append("/"); fileInformationBuffer.append(totalFileNumber); fileInformationBuffer.append("]"); out.println(fileInformationBuffer.toString()); } switch (Settings.getInstance().getLanguage()) { case JAVA15: final Java15Lexer java15lexer = new Java15Lexer(new FileInputStream(name)); java15lexer.setTabSize(1); final Java15Parser java15parser = new Java15Parser(java15lexer); final ASTFactory java15factory = new MasuAstFactory(); java15factory.setASTNodeClass(CommonASTWithLineNumber.class); java15parser.setASTFactory(java15factory); java15parser.compilationUnit(); targetFile.setCorrectSytax(true); if (visitorManager != null) { visitorManager.visitStart(java15parser.getAST()); } fileInfo.setLOC(java15lexer.getLine()); break; case JAVA14: final Java14Lexer java14lexer = new Java14Lexer(new FileInputStream(name)); java14lexer.setTabSize(1); final Java14Parser java14parser = new Java14Parser(java14lexer); final ASTFactory java14factory = new MasuAstFactory(); java14factory.setASTNodeClass(CommonASTWithLineNumber.class); java14parser.setASTFactory(java14factory); java14parser.compilationUnit(); targetFile.setCorrectSytax(true); if (visitorManager != null) { visitorManager.visitStart(java14parser.getAST()); } fileInfo.setLOC(java14lexer.getLine()); break; case CSHARP: final CSharpLexer csharpLexer = new CSharpLexer(new FileInputStream(name)); csharpLexer.setTabSize(1); final CSharpParser csharpParser = new CSharpParser(csharpLexer); final ASTFactory cshaprFactory = new MasuAstFactory(); cshaprFactory.setASTNodeClass(CommonASTWithLineNumber.class); csharpParser.setASTFactory(cshaprFactory); csharpParser.compilationUnit(); targetFile.setCorrectSytax(true); if (visitorManager != null) { visitorManager.visitStart(csharpParser.getAST()); } fileInfo.setLOC(csharpLexer.getLine()); break; default: assert false : "here shouldn't be reached!"; } } catch (FileNotFoundException e) { err.println(e.getMessage()); } catch (RecognitionException e) { targetFile.setCorrectSytax(false); err.println(e.getMessage()); // TODO �G���[���N���������Ƃ� TargetFileData �Ȃǂɒʒm���鏈�����K�v } catch (TokenStreamException e) { targetFile.setCorrectSytax(false); err.println(e.getMessage()); // TODO �G���[���N���������Ƃ� TargetFileData �Ȃǂɒʒm���鏈�����K�v } catch (ASTParseException e) { err.println(e.getMessage()); } } } out.println("resolving definitions and usages."); if (Settings.getInstance().isVerbose()) { out.println("STEP1 : resolve class definitions."); } registClassInfos(); if (Settings.getInstance().isVerbose()) { out.println("STEP2 : resolve type parameters of classes."); } resolveTypeParameterOfClassInfos(); if (Settings.getInstance().isVerbose()) { out.println("STEP3 : resolve class inheritances."); } addInheritanceInformationToClassInfos(); if (Settings.getInstance().isVerbose()) { out.println("STEP4 : resolve field definitions."); } registFieldInfos(); if (Settings.getInstance().isVerbose()) { out.println("STEP5 : resolve method definitions."); } registMethodInfos(); if (Settings.getInstance().isVerbose()) { out.println("STEP6 : resolve type parameter usages."); } addClassTypeParameterInfos(); addMethodTypeParameterInfos(); if (Settings.getInstance().isVerbose()) { out.println("STEP7 : resolve method overrides."); } addOverrideRelation(); if (Settings.getInstance().isVerbose()) { out.println("STEP8 : resolve field and method usages."); } addReferenceAssignmentCallRelateion(); // ���@���̂���t�@�C���ꗗ��\�� // err.println("The following files includes uncorrect syntax."); // err.println("Any metrics of them were not measured"); for (final TargetFile targetFile : DataManager.getInstance().getTargetFileManager()) { if (!targetFile.isCorrectSyntax()) { err.println("Incorrect syntax file: " + targetFile.getName()); } } } /** * �v���O�C�������[�h����. �w�肳�ꂽ����C�w�肳�ꂽ���g���N�X�Ɋ֘A����v���O�C���݂̂� {@link PluginManager}�ɓo�^����. * null ���w�肳�ꂽ�ꍇ�͑Ώی���ɂ����Čv���”\�ȑS�Ẵ��g���N�X��o�^���� * * @param metrics �w�肷�郁�g���N�X�̔z��C�w�肵�Ȃ��ꍇ��null */ public void loadPlugins(final String[] metrics) { final PluginManager pluginManager = DataManager.getInstance().getPluginManager(); final Settings settings = Settings.getInstance(); try { for (final AbstractPlugin plugin : (new DefaultPluginLoader()).loadPlugins()) {// �v���O�C����S���[�h final PluginInfo info = plugin.getPluginInfo(); // �Ώی���Ōv���”\�łȂ���Γo�^���Ȃ� if (!info.isMeasurable(settings.getLanguage())) { continue; } if (null != metrics) { // ���g���N�X���w�肳��Ă���̂ł��̃v���O�C���ƈ�v���邩�`�F�b�N final String pluginMetricName = info.getMetricName(); for (final String metric : metrics) { if (metric.equalsIgnoreCase(pluginMetricName)) { pluginManager.addPlugin(plugin); break; } } // ���g���N�X���w�肳��Ă��Ȃ��̂łƂ肠�����S���o�^ } else { pluginManager.addPlugin(plugin); } } } catch (PluginLoadException e) { err.println(e.getMessage()); System.exit(0); } } /** * ���[�h�ς݂̃v���O�C�������s����. */ public void launchPlugins() { out.println("calculating metrics."); PluginLauncher launcher = new DefaultPluginLauncher(); launcher.setMaximumLaunchingNum(1); launcher.launchAll(DataManager.getInstance().getPluginManager().getPlugins()); do { try { Thread.sleep(1000); } catch (InterruptedException e) { // �C�ɂ��Ȃ� } } while (0 < launcher.getCurrentLaunchingNum() + launcher.getLaunchWaitingTaskNum()); launcher.stopLaunching(); } /** * {@link Settings}�Ɏw�肳�ꂽ�ꏊ�����͑Ώۃt�@�C����ǂݍ���œo�^���� */ public void readTargetFiles() { out.println("building target file list."); final Settings settings = Settings.getInstance(); // �f�B���N�g������ǂݍ��� if (null != settings.getTargetDirectory()) { File targetDirectory = new File(settings.getTargetDirectory()); registerFilesFromDirectory(targetDirectory); // ���X�g�t�@�C������ǂݍ��� } else if (null != settings.getListFile()) { try { final TargetFileManager targetFiles = DataManager.getInstance() .getTargetFileManager(); for (BufferedReader reader = new BufferedReader(new FileReader(settings .getListFile())); reader.ready();) { final String line = reader.readLine(); final TargetFile targetFile = new TargetFile(line); targetFiles.add(targetFile); } } catch (FileNotFoundException e) { err.println("\"" + settings.getListFile() + "\" is not a valid file!"); System.exit(0); } catch (IOException e) { err.println("\"" + settings.getListFile() + "\" can\'t read!"); System.exit(0); } } } /** * ���g���N�X���� {@link Settings} �Ɏw�肳�ꂽ�t�@�C���ɏo�͂���. */ public void writeMetrics() { final PluginManager pluginManager = DataManager.getInstance().getPluginManager(); final Settings settings = Settings.getInstance(); // �t�@�C�����g���N�X���v������ꍇ if (0 < pluginManager.getFileMetricPlugins().size()) { try { final FileMetricsInfoManager manager = DataManager.getInstance() .getFileMetricsInfoManager(); manager.checkMetrics(); final String fileName = settings.getFileMetricsFile(); final CSVFileMetricsWriter writer = new CSVFileMetricsWriter(fileName); writer.write(); } catch (MetricNotRegisteredException e) { err.println(e.getMessage()); err.println("File metrics can't be output!"); } } // �N���X���g���N�X���v������ꍇ if (0 < pluginManager.getClassMetricPlugins().size()) { try { final ClassMetricsInfoManager manager = DataManager.getInstance() .getClassMetricsInfoManager(); manager.checkMetrics(); final String fileName = settings.getClassMetricsFile(); final CSVClassMetricsWriter writer = new CSVClassMetricsWriter(fileName); writer.write(); } catch (MetricNotRegisteredException e) { err.println(e.getMessage()); err.println("Class metrics can't be output!"); } } // ���\�b�h���g���N�X���v������ꍇ if (0 < pluginManager.getMethodMetricPlugins().size()) { try { final MethodMetricsInfoManager manager = DataManager.getInstance() .getMethodMetricsInfoManager(); manager.checkMetrics(); final String fileName = settings.getMethodMetricsFile(); final CSVMethodMetricsWriter writer = new CSVMethodMetricsWriter(fileName); writer.write(); } catch (MetricNotRegisteredException e) { err.println(e.getMessage()); err.println("Method metrics can't be output!"); } } // �t�B�[���h���g���N�X���v������ꍇ if (0 < pluginManager.getFieldMetricPlugins().size()) { try { final FieldMetricsInfoManager manager = DataManager.getInstance() .getFieldMetricsInfoManager(); manager.checkMetrics(); final String fileName = settings.getMethodMetricsFile(); final CSVMethodMetricsWriter writer = new CSVMethodMetricsWriter(fileName); writer.write(); } catch (MetricNotRegisteredException e) { err.println(e.getMessage()); err.println("Field metrics can't be output!"); } } } /** * {@link MetricsToolSecurityManager} �̏��������s��. �V�X�e���ɓo�^�ł���΁C�V�X�e���̃Z�L�����e�B�}�l�[�W���ɂ��o�^����. */ private final void initSecurityManager() { try { // MetricsToolSecurityManager�̃V���O���g���C���X�^���X���\�z���C�������ʌ����X���b�h�ɂȂ� System.setSecurityManager(MetricsToolSecurityManager.getInstance()); } catch (final SecurityException e) { // ���ɃZ�b�g����Ă���Z�L�����e�B�}�l�[�W���ɂ���āC�V���ȃZ�L�����e�B�}�l�[�W���̓o�^�����‚���Ȃ������D // �V�X�e���̃Z�L�����e�B�}�l�[�W���Ƃ��Ďg��Ȃ��Ă��C���ʌ����X���b�h�̃A�N�Z�X����͖��Ȃ����삷��̂łƂ肠������������ err .println("Failed to set system security manager. MetricsToolsecurityManager works only to manage privilege threads."); } } /** * * @param file �Ώۃt�@�C���܂��̓f�B���N�g�� * * �Ώۂ��f�B���N�g���̏ꍇ�́C���̎q�ɑ΂��čċA�I�ɏ���������D �Ώۂ��t�@�C���̏ꍇ�́C�Ώی���̃\�[�X�t�@�C���ł���΁C�o�^�������s���D */ private void registerFilesFromDirectory(final File file) { // �f�B���N�g���Ȃ�΁C�ċA�I�ɏ��� if (file.isDirectory()) { File[] subfiles = file.listFiles(); for (int i = 0; i < subfiles.length; i++) { registerFilesFromDirectory(subfiles[i]); } // �t�@�C���Ȃ�΁C�g���q���Ώی���ƈ�v����Γo�^ } else if (file.isFile()) { final LANGUAGE language = Settings.getInstance().getLanguage(); final String extension = language.getExtension(); final String path = file.getAbsolutePath(); if (path.endsWith(extension)) { final TargetFileManager targetFiles = DataManager.getInstance() .getTargetFileManager(); final TargetFile targetFile = new TargetFile(path); targetFiles.add(targetFile); } // �f�B���N�g���ł��t�@�C���ł��Ȃ��ꍇ�͕s�� } else { err.println("\"" + file.getAbsolutePath() + "\" is not a vaild file!"); System.exit(0); } } /** * �o�̓��b�Z�[�W�o�͗p�̃v�����^ */ protected static MessagePrinter out = new DefaultMessagePrinter(new MessageSource() { public String getMessageSourceName() { return "main"; } }, MESSAGE_TYPE.OUT); /** * �G���[���b�Z�[�W�o�͗p�̃v�����^ */ protected static MessagePrinter err = new DefaultMessagePrinter(new MessageSource() { public String getMessageSourceName() { return "main"; } }, MESSAGE_TYPE.ERROR); /** * �N���X�̒�`�� ClassInfoManager �ɓo�^����DAST �p�[�X�̌�ɌĂяo���Ȃ���΂Ȃ�Ȃ��D */ private void registClassInfos() { // �������N���X���}�l�[�W���C �N���X���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = DataManager.getInstance() .getUnresolvedClassInfoManager(); final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager(); // �e�������N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager .getClassInfos()) { final FileInfo fileInfo = unresolvedClassInfo.getFileInfo(); //�@�N���X�������� final TargetClassInfo classInfo = unresolvedClassInfo.resolve(null, null, classInfoManager, null, null); fileInfo.addDefinedClass(classInfo); // �������ꂽ�N���X����o�^ classInfoManager.add(classInfo); // �e�C���i�[�N���X�ɑ΂��ď��� for (final UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo .getInnerClasses()) { //�@�C���i�[�N���X�������� final TargetInnerClassInfo innerClass = registInnerClassInfo( unresolvedInnerClassInfo, classInfo, classInfoManager); // �������ꂽ�C���i�[�N���X����o�^ classInfo.addInnerClass(innerClass); classInfoManager.add(innerClass); } } } /** * �C���i�[�N���X�̒�`�� ClassInfoManager �ɓo�^����D registClassInfos ����̂݌Ă΂��ׂ��ł���D * * @param unresolvedClassInfo ���O���������C���i�[�N���X�I�u�W�F�N�g * @param outerClass �O���̃N���X * @param classInfoManager �C���i�[�N���X��o�^����N���X�}�l�[�W�� * @return ���������C���i�[�N���X�� ClassInfo */ private TargetInnerClassInfo registInnerClassInfo( final UnresolvedClassInfo unresolvedClassInfo, final TargetClassInfo outerClass, final ClassInfoManager classInfoManager) { final TargetInnerClassInfo classInfo = (TargetInnerClassInfo) unresolvedClassInfo.resolve( outerClass, null, classInfoManager, null, null); // ���̃N���X�̃C���i�[�N���X�ɑ΂��čċA�I�ɏ��� for (final UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo .getInnerClasses()) { //�@�C���i�[�N���X�������� final TargetInnerClassInfo innerClass = registInnerClassInfo(unresolvedInnerClassInfo, classInfo, classInfoManager); // �������ꂽ�C���i�[�N���X����o�^ classInfo.addInnerClass(innerClass); classInfoManager.add(innerClass); } // ���̃N���X�� ClassInfo ��Ԃ� return classInfo; } /** * �N���X�̌^�p�����[�^�𖼑O��������DregistClassInfos �̌�C ����addInheritanceInformationToClassInfo * �̑O�ɌĂяo���Ȃ���΂Ȃ�Ȃ��D * */ private void resolveTypeParameterOfClassInfos() { // �������N���X���}�l�[�W���C �����ς݃N���X�}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = DataManager.getInstance() .getUnresolvedClassInfoManager(); final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager(); // �e�������N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager .getClassInfos()) { resolveTypeParameterOfClassInfos(unresolvedClassInfo, classInfoManager); } } /** * �N���X�̌^�p�����[�^�𖼑O��������D resolveTypeParameterOfClassInfo() ������̂݌Ăяo�����ׂ� * * @param unresolvedClassInfo ���O��������^�p�����[�^�����ƒN���X * @param classInfoManager ���O�����ɗp����N���X�}�l�[�W�� */ private void resolveTypeParameterOfClassInfos(final UnresolvedClassInfo unresolvedClassInfo, final ClassInfoManager classInfoManager) { // �����ς݃N���X�����擾 final TargetClassInfo classInfo = unresolvedClassInfo.getResolved(); assert null != classInfo : "classInfo shouldn't be null!"; // �������N���X��񂩂疢�����^�p�����[�^���擾���C�^�������s������C�����ς݃N���X���ɕt�^���� for (final UnresolvedTypeParameterInfo unresolvedTypeParameter : unresolvedClassInfo .getTypeParameters()) { final TypeInfo typeParameter = unresolvedTypeParameter.resolve(classInfo, null, classInfoManager, null, null); classInfo.addTypeParameter((TypeParameterInfo) typeParameter); } // �e�������C���i�[�N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo .getInnerClasses()) { resolveTypeParameterOfClassInfos(unresolvedInnerClassInfo, classInfoManager); } } /** * �N���X�̌p������ ClassInfo �ɒlj�����D��x�ڂ� AST �p�[�X�̌�C���� registClassInfos �̌�ɂ�т����Ȃ���΂Ȃ�Ȃ��D */ private void addInheritanceInformationToClassInfos() { // Unresolved �N���X���}�l�[�W���C �N���X���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = DataManager.getInstance() .getUnresolvedClassInfoManager(); final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager(); final FieldInfoManager fieldInfoManager = DataManager.getInstance().getFieldInfoManager(); final MethodInfoManager methodInfoManager = DataManager.getInstance() .getMethodInfoManager(); // ���O�����s�”\�N���X��ۑ����邽�߂̃��X�g final List<UnresolvedClassInfo> unresolvableClasses = new LinkedList<UnresolvedClassInfo>(); // �e Unresolved�N���X�ɑ΂��� for (UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager.getClassInfos()) { addInheritanceInformationToClassInfo(unresolvedClassInfo, classInfoManager, fieldInfoManager, methodInfoManager, unresolvableClasses); } // ���O�����s�”\�N���X����͂��� for (int i = 0; i < 100; i++) { CLASSLOOP: for (final Iterator<UnresolvedClassInfo> classIterator = unresolvableClasses .iterator(); classIterator.hasNext();) { // ClassInfo ���擾 final UnresolvedClassInfo unresolvedClassInfo = classIterator.next(); final TargetClassInfo classInfo = unresolvedClassInfo.getResolved(); assert null != classInfo : "classInfo shouldn't be null!"; // �e�e�N���X���ɑ΂��� for (final UnresolvedClassTypeInfo unresolvedSuperClassType : unresolvedClassInfo .getSuperClasses()) { TypeInfo superClassType = unresolvedSuperClassType.resolve(classInfo, null, classInfoManager, null, null); // null �łȂ��ꍇ�͖��O�����ɐ��������Ƃ݂Ȃ� if (null != superClassType) { // ���‚���Ȃ������ꍇ�͖��O��Ԗ���UNKNOWN�ȃN���X��o�^���� if (superClassType instanceof UnknownTypeInfo) { final ExternalClassInfo superClass = new ExternalClassInfo( unresolvedSuperClassType.getTypeName()); classInfoManager.add(superClass); superClassType = new ClassTypeInfo(superClass); } classInfo.addSuperClass((ClassTypeInfo) superClassType); ((ClassTypeInfo) superClassType).getReferencedClass() .addSubClass(classInfo); // null �ȏꍇ�͖��O�����Ɏ��s�����Ƃ݂Ȃ��̂� unresolvedClassInfo �� unresolvableClasses // ����폜���Ȃ� } else { continue CLASSLOOP; } } classIterator.remove(); } // ����ׂ� unresolvableClasses �����ւ� Collections.shuffle(unresolvableClasses); } if (0 < unresolvableClasses.size()) { err.println("There are " + unresolvableClasses.size() + " unresolvable class inheritance"); } } /** * �N���X�̌p������ InnerClassInfo �ɒlj�����DaddInheritanceInformationToClassInfos �̒�����̂݌Ăяo�����ׂ� * * @param unresolvedClassInfo �p���֌W��lj�����i�������j�N���X��� * @param classInfoManager ���O�����ɗp����N���X�}�l�[�W�� */ private void addInheritanceInformationToClassInfo( final UnresolvedClassInfo unresolvedClassInfo, final ClassInfoManager classInfoManager, final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager, final List<UnresolvedClassInfo> unresolvableClasses) { // ClassInfo ���擾 final TargetClassInfo classInfo = unresolvedClassInfo.getResolved(); assert null != classInfo : "classInfo shouldn't be null!"; // �e�e�N���X���ɑ΂��� for (final UnresolvedClassTypeInfo unresolvedSuperClassType : unresolvedClassInfo .getSuperClasses()) { TypeInfo superClassType = unresolvedSuperClassType.resolve(classInfo, null, classInfoManager, fieldInfoManager, methodInfoManager); // null �������ꍇ�͉����s�”\���X�g�Ɉꎞ�I�Ɋi�[ if (null == superClassType) { unresolvableClasses.add(unresolvedClassInfo); } else { // ���‚���Ȃ������ꍇ�͖��O��Ԗ���UNKNOWN�ȃN���X��o�^���� if (superClassType instanceof UnknownTypeInfo) { final ExternalClassInfo superClass = new ExternalClassInfo( unresolvedSuperClassType.getTypeName()); classInfoManager.add(superClass); } classInfo.addSuperClass((ClassTypeInfo) superClassType); ((ClassTypeInfo) superClassType).getReferencedClass().addSubClass(classInfo); } } // �e�C���i�[�N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo .getInnerClasses()) { addInheritanceInformationToClassInfo(unresolvedInnerClassInfo, classInfoManager, fieldInfoManager, methodInfoManager, unresolvableClasses); } } /** * �t�B�[���h�̒�`�� FieldInfoManager �ɓo�^����D registClassInfos �̌�ɌĂяo���Ȃ���΂Ȃ�Ȃ� * */ private void registFieldInfos() { // Unresolved �N���X���}�l�[�W���C�N���X���}�l�[�W���C�t�B�[���h���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = DataManager.getInstance() .getUnresolvedClassInfoManager(); final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager(); final FieldInfoManager fieldInfoManager = DataManager.getInstance().getFieldInfoManager(); final MethodInfoManager methodInfoManager = DataManager.getInstance() .getMethodInfoManager(); // �e Unresolved�N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager .getClassInfos()) { registFieldInfos(unresolvedClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } } /** * �t�B�[���h�̒�`�� FieldInfoManager �ɓo�^����D * * @param unresolvedClassInfo �t�B�[���h�����ΏۃN���X * @param classInfoManager �p����N���X�}�l�[�W�� * @param fieldInfoManager �p����t�B�[���h�}�l�[�W�� */ private void registFieldInfos(final UnresolvedClassInfo unresolvedClassInfo, final ClassInfoManager classInfoManager, final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) { // ClassInfo ���擾 final TargetClassInfo ownerClass = unresolvedClassInfo.getResolved(); assert null != ownerClass : "ownerClass shouldn't be null!"; // �e�������t�B�[���h�ɑ΂��� for (final UnresolvedFieldInfo unresolvedFieldInfo : unresolvedClassInfo.getDefinedFields()) { unresolvedFieldInfo.resolve(ownerClass, null, classInfoManager, fieldInfoManager, methodInfoManager); } // �e�C���i�[�N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo .getInnerClasses()) { registFieldInfos(unresolvedInnerClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } } /** * ���\�b�h�̒�`�� MethodInfoManager �ɓo�^����DregistClassInfos �̌�ɌĂяo���Ȃ���΂Ȃ�Ȃ��D */ private void registMethodInfos() { // Unresolved �N���X���}�l�[�W���C �N���X���}�l�[�W���C���\�b�h���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = DataManager.getInstance() .getUnresolvedClassInfoManager(); final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager(); final FieldInfoManager fieldInfoManager = DataManager.getInstance().getFieldInfoManager(); final MethodInfoManager methodInfoManager = DataManager.getInstance() .getMethodInfoManager(); // �e Unresolved�N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager .getClassInfos()) { registMethodInfos(unresolvedClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } } /** * ���������\�b�h��`�����������C���\�b�h�}�l�[�W���ɓo�^����D * * @param unresolvedClassInfo ���\�b�h�����ΏۃN���X * @param classInfoManager �p����N���X�}�l�[�W�� * @param methodInfoManager �p���郁�\�b�h�}�l�[�W�� */ private void registMethodInfos(final UnresolvedClassInfo unresolvedClassInfo, final ClassInfoManager classInfoManager, final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) { // ClassInfo ���擾 final TargetClassInfo ownerClass = unresolvedClassInfo.getResolved(); // �e���������\�b�h�ɑ΂��� for (final UnresolvedMethodInfo unresolvedMethodInfo : unresolvedClassInfo .getDefinedMethods()) { // ���\�b�h�������� final TargetMethodInfo methodInfo = unresolvedMethodInfo.resolve(ownerClass, null, classInfoManager, fieldInfoManager, methodInfoManager); // ���\�b�h����o�^ ownerClass.addDefinedMethod(methodInfo); methodInfoManager.add(methodInfo); } // �e�������R���X�g���N�^�ɑ΂��� for (final UnresolvedConstructorInfo unresolvedConstructorInfo : unresolvedClassInfo .getDefinedConstructors()) { //�@�R���X�g���N�^�������� final TargetConstructorInfo constructorInfo = unresolvedConstructorInfo.resolve( ownerClass, null, classInfoManager, fieldInfoManager, methodInfoManager); methodInfoManager.add(constructorInfo); // �R���X�g���N�^����o�^ ownerClass.addDefinedConstructor(constructorInfo); methodInfoManager.add(constructorInfo); } // �e Unresolved�N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo .getInnerClasses()) { registMethodInfos(unresolvedInnerClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } } private void addClassTypeParameterInfos() { for (final TargetClassInfo classInfo : DataManager.getInstance().getClassInfoManager() .getTargetClassInfos()) { addClassTypeParameterInfos(classInfo); } } private void addClassTypeParameterInfos(final TargetClassInfo classInfo) { final List<ClassTypeInfo> superClassTypes = classInfo.getSuperClasses(); for (final ClassTypeInfo superClassType : superClassTypes) { final ClassInfo superClassInfo = superClassType.getReferencedClass(); if (superClassInfo instanceof TargetClassInfo) { addClassTypeParameterInfos((TargetClassInfo) superClassInfo); // �e�N���X�ȏ�ɂ�����^�p�����[�^�̎g�p���擾 final Map<TypeParameterInfo, TypeInfo> typeParameterUsages = ((TargetClassInfo) superClassInfo) .getTypeParameterUsages(); for (final TypeParameterInfo typeParameterInfo : typeParameterUsages.keySet()) { final TypeInfo usedType = typeParameterUsages.get(typeParameterInfo); classInfo.addTypeParameterUsage(typeParameterInfo, usedType); } // ���̃N���X�ɂ�����^�p�����[�^�̎g�p���擾 final List<TypeInfo> typeArguments = superClassType.getTypeArguments(); for (int index = 0; index < typeArguments.size(); index++) { final TypeInfo usedType = typeArguments.get(index); final TypeParameterInfo typeParameterInfo = ((TargetClassInfo) superClassInfo) .getTypeParameter(index); classInfo.addTypeParameterUsage(typeParameterInfo, usedType); } } } } private void addMethodTypeParameterInfos() { for (final TargetMethodInfo methodInfo : DataManager.getInstance().getMethodInfoManager() .getTargetMethodInfos()) { addMethodTypeParameterInfos(methodInfo); } } private void addMethodTypeParameterInfos(final TargetMethodInfo methodInfo) { //�@�܂��C�I�[�i�[�N���X�ɂ�����^�p�����[�^�g�p�̏���lj����� { final TargetClassInfo ownerClassInfo = (TargetClassInfo) methodInfo.getOwnerClass(); final Map<TypeParameterInfo, TypeInfo> typeParameterUsages = ownerClassInfo .getTypeParameterUsages(); for (final TypeParameterInfo typeParameterInfo : typeParameterUsages.keySet()) { final TypeInfo usedType = typeParameterUsages.get(typeParameterInfo); methodInfo.addTypeParameterUsage(typeParameterInfo, usedType); } } // TODO ���\�b�h���ɂ�����^�p�����[�^�g�p��lj����ׂ��H } /** * ���\�b�h�I�[�o�[���C�h�����eMethodInfo�ɒlj�����DaddInheritanceInfomationToClassInfos �̌� ���� registMethodInfos * �̌�ɌĂяo���Ȃ���΂Ȃ�Ȃ� */ private void addOverrideRelation() { // �S�Ă̑ΏۃN���X�ɑ΂��� for (final TargetClassInfo classInfo : DataManager.getInstance().getClassInfoManager() .getTargetClassInfos()) { addOverrideRelation(classInfo); } } /** * ���\�b�h�I�[�o�[���C�h�����eMethodInfo�ɒlj�����D�����Ŏw�肵���N���X�̃��\�b�h�ɂ‚��ď������s�� * * @param classInfo �ΏۃN���X */ private void addOverrideRelation(final TargetClassInfo classInfo) { // �e�e�N���X�ɑ΂��� for (final ClassInfo superClassInfo : ClassTypeInfo.convert(classInfo.getSuperClasses())) { // �e�ΏۃN���X�̊e���\�b�h�ɂ‚��āC�e�N���X�̃��\�b�h���I�[�o�[���C�h���Ă��邩�𒲍� for (final MethodInfo methodInfo : classInfo.getDefinedMethods()) { addOverrideRelation(superClassInfo, methodInfo); } } // �e�C���i�[�N���X�ɑ΂��� for (ClassInfo innerClassInfo : classInfo.getInnerClasses()) { addOverrideRelation((TargetClassInfo) innerClassInfo); } } /** * ���\�b�h�I�[�o�[���C�h����lj�����D�����Ŏw�肳�ꂽ�N���X�Œ�`����Ă��郁�\�b�h�ɑ΂��đ�����s��. * AddOverrideInformationToMethodInfos()�̒�����̂݌Ăяo�����D * * @param classInfo �N���X��� * @param overrider �I�[�o�[���C�h�Ώۂ̃��\�b�h */ private void addOverrideRelation(final ClassInfo classInfo, final MethodInfo overrider) { if ((null == classInfo) || (null == overrider)) { throw new NullPointerException(); } if (!(classInfo instanceof TargetClassInfo)) { return; } for (final TargetMethodInfo methodInfo : ((TargetClassInfo) classInfo).getDefinedMethods()) { // ���\�b�h�����Ⴄ�ꍇ�̓I�[�o�[���C�h����Ȃ� if (!methodInfo.getMethodName().equals(overrider.getMethodName())) { continue; } // �I�[�o�[���C�h�֌W��o�^���� overrider.addOverridee(methodInfo); methodInfo.addOverrider(overrider); // ���ڂ̃I�[�o�[���C�h�֌W�������o���Ȃ��̂ŁC���̃N���X�̐e�N���X�͒������Ȃ� return; } // �e�N���X�Q�ɑ΂��čċA�I�ɏ��� for (final ClassInfo superClassInfo : ClassTypeInfo.convert(classInfo.getSuperClasses())) { addOverrideRelation(superClassInfo, overrider); } } /** * �G���e�B�e�B�i�t�B�[���h��N���X�j�̑���E�Q�ƁC���\�b�h�̌Ăяo���֌W��lj�����D */ private void addReferenceAssignmentCallRelateion() { final UnresolvedClassInfoManager unresolvedClassInfoManager = DataManager.getInstance() .getUnresolvedClassInfoManager(); final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager(); final FieldInfoManager fieldInfoManager = DataManager.getInstance().getFieldInfoManager(); final MethodInfoManager methodInfoManager = DataManager.getInstance() .getMethodInfoManager(); // �e�������N���X��� �ɑ΂��� for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager .getClassInfos()) { addReferenceAssignmentCallRelation(unresolvedClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } } /** * �G���e�B�e�B�i�t�B�[���h��N���X�j�̑���E�Q�ƁC���\�b�h�̌Ăяo���֌W��lj�����D * * @param unresolvedClassInfo �����ΏۃN���X * @param classInfoManager �p����N���X�}�l�[�W�� * @param fieldInfoManager �p����t�B�[���h�}�l�[�W�� * @param methodInfoManager �p���郁�\�b�h�}�l�[�W�� * @param resolvedCache �����ς݌Ăяo�����̃L���b�V�� */ private void addReferenceAssignmentCallRelation(final UnresolvedClassInfo unresolvedClassInfo, final ClassInfoManager classInfoManager, final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) { // �������N���X��񂩂�C�����ς݃N���X�����擾 // final TargetClassInfo ownerClass = unresolvedClassInfo.getResolvedUnit(); // �e���������\�b�h���ɑ΂��� for (final UnresolvedMethodInfo unresolvedMethodInfo : unresolvedClassInfo .getDefinedMethods()) { // ���������\�b�h�����̗��p�֌W������ this.addReferenceAssignmentCallRelation(unresolvedMethodInfo, unresolvedClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } // �e�������R���X�g���N�^���ɑ΂��� for (final UnresolvedConstructorInfo unresolvedConstructorInfo : unresolvedClassInfo .getDefinedConstructors()) { // �������R���X�g���N�^�����̗��p�֌W������ this.addReferenceAssignmentCallRelation(unresolvedConstructorInfo, unresolvedClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } // �e�C���i�[�N���X�ɑ΂��� for (final UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo .getInnerClasses()) { addReferenceAssignmentCallRelation(unresolvedInnerClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } } /** * �G���e�B�e�B�i�t�B�[���h��N���X�j�̑���E�Q�ƁC���\�b�h�̌Ăяo���֌W��lj�����D * * @param unresolvedLocalSpace ��͑Ώۖ��������[�J���̈� * @param unresolvedClassInfo �����ΏۃN���X * @param classInfoManager �p����N���X�}�l�[�W�� * @param fieldInfoManager �p����t�B�[���h�}�l�[�W�� * @param methodInfoManager �p���郁�\�b�h�}�l�[�W�� * @param resolvedCache �����ς݌Ăяo�����̃L���b�V�� */ private void addReferenceAssignmentCallRelation( final UnresolvedLocalSpaceInfo<?> unresolvedLocalSpace, final UnresolvedClassInfo unresolvedClassInfo, final ClassInfoManager classInfoManager, final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) { // ���������\�b�h��񂩂�C�����ς݃��\�b�h�����擾 final LocalSpaceInfo localSpace = unresolvedLocalSpace.getResolved(); assert null != localSpace : "UnresolvedLocalSpaceInfo#getResolvedInfo is null!"; // ���L�N���X���擾 final TargetClassInfo ownerClass = (TargetClassInfo) localSpace.getOwnerClass(); final CallableUnitInfo ownerMethod; if (localSpace instanceof CallableUnitInfo) { ownerMethod = (CallableUnitInfo) localSpace; } else if (localSpace instanceof BlockInfo) { ownerMethod = ((BlockInfo) localSpace).getOwnerMethod(); } else { ownerMethod = null; assert false : "Here shouldn't be reached!"; } // �������̏ꍇ�C�������������̖��O�������� if (localSpace instanceof ConditionalBlockInfo) { final UnresolvedConditionalBlockInfo<?> unresolvedConditionalBlock = (UnresolvedConditionalBlockInfo<?>) unresolvedLocalSpace; if (null != unresolvedConditionalBlock.getConditionalClause()) { final ConditionalClauseInfo conditionalClause = unresolvedConditionalBlock .getConditionalClause().resolve(ownerClass, ownerMethod, classInfoManager, fieldInfoManager, methodInfoManager); try { final Class<?> cls = Class .forName("jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ConditionalBlockInfo"); final Field filed = cls.getDeclaredField("conditionalClause"); filed.setAccessible(true); filed.set(localSpace, conditionalClause); } catch (ClassNotFoundException e) { assert false : "Illegal state: ConditionalBlockInfo is not found"; } catch (NoSuchFieldException e) { assert false : "Illegal state: conditionalClause is not found"; } catch (IllegalAccessException e) { assert false; } } else { assert false; } } // �e�����������̖��O�������� for (final UnresolvedStatementInfo<? extends StatementInfo> unresolvedStatement : unresolvedLocalSpace .getStatements()) { if (!(unresolvedStatement instanceof UnresolvedBlockInfo)) { final StatementInfo statement = unresolvedStatement.resolve(ownerClass, ownerMethod, classInfoManager, fieldInfoManager, methodInfoManager); localSpace.addStatement(statement); } } // �e�������t�B�[���h�g�p�̖��O�������� for (final UnresolvedVariableUsageInfo<?> unresolvedVariableUsage : unresolvedLocalSpace .getVariableUsages()) { // �������ϐ��g�p������ final ExpressionInfo variableUsage = unresolvedVariableUsage.resolve(ownerClass, ownerMethod, classInfoManager, fieldInfoManager, methodInfoManager); // ���O�����ł����ꍇ�͓o�^ if (variableUsage instanceof VariableUsageInfo) { VariableUsageInfo<?> usage = (VariableUsageInfo<?>) variableUsage; localSpace.addVariableUsage(usage); //usage.getUsedVariable().addUsage(usage); // �t�B�[���h�̏ꍇ�́C���p�֌W������� if (variableUsage instanceof FieldUsageInfo) { final boolean reference = ((FieldUsageInfo) variableUsage).isReference(); final FieldInfo usedField = ((FieldUsageInfo) variableUsage).getUsedVariable(); if (reference) { usedField.addReferencer(ownerMethod); } else { usedField.addAssignmenter(ownerMethod); } } } } // �e���������\�b�h�Ăяo���̉������� for (final UnresolvedCallInfo<?> unresolvedCall : unresolvedLocalSpace.getCalls()) { final ExpressionInfo memberCall = unresolvedCall.resolve(ownerClass, ownerMethod, classInfoManager, fieldInfoManager, methodInfoManager); // ���\�b�h����уR���X�g���N�^�Ăяo���������ł����ꍇ if (memberCall instanceof MethodCallInfo) { localSpace.addCall((MethodCallInfo) memberCall); ((MethodCallInfo) memberCall).getCallee().addCaller(ownerMethod); } else if (memberCall instanceof ConstructorCallInfo) { localSpace.addCall((ConstructorCallInfo) memberCall); } } //�@�e�C���i�[�u���b�N�ɂ‚��� for (final UnresolvedStatementInfo<?> unresolvedStatement : unresolvedLocalSpace .getStatements()) { // ���������\�b�h�����̗��p�֌W������ if (unresolvedStatement instanceof UnresolvedBlockInfo) { this.addReferenceAssignmentCallRelation( (UnresolvedBlockInfo<?>) unresolvedStatement, unresolvedClassInfo, classInfoManager, fieldInfoManager, methodInfoManager); } } } }
true
true
public static void main(String[] args) { // ���\���p�̃��X�i���쐬 final MessageListener outListener = new MessageListener() { public void messageReceived(MessageEvent event) { System.out.print(event.getSource().getMessageSourceName() + " > " + event.getMessage()); } }; final MessageListener errListener = new MessageListener() { public void messageReceived(MessageEvent event) { System.out.print(event.getSource().getMessageSourceName() + " > " + event.getMessage()); } }; MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(outListener); MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(errListener); final Options options = new Options(); { final Option h = new Option("h", "help", false, "display usage"); h.setRequired(false); options.addOption(h); } { final Option v = new Option("v", "verbose", false, "output progress verbosely"); v.setRequired(false); options.addOption(v); } { final Option d = new Option("d", "directory", true, "specify target directory"); d.setArgName("directory"); d.setArgs(1); d.setRequired(false); options.addOption(d); } { final Option i = new Option("i", "input", true, "specify the input that contains the list of target files"); i.setArgName("input"); i.setArgs(1); i.setRequired(false); options.addOption(i); } { final Option l = new Option("l", "language", true, "specify programming language"); l.setArgName("input"); l.setArgs(1); l.setRequired(false); options.addOption(l); } { final Option m = new Option("m", "metrics", true, "specify measured metrics with comma separeted format (e.g., -m rfc,dit,lcom)"); m.setArgName("metrics"); m.setArgs(1); m.setRequired(false); options.addOption(m); } { final Option F = new Option("F", "FileMetricsFile", true, "specify file that measured FILE metrics were stored into"); F.setArgName("file metrics file"); F.setArgs(1); F.setRequired(false); options.addOption(F); } { final Option C = new Option("C", "ClassMetricsFile", true, "specify file that measured CLASS metrics were stored into"); C.setArgName("class metrics file"); C.setArgs(1); C.setRequired(false); options.addOption(C); } { final Option M = new Option("M", "MethodMetricsFile", true, "specify file that measured METHOD metrics were stored into"); M.setArgName("method metrics file"); M.setArgs(1); M.setRequired(false); options.addOption(M); } { final Option A = new Option("A", "AttributeMetricsFile", true, "specify file that measured ATTRIBUTE metrics were stored into"); A.setArgName("attribute metrics file"); A.setArgs(1); A.setRequired(false); options.addOption(A); } final MetricsTool metricsTool = new MetricsTool(); try { final CommandLineParser parser = new PosixParser(); final CommandLine cmd = parser.parse(options, args); // "-h"���w�肳��Ă���ꍇ�̓w���v��\�����ďI�� // ���̂Ƃ��C���̃I�v�V�����͑S�Ė�������� if (cmd.hasOption("h")) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("MetricsTool", options, true); // -l �Ō��ꂪ�w�肳��Ă��Ȃ��ꍇ�́C��͉”\����ꗗ��\�� if (!cmd.hasOption("l")) { err.println("Available languages;"); for (final LANGUAGE language : LANGUAGE.values()) { err.println("\t" + language.getName() + ": can be specified with term \"" + language.getIdentifierName() + "\""); } // -l �Ō��ꂪ�w�肳��Ă���ꍇ�́C���̃v���O���~���O����Ŏg�p�”\�ȃ��g���N�X�ꗗ��\�� } else { Settings.getInstance().setLanguage(cmd.getOptionValue("l")); err.println("Available metrics for " + Settings.getInstance().getLanguage().getName()); metricsTool.loadPlugins(Settings.getInstance().getMetrics()); for (final AbstractPlugin plugin : DataManager.getInstance().getPluginManager() .getPlugins()) { final PluginInfo pluginInfo = plugin.getPluginInfo(); if (pluginInfo.isMeasurable(Settings.getInstance().getLanguage())) { err.println("\t" + pluginInfo.getMetricName()); } } } System.exit(0); } Settings.getInstance().setVerbose(cmd.hasOption("v")); if (cmd.hasOption("d")) { Settings.getInstance().setTargetDirectory(cmd.getOptionValue("d")); } if (cmd.hasOption("i")) { Settings.getInstance().setListFile(cmd.getOptionValue("i")); } Settings.getInstance().setLanguage(cmd.getOptionValue("l")); if (cmd.hasOption("m")) { Settings.getInstance().setMetrics(cmd.getOptionValue("m")); } if (cmd.hasOption("F")) { Settings.getInstance().setFileMetricsFile(cmd.getOptionValue("F")); } if (cmd.hasOption("C")) { Settings.getInstance().setClassMetricsFile(cmd.getOptionValue("C")); } if (cmd.hasOption("M")) { Settings.getInstance().setMethodMetricsFile(cmd.getOptionValue("M")); } if (cmd.hasOption("A")) { Settings.getInstance().setFieldMetricsFile(cmd.getOptionValue("A")); } metricsTool.loadPlugins(Settings.getInstance().getMetrics()); // �R�}���h���C�����������������ǂ����`�F�b�N���� { // -d �� -i �̂ǂ�����w�肳��Ă���͕̂s�� if (!cmd.hasOption("d") && !cmd.hasOption("l")) { err.println("-d and/or -i must be specified in the analysis mode!"); System.exit(0); } // ���ꂪ�w�肳��Ȃ������͕̂s�� if (!cmd.hasOption("l")) { err.println("-l must be specified for analysis"); System.exit(0); } { // �t�@�C�����g���N�X���v������ꍇ�� -F �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getFileMetricPlugins() .size()) && !cmd.hasOption("F")) { err.println("-F must be specified for file metrics!"); System.exit(0); } // �N���X���g���N�X���v������ꍇ�� -C �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getClassMetricPlugins() .size()) && !cmd.hasOption("C")) { err.println("-C must be specified for class metrics!"); System.exit(0); } // ���\�b�h���g���N�X���v������ꍇ�� -M �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getMethodMetricPlugins() .size()) && !cmd.hasOption("M")) { err.println("-M must be specified for method metrics!"); System.exit(0); } // �t�B�[���h���g���N�X���v������ꍇ�� -A �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getFieldMetricPlugins() .size()) && !cmd.hasOption("A")) { err.println("-A must be specified for field metrics!"); System.exit(0); } } { // �t�@�C�����g���N�X���v�����Ȃ��̂� -F�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getFileMetricPlugins() .size()) && cmd.hasOption("F")) { err.println("No file metric is specified. -F is ignored."); } // �N���X���g���N�X���v�����Ȃ��̂� -C�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getClassMetricPlugins() .size()) && cmd.hasOption("C")) { err.println("No class metric is specified. -C is ignored."); } // ���\�b�h���g���N�X���v�����Ȃ��̂� -M�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getMethodMetricPlugins() .size()) && cmd.hasOption("M")) { err.println("No method metric is specified. -M is ignored."); } // �t�B�[���h���g���N�X���v�����Ȃ��̂� -A�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getFieldMetricPlugins() .size()) && cmd.hasOption("A")) { err.println("No field metric is specified. -A is ignored."); } } } } catch (ParseException e) { System.out.println(e.getMessage()); System.exit(0); } final long start = System.nanoTime(); metricsTool.readTargetFiles(); metricsTool.analyzeTargetFiles(); metricsTool.launchPlugins(); metricsTool.writeMetrics(); out.println("successfully finished."); final long end = System.nanoTime(); if (Settings.getInstance().isVerbose()) { out.println("elapsed time: " + (end - start) / 1000000000 + " seconds"); out.println("number of analyzed files: " + DataManager.getInstance().getFileInfoManager().getFileInfos().size()); int loc = 0; for (final FileInfo file : DataManager.getInstance().getFileInfoManager() .getFileInfos()) { loc += file.getLOC(); } out.println("analyzed lines of code: " + loc); } MessagePool.getInstance(MESSAGE_TYPE.OUT).removeMessageListener(outListener); MessagePool.getInstance(MESSAGE_TYPE.ERROR).removeMessageListener(errListener); }
public static void main(String[] args) { // ���\���p�̃��X�i���쐬 final MessageListener outListener = new MessageListener() { public void messageReceived(MessageEvent event) { System.out.print(event.getSource().getMessageSourceName() + " > " + event.getMessage()); } }; final MessageListener errListener = new MessageListener() { public void messageReceived(MessageEvent event) { System.out.print(event.getSource().getMessageSourceName() + " > " + event.getMessage()); } }; MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(outListener); MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(errListener); final Options options = new Options(); { final Option h = new Option("h", "help", false, "display usage"); h.setRequired(false); options.addOption(h); } { final Option v = new Option("v", "verbose", false, "output progress verbosely"); v.setRequired(false); options.addOption(v); } { final Option d = new Option("d", "directory", true, "specify target directory"); d.setArgName("directory"); d.setArgs(1); d.setRequired(false); options.addOption(d); } { final Option i = new Option("i", "input", true, "specify the input that contains the list of target files"); i.setArgName("input"); i.setArgs(1); i.setRequired(false); options.addOption(i); } { final Option l = new Option("l", "language", true, "specify programming language"); l.setArgName("input"); l.setArgs(1); l.setRequired(false); options.addOption(l); } { final Option m = new Option("m", "metrics", true, "specify measured metrics with comma separeted format (e.g., -m rfc,dit,lcom)"); m.setArgName("metrics"); m.setArgs(1); m.setRequired(false); options.addOption(m); } { final Option F = new Option("F", "FileMetricsFile", true, "specify file that measured FILE metrics were stored into"); F.setArgName("file metrics file"); F.setArgs(1); F.setRequired(false); options.addOption(F); } { final Option C = new Option("C", "ClassMetricsFile", true, "specify file that measured CLASS metrics were stored into"); C.setArgName("class metrics file"); C.setArgs(1); C.setRequired(false); options.addOption(C); } { final Option M = new Option("M", "MethodMetricsFile", true, "specify file that measured METHOD metrics were stored into"); M.setArgName("method metrics file"); M.setArgs(1); M.setRequired(false); options.addOption(M); } { final Option A = new Option("A", "AttributeMetricsFile", true, "specify file that measured ATTRIBUTE metrics were stored into"); A.setArgName("attribute metrics file"); A.setArgs(1); A.setRequired(false); options.addOption(A); } final MetricsTool metricsTool = new MetricsTool(); try { final CommandLineParser parser = new PosixParser(); final CommandLine cmd = parser.parse(options, args); // "-h"���w�肳��Ă���ꍇ�̓w���v��\�����ďI�� // ���̂Ƃ��C���̃I�v�V�����͑S�Ė�������� if (cmd.hasOption("h") || (0 == args.length)) { final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("MetricsTool", options, true); // -l �Ō��ꂪ�w�肳��Ă��Ȃ��ꍇ�́C��͉”\����ꗗ��\�� if (!cmd.hasOption("l")) { err.println("Available languages;"); for (final LANGUAGE language : LANGUAGE.values()) { err.println("\t" + language.getName() + ": can be specified with term \"" + language.getIdentifierName() + "\""); } // -l �Ō��ꂪ�w�肳��Ă���ꍇ�́C���̃v���O���~���O����Ŏg�p�”\�ȃ��g���N�X�ꗗ��\�� } else { Settings.getInstance().setLanguage(cmd.getOptionValue("l")); err.println("Available metrics for " + Settings.getInstance().getLanguage().getName()); metricsTool.loadPlugins(Settings.getInstance().getMetrics()); for (final AbstractPlugin plugin : DataManager.getInstance().getPluginManager() .getPlugins()) { final PluginInfo pluginInfo = plugin.getPluginInfo(); if (pluginInfo.isMeasurable(Settings.getInstance().getLanguage())) { err.println("\t" + pluginInfo.getMetricName()); } } } System.exit(0); } Settings.getInstance().setVerbose(cmd.hasOption("v")); if (cmd.hasOption("d")) { Settings.getInstance().setTargetDirectory(cmd.getOptionValue("d")); } if (cmd.hasOption("i")) { Settings.getInstance().setListFile(cmd.getOptionValue("i")); } Settings.getInstance().setLanguage(cmd.getOptionValue("l")); if (cmd.hasOption("m")) { Settings.getInstance().setMetrics(cmd.getOptionValue("m")); } if (cmd.hasOption("F")) { Settings.getInstance().setFileMetricsFile(cmd.getOptionValue("F")); } if (cmd.hasOption("C")) { Settings.getInstance().setClassMetricsFile(cmd.getOptionValue("C")); } if (cmd.hasOption("M")) { Settings.getInstance().setMethodMetricsFile(cmd.getOptionValue("M")); } if (cmd.hasOption("A")) { Settings.getInstance().setFieldMetricsFile(cmd.getOptionValue("A")); } metricsTool.loadPlugins(Settings.getInstance().getMetrics()); // �R�}���h���C�����������������ǂ����`�F�b�N���� { // -d �� -i �̂ǂ�����w�肳��Ă���͕̂s�� if (!cmd.hasOption("d") && !cmd.hasOption("l")) { err.println("-d and/or -i must be specified in the analysis mode!"); System.exit(0); } // ���ꂪ�w�肳��Ȃ������͕̂s�� if (!cmd.hasOption("l")) { err.println("-l must be specified for analysis"); System.exit(0); } { // �t�@�C�����g���N�X���v������ꍇ�� -F �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getFileMetricPlugins() .size()) && !cmd.hasOption("F")) { err.println("-F must be specified for file metrics!"); System.exit(0); } // �N���X���g���N�X���v������ꍇ�� -C �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getClassMetricPlugins() .size()) && !cmd.hasOption("C")) { err.println("-C must be specified for class metrics!"); System.exit(0); } // ���\�b�h���g���N�X���v������ꍇ�� -M �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getMethodMetricPlugins() .size()) && !cmd.hasOption("M")) { err.println("-M must be specified for method metrics!"); System.exit(0); } // �t�B�[���h���g���N�X���v������ꍇ�� -A �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if ((0 < DataManager.getInstance().getPluginManager().getFieldMetricPlugins() .size()) && !cmd.hasOption("A")) { err.println("-A must be specified for field metrics!"); System.exit(0); } } { // �t�@�C�����g���N�X���v�����Ȃ��̂� -F�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getFileMetricPlugins() .size()) && cmd.hasOption("F")) { err.println("No file metric is specified. -F is ignored."); } // �N���X���g���N�X���v�����Ȃ��̂� -C�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getClassMetricPlugins() .size()) && cmd.hasOption("C")) { err.println("No class metric is specified. -C is ignored."); } // ���\�b�h���g���N�X���v�����Ȃ��̂� -M�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getMethodMetricPlugins() .size()) && cmd.hasOption("M")) { err.println("No method metric is specified. -M is ignored."); } // �t�B�[���h���g���N�X���v�����Ȃ��̂� -A�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm if ((0 == DataManager.getInstance().getPluginManager().getFieldMetricPlugins() .size()) && cmd.hasOption("A")) { err.println("No field metric is specified. -A is ignored."); } } } } catch (ParseException e) { System.out.println(e.getMessage()); System.exit(0); } final long start = System.nanoTime(); metricsTool.readTargetFiles(); metricsTool.analyzeTargetFiles(); metricsTool.launchPlugins(); metricsTool.writeMetrics(); out.println("successfully finished."); final long end = System.nanoTime(); if (Settings.getInstance().isVerbose()) { out.println("elapsed time: " + (end - start) / 1000000000 + " seconds"); out.println("number of analyzed files: " + DataManager.getInstance().getFileInfoManager().getFileInfos().size()); int loc = 0; for (final FileInfo file : DataManager.getInstance().getFileInfoManager() .getFileInfos()) { loc += file.getLOC(); } out.println("analyzed lines of code: " + loc); } MessagePool.getInstance(MESSAGE_TYPE.OUT).removeMessageListener(outListener); MessagePool.getInstance(MESSAGE_TYPE.ERROR).removeMessageListener(errListener); }
diff --git a/src/org/puimula/droidvoikko/Voikko.java b/src/org/puimula/droidvoikko/Voikko.java index f62fd6a..4a3a63b 100644 --- a/src/org/puimula/droidvoikko/Voikko.java +++ b/src/org/puimula/droidvoikko/Voikko.java @@ -1,52 +1,55 @@ /* * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Libvoikko: Library of natural language processing tools. * The Initial Developer of the Original Code is Harri Pitkänen <[email protected]>. * Portions created by the Initial Developer are Copyright (C) 2012 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. */ package org.puimula.droidvoikko; public class Voikko { final long nativeHandle; public Voikko(String langCode, String path) { nativeHandle = init(langCode, path); } public boolean spell(String word) { + if (word == null) { + return true; + } int spellResult = spell(nativeHandle, word); return spellResult != 0; } private native long init(String langCode, String path); private native int spell(long handle, String word); static { System.loadLibrary("voikko-jni"); } }
true
true
public boolean spell(String word) { int spellResult = spell(nativeHandle, word); return spellResult != 0; }
public boolean spell(String word) { if (word == null) { return true; } int spellResult = spell(nativeHandle, word); return spellResult != 0; }
diff --git a/app/se/aimday/scheduler/api/KonferensJson.java b/app/se/aimday/scheduler/api/KonferensJson.java index feb4e5b..2631d36 100644 --- a/app/se/aimday/scheduler/api/KonferensJson.java +++ b/app/se/aimday/scheduler/api/KonferensJson.java @@ -1,54 +1,54 @@ package se.aimday.scheduler.api; import java.util.List; import play.Logger; /** * Konferens -id/namn -lista med frågor -lista med forskare -lista med företagsrepresentanter -schema där alla är * utplacerade (första gången man anropar optimeraren är denna tom, tanken är att arrangörerna ska kunna ändra i schemat * flera gånger) * * En fråga innehåller ett id och själva frågan En forskare har id, grad som nummer (1), grad som text (1=Prof), nåt * slags namn (alt förnamn och efternamn) , prioriterad önskelista, en boolean om man är joker (som man får placera * överallt). Joker har jag nog inte pratat om, kanske? Det är inte ett fält som forskaren anger utan arrangören väljer * om en forskare kan vara joker. En företagsrepresentant har id, namn och vilka frågor han vill vara med på. Den listan * är inte ordnad. * * @author fredrikbromee * */ public class KonferensJson { public String id; public String postback_url; public String namn; public OptimeringsInformation optimeringsInformation; public List<String> senioritetsgrader; public List<FragaJson> fragor; public List<ForetagsRepresentantJson> foretagsrepresentanter; public List<ForskareJson> forskare; public SchemaJson schema; public void resetFrågeNummerFrånTretton() { if (fragor == null || fragor.isEmpty()) { return; } for (FragaJson fraga : fragor) { try { int id = Integer.parseInt(fraga.id); if (id > 17) { - fraga.id = (id - 12) + ""; + fraga.id = (id - 14) + ""; } else { if (id > 12) { - fraga.id = (id - 14) + ""; + fraga.id = (id - 12) + ""; } } } catch (RuntimeException re) { Logger.error(re, "failed to reset fråga nummer %s", fraga.id); } } } }
false
true
public void resetFrågeNummerFrånTretton() { if (fragor == null || fragor.isEmpty()) { return; } for (FragaJson fraga : fragor) { try { int id = Integer.parseInt(fraga.id); if (id > 17) { fraga.id = (id - 12) + ""; } else { if (id > 12) { fraga.id = (id - 14) + ""; } } } catch (RuntimeException re) { Logger.error(re, "failed to reset fråga nummer %s", fraga.id); } } }
public void resetFrågeNummerFrånTretton() { if (fragor == null || fragor.isEmpty()) { return; } for (FragaJson fraga : fragor) { try { int id = Integer.parseInt(fraga.id); if (id > 17) { fraga.id = (id - 14) + ""; } else { if (id > 12) { fraga.id = (id - 12) + ""; } } } catch (RuntimeException re) { Logger.error(re, "failed to reset fråga nummer %s", fraga.id); } } }
diff --git a/org.eclipse.mylyn.commons.core/src/org/eclipse/mylyn/internal/commons/core/XmlStringConverter.java b/org.eclipse.mylyn.commons.core/src/org/eclipse/mylyn/internal/commons/core/XmlStringConverter.java index 160f4fc8..f7e16e9d 100644 --- a/org.eclipse.mylyn.commons.core/src/org/eclipse/mylyn/internal/commons/core/XmlStringConverter.java +++ b/org.eclipse.mylyn.commons.core/src/org/eclipse/mylyn/internal/commons/core/XmlStringConverter.java @@ -1,140 +1,140 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.commons.core; /** * @author Ken Sueda */ // API-3.0: should use xerces or some other parser's facilities public class XmlStringConverter { @Deprecated public static String convertToXmlString(String s) { if (s == null) { return ""; } StringBuffer res = new StringBuffer(s.length() + 20); for (int i = 0; i < s.length(); ++i) { appendEscapedChar(res, s.charAt(i)); } return res.toString(); } private static void appendEscapedChar(StringBuffer buffer, char c) { String replacement = getReplacementForSymbol(c); if (replacement != null) { buffer.append('&'); buffer.append(replacement); buffer.append(';'); } else { buffer.append(c); } } private static String getReplacementForSymbol(char c) { switch (c) { case '<': return "lt"; //$NON-NLS-1$ case '>': return "gt"; //$NON-NLS-1$ case '"': return "quot"; //$NON-NLS-1$ case '\'': return "apos"; //$NON-NLS-1$ case '&': return "amp"; //$NON-NLS-1$ case '\r': return "#x0D"; //$NON-NLS-1$ case '\n': return "#x0A"; //$NON-NLS-1$ case '\u0009': return "#x09"; //$NON-NLS-1$ } return null; } @Deprecated public static String convertXmlToString(String string) { - StringBuffer result = new StringBuffer(string.length() + 10); + StringBuilder result = new StringBuilder(string.length() + 10); for (int i = 0; i < string.length(); ++i) { char xChar = string.charAt(i); if (xChar == '&') { i++; StringBuffer escapeChar = new StringBuffer(10); boolean flag = true; while (flag) { xChar = string.charAt(i++); if (xChar == ';') { flag = false; i--; } else { escapeChar.append(xChar); } } result.append(getReplacementForXml(escapeChar.toString())); } else { result.append(xChar); } } return result.toString(); } private static char getReplacementForXml(String s) { if (s.equals("lt")) { return '<'; } else if (s.equals("gt")) { return '>'; } else if (s.equals("quot")) { return '"'; } else if (s.equals("apos")) { return '\''; } else if (s.equals("amp")) { return '&'; } else if (s.equals("#x0D")) { return '\r'; } else if (s.equals("#x0A")) { return '\n'; } else if (s.equals("#x09")) { return '\u0009'; } return 0; } /** * @param text * string to clean * @return string with all non valid characters removed, if text is null return null */ @Deprecated public static String cleanXmlString(String text) { if (text == null) { return null; } StringBuilder builder = new StringBuilder(text.length()); for (int x = 0; x < text.length(); x++) { char ch = text.charAt(x); if (isValid(ch)) { builder.append(ch); } } return builder.toString(); } /** * Return true if character is a valid xml character * * @see http://www.w3.org/TR/REC-xml/ */ @Deprecated public static boolean isValid(char ch) { return (0x0A == ch || 0x0D == ch || 0x09 == ch) || (ch >= 0x20 && ch <= 0xD7FF) || (ch >= 0xE000 && ch <= 0xFFFD) || (ch >= 0x10000 && ch <= 0x10FFFF); } }
true
true
public static String convertXmlToString(String string) { StringBuffer result = new StringBuffer(string.length() + 10); for (int i = 0; i < string.length(); ++i) { char xChar = string.charAt(i); if (xChar == '&') { i++; StringBuffer escapeChar = new StringBuffer(10); boolean flag = true; while (flag) { xChar = string.charAt(i++); if (xChar == ';') { flag = false; i--; } else { escapeChar.append(xChar); } } result.append(getReplacementForXml(escapeChar.toString())); } else { result.append(xChar); } } return result.toString(); }
public static String convertXmlToString(String string) { StringBuilder result = new StringBuilder(string.length() + 10); for (int i = 0; i < string.length(); ++i) { char xChar = string.charAt(i); if (xChar == '&') { i++; StringBuffer escapeChar = new StringBuffer(10); boolean flag = true; while (flag) { xChar = string.charAt(i++); if (xChar == ';') { flag = false; i--; } else { escapeChar.append(xChar); } } result.append(getReplacementForXml(escapeChar.toString())); } else { result.append(xChar); } } return result.toString(); }
diff --git a/src/gtna/transformation/sampling/walker/MetropolizedRandomWalkWalker.java b/src/gtna/transformation/sampling/walker/MetropolizedRandomWalkWalker.java index b74636b5..3f8966cf 100644 --- a/src/gtna/transformation/sampling/walker/MetropolizedRandomWalkWalker.java +++ b/src/gtna/transformation/sampling/walker/MetropolizedRandomWalkWalker.java @@ -1,119 +1,119 @@ /* =========================================================== * GTNA : Graph-Theoretic Network Analyzer * =========================================================== * * (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt) * and Contributors * * Project Info: http://www.p2p.tu-darmstadt.de/research/gtna/ * * GTNA is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GTNA is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * --------------------------------------- * RandomWalkWalker.java * --------------------------------------- * (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt) * and Contributors * * Original Author: Tim; * Contributors: -; * * Changes since 2011-05-17 * --------------------------------------- * */ package gtna.transformation.sampling.walker; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import gtna.graph.Graph; import gtna.graph.Node; import gtna.transformation.sampling.AWalker; /** * @author Tim * */ public class MetropolizedRandomWalkWalker extends AWalker { /** * @param walker */ public MetropolizedRandomWalkWalker() { super("METROPLIZED_RANDOM_WALK_WALKER"); } /* * (non-Javadoc) * * @see * gtna.transformation.sampling.AWalker#selectNextNode(java.util.Collection) */ @Override protected Node selectNextNode(Collection<Node> candidates) { Random r = this.getRNG(); Collection<Node> c = this.getCurrentNodes(); if (c.size() > 0) { Node current = c.toArray(new Node[0])[0]; int next = r.nextInt(candidates.size()); next = next % candidates.size(); Node nextStepCandidate = candidates.toArray(new Node[0])[next]; int nscDegree = nextStepCandidate.getDegree(); int cDegree = current.getDegree(); double d = (double) cDegree / (double) nscDegree; d = Math.min(d, 1); double p = r.nextDouble(); - if (d < p) { + if (p < d) { return nextStepCandidate; // move the walker to the next node } else { System.err.println("Stay, no moving: deg(old)/deg(candidate) - " + cDegree + "/" + nscDegree); return current; // stay and don't move the walker! } } else { c = this.getRestartNodes(); return c.toArray(new Node[0])[0]; } } /** * returns the list of neighbors as candidates * * @param g * Graph * @param n * Current node * @return List of candidates */ @Override public Collection<Node> resolveCandidates(Graph g, Node n) { int[] nids = n.getOutgoingEdges(); ArrayList<Node> nn = new ArrayList<Node>(); for (int i : nids) { nn.add(g.getNode(i)); } return nn; } }
true
true
protected Node selectNextNode(Collection<Node> candidates) { Random r = this.getRNG(); Collection<Node> c = this.getCurrentNodes(); if (c.size() > 0) { Node current = c.toArray(new Node[0])[0]; int next = r.nextInt(candidates.size()); next = next % candidates.size(); Node nextStepCandidate = candidates.toArray(new Node[0])[next]; int nscDegree = nextStepCandidate.getDegree(); int cDegree = current.getDegree(); double d = (double) cDegree / (double) nscDegree; d = Math.min(d, 1); double p = r.nextDouble(); if (d < p) { return nextStepCandidate; // move the walker to the next node } else { System.err.println("Stay, no moving: deg(old)/deg(candidate) - " + cDegree + "/" + nscDegree); return current; // stay and don't move the walker! } } else { c = this.getRestartNodes(); return c.toArray(new Node[0])[0]; } }
protected Node selectNextNode(Collection<Node> candidates) { Random r = this.getRNG(); Collection<Node> c = this.getCurrentNodes(); if (c.size() > 0) { Node current = c.toArray(new Node[0])[0]; int next = r.nextInt(candidates.size()); next = next % candidates.size(); Node nextStepCandidate = candidates.toArray(new Node[0])[next]; int nscDegree = nextStepCandidate.getDegree(); int cDegree = current.getDegree(); double d = (double) cDegree / (double) nscDegree; d = Math.min(d, 1); double p = r.nextDouble(); if (p < d) { return nextStepCandidate; // move the walker to the next node } else { System.err.println("Stay, no moving: deg(old)/deg(candidate) - " + cDegree + "/" + nscDegree); return current; // stay and don't move the walker! } } else { c = this.getRestartNodes(); return c.toArray(new Node[0])[0]; } }
diff --git a/org.alder.fotobuchconvert.ifolorconvert/src/main/java/org/alder/fotobuchconvert/ifolor/TestData.java b/org.alder.fotobuchconvert.ifolorconvert/src/main/java/org/alder/fotobuchconvert/ifolor/TestData.java index fad1df0..1760f12 100644 --- a/org.alder.fotobuchconvert.ifolorconvert/src/main/java/org/alder/fotobuchconvert/ifolor/TestData.java +++ b/org.alder.fotobuchconvert.ifolorconvert/src/main/java/org/alder/fotobuchconvert/ifolor/TestData.java @@ -1,65 +1,69 @@ package org.alder.fotobuchconvert.ifolor; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class TestData { private final static Log log = LogFactory.getLog(TestData.class); public static ProjectPath getTestProject() { final String configFile = "testpaths.txt"; try { InputStream is = TestData.class.getClassLoader() .getResourceAsStream(configFile); + if (is == null) + throw new RuntimeException( + "Test project config not found (check " + configFile + + ")"); BufferedReader ir = new BufferedReader(new InputStreamReader(is)); String line; while ((line = ir.readLine()) != null) { if (line.isEmpty() || line.startsWith("#")) continue; File file = new File(line); if (!file.exists()) continue; // if (line.endsWith(".xml")) // line = line.substring(0, line.length() - 4); // if (line.endsWith(".dpp")) // line = line.substring(0, line.length() - 4); log.info("Using Test Data: " + file); return new ProjectPath(file); } } catch (IOException e) { throw new RuntimeException(e); } throw new RuntimeException("No test file found (check " + configFile + ")"); } public static File getTestOutputPath() { if (isWindows()) return new File("C:\\Temp\\scribustest.sla"); else return new File("/tmp/scribustest.sla"); } private static boolean isWindows() { String os = System.getProperty("os.name").toLowerCase(); return (os.indexOf("win") >= 0); } public static void main(String[] args) { ProjectPath pp = getTestProject(); System.out.println(pp.projectFile); System.out.println(pp.projectFolder); } }
true
true
public static ProjectPath getTestProject() { final String configFile = "testpaths.txt"; try { InputStream is = TestData.class.getClassLoader() .getResourceAsStream(configFile); BufferedReader ir = new BufferedReader(new InputStreamReader(is)); String line; while ((line = ir.readLine()) != null) { if (line.isEmpty() || line.startsWith("#")) continue; File file = new File(line); if (!file.exists()) continue; // if (line.endsWith(".xml")) // line = line.substring(0, line.length() - 4); // if (line.endsWith(".dpp")) // line = line.substring(0, line.length() - 4); log.info("Using Test Data: " + file); return new ProjectPath(file); } } catch (IOException e) { throw new RuntimeException(e); } throw new RuntimeException("No test file found (check " + configFile + ")"); }
public static ProjectPath getTestProject() { final String configFile = "testpaths.txt"; try { InputStream is = TestData.class.getClassLoader() .getResourceAsStream(configFile); if (is == null) throw new RuntimeException( "Test project config not found (check " + configFile + ")"); BufferedReader ir = new BufferedReader(new InputStreamReader(is)); String line; while ((line = ir.readLine()) != null) { if (line.isEmpty() || line.startsWith("#")) continue; File file = new File(line); if (!file.exists()) continue; // if (line.endsWith(".xml")) // line = line.substring(0, line.length() - 4); // if (line.endsWith(".dpp")) // line = line.substring(0, line.length() - 4); log.info("Using Test Data: " + file); return new ProjectPath(file); } } catch (IOException e) { throw new RuntimeException(e); } throw new RuntimeException("No test file found (check " + configFile + ")"); }
diff --git a/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/text/completion/JavaScriptCompletionProposalCollector.java b/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/text/completion/JavaScriptCompletionProposalCollector.java index 2e033c6d..b8861993 100644 --- a/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/text/completion/JavaScriptCompletionProposalCollector.java +++ b/plugins/org.eclipse.dltk.javascript.ui/src/org/eclipse/dltk/javascript/internal/ui/text/completion/JavaScriptCompletionProposalCollector.java @@ -1,155 +1,159 @@ /******************************************************************************* * Copyright (c) 2005, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.eclipse.dltk.javascript.internal.ui.text.completion; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.dltk.core.CompletionProposal; import org.eclipse.dltk.core.IScriptProject; import org.eclipse.dltk.core.IMember; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.internal.javascript.typeinference.IReference; import org.eclipse.dltk.javascript.scriptdoc.ScriptDocumentationProvider; import org.eclipse.dltk.ui.text.completion.AbstractScriptCompletionProposal; import org.eclipse.dltk.ui.text.completion.CompletionProposalLabelProvider; import org.eclipse.dltk.ui.text.completion.IScriptCompletionProposal; import org.eclipse.dltk.ui.text.completion.ProposalInfo; import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposal; import org.eclipse.dltk.ui.text.completion.ScriptCompletionProposalCollector; import org.eclipse.dltk.ui.text.completion.ScriptContentAssistInvocationContext; import org.eclipse.swt.graphics.Image; public class JavaScriptCompletionProposalCollector extends ScriptCompletionProposalCollector { protected final static char[] VAR_TRIGGER = new char[] { '\t', ' ', '=', ';', '.' }; protected char[] getVarTrigger() { return VAR_TRIGGER; } public JavaScriptCompletionProposalCollector(ISourceModule module) { super(module); } // Label provider protected CompletionProposalLabelProvider createLabelProvider() { return new JavaScriptCompletionProposalLabelProvider(); } // Invocation context protected ScriptContentAssistInvocationContext createScriptContentAssistInvocationContext( ISourceModule sourceModule) { return new ScriptContentAssistInvocationContext(sourceModule) { protected CompletionProposalLabelProvider createLabelProvider() { return new JavaScriptCompletionProposalLabelProvider(); } }; } // Specific proposals creation. May be use factory? protected IScriptCompletionProposal createScriptCompletionProposal( CompletionProposal proposal) { // TODO Auto-generated method stub final IScriptCompletionProposal createScriptCompletionProposal2 = super .createScriptCompletionProposal(proposal); AbstractScriptCompletionProposal createScriptCompletionProposal = (AbstractScriptCompletionProposal) createScriptCompletionProposal2; final Object ref = (Object) proposal.extraInfo; ProposalInfo proposalInfo = new ProposalInfo(null) { public String getInfo(IProgressMonitor monitor) { if (ref instanceof IReference) { ArrayList ms = new ArrayList(); ((IReference) ref).addModelElements(ms); if (ms.size() > 0) ; Reader contentReader = new ScriptDocumentationProvider() .getInfo((IMember) ms.get(0), true, true); if (contentReader != null) { String string = getString(contentReader); return string; } } else if (ref instanceof IMember) { Reader contentReader = new ScriptDocumentationProvider() .getInfo((IMember) ref, true, true); if (contentReader != null) { String string = getString(contentReader); return string; } } + else if (ref instanceof String) + { + return (String)ref; + } return "Documentation not resolved"; } /** * Gets the reader content as a String */ private String getString(Reader reader) { StringBuffer buf = new StringBuffer(); char[] buffer = new char[1024]; int count; try { while ((count = reader.read(buffer)) != -1) buf.append(buffer, 0, count); } catch (IOException e) { return null; } return buf.toString(); } }; createScriptCompletionProposal.setProposalInfo(proposalInfo); return createScriptCompletionProposal; } protected ScriptCompletionProposal createScriptCompletionProposal( String completion, int replaceStart, int length, Image image, String displayString, int i) { JavaScriptCompletionProposal javaScriptCompletionProposal = new JavaScriptCompletionProposal( completion, replaceStart, length, image, displayString, i); return javaScriptCompletionProposal; } protected ScriptCompletionProposal createScriptCompletionProposal( String completion, int replaceStart, int length, Image image, String displayString, int i, boolean isInDoc) { JavaScriptCompletionProposal javaScriptCompletionProposal = new JavaScriptCompletionProposal( completion, replaceStart, length, image, displayString, i, isInDoc); return javaScriptCompletionProposal; } protected ScriptCompletionProposal createOverrideCompletionProposal( IScriptProject scriptProject, ISourceModule compilationUnit, String name, String[] paramTypes, int start, int length, String displayName, String completionProposal) { return new JavaScriptOverrideCompletionProposal(scriptProject, compilationUnit, name, paramTypes, start, length, displayName, completionProposal); } protected IScriptCompletionProposal createKeywordProposal( CompletionProposal proposal) { String completion = String.valueOf(proposal.getCompletion()); int start = proposal.getReplaceStart(); int length = getLength(proposal); String label = getLabelProvider().createSimpleLabel(proposal); Image img = getImage(getLabelProvider().createMethodImageDescriptor( proposal)); int relevance = computeRelevance(proposal); return createScriptCompletionProposal(completion, start, length, img, label, relevance); } }
true
true
protected IScriptCompletionProposal createScriptCompletionProposal( CompletionProposal proposal) { // TODO Auto-generated method stub final IScriptCompletionProposal createScriptCompletionProposal2 = super .createScriptCompletionProposal(proposal); AbstractScriptCompletionProposal createScriptCompletionProposal = (AbstractScriptCompletionProposal) createScriptCompletionProposal2; final Object ref = (Object) proposal.extraInfo; ProposalInfo proposalInfo = new ProposalInfo(null) { public String getInfo(IProgressMonitor monitor) { if (ref instanceof IReference) { ArrayList ms = new ArrayList(); ((IReference) ref).addModelElements(ms); if (ms.size() > 0) ; Reader contentReader = new ScriptDocumentationProvider() .getInfo((IMember) ms.get(0), true, true); if (contentReader != null) { String string = getString(contentReader); return string; } } else if (ref instanceof IMember) { Reader contentReader = new ScriptDocumentationProvider() .getInfo((IMember) ref, true, true); if (contentReader != null) { String string = getString(contentReader); return string; } } return "Documentation not resolved"; } /** * Gets the reader content as a String */ private String getString(Reader reader) { StringBuffer buf = new StringBuffer(); char[] buffer = new char[1024]; int count; try { while ((count = reader.read(buffer)) != -1) buf.append(buffer, 0, count); } catch (IOException e) { return null; } return buf.toString(); } }; createScriptCompletionProposal.setProposalInfo(proposalInfo); return createScriptCompletionProposal; }
protected IScriptCompletionProposal createScriptCompletionProposal( CompletionProposal proposal) { // TODO Auto-generated method stub final IScriptCompletionProposal createScriptCompletionProposal2 = super .createScriptCompletionProposal(proposal); AbstractScriptCompletionProposal createScriptCompletionProposal = (AbstractScriptCompletionProposal) createScriptCompletionProposal2; final Object ref = (Object) proposal.extraInfo; ProposalInfo proposalInfo = new ProposalInfo(null) { public String getInfo(IProgressMonitor monitor) { if (ref instanceof IReference) { ArrayList ms = new ArrayList(); ((IReference) ref).addModelElements(ms); if (ms.size() > 0) ; Reader contentReader = new ScriptDocumentationProvider() .getInfo((IMember) ms.get(0), true, true); if (contentReader != null) { String string = getString(contentReader); return string; } } else if (ref instanceof IMember) { Reader contentReader = new ScriptDocumentationProvider() .getInfo((IMember) ref, true, true); if (contentReader != null) { String string = getString(contentReader); return string; } } else if (ref instanceof String) { return (String)ref; } return "Documentation not resolved"; } /** * Gets the reader content as a String */ private String getString(Reader reader) { StringBuffer buf = new StringBuffer(); char[] buffer = new char[1024]; int count; try { while ((count = reader.read(buffer)) != -1) buf.append(buffer, 0, count); } catch (IOException e) { return null; } return buf.toString(); } }; createScriptCompletionProposal.setProposalInfo(proposalInfo); return createScriptCompletionProposal; }
diff --git a/CloudStorge/src/main/java/com/ces/cloudstorge/Dialog/FolderListDialog.java b/CloudStorge/src/main/java/com/ces/cloudstorge/Dialog/FolderListDialog.java index d5c9e8b..0aa4c2f 100644 --- a/CloudStorge/src/main/java/com/ces/cloudstorge/Dialog/FolderListDialog.java +++ b/CloudStorge/src/main/java/com/ces/cloudstorge/Dialog/FolderListDialog.java @@ -1,188 +1,188 @@ package com.ces.cloudstorge.Dialog; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import com.ces.cloudstorge.Contract; import com.ces.cloudstorge.MainActivity; import com.ces.cloudstorge.R; import com.ces.cloudstorge.provider.CloudStorgeContract; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by MichaelDai on 13-7-30. */ public class FolderListDialog extends DialogFragment { public FolderListDialog() { } public interface FolderListDialogListener { void onFinishSelectFolder(int folderId, String arraylist); } FolderListDialogListener mListener; private ListView mDialogFolderList; private ImageView mDialogImageIcon; private TextView mDialogFolderName; private int currentFolderId; private int parentFolderId; private String arraylist; private SimpleAdapter mAdapter; private boolean isRoot; private String username; private List<Map<String, String>> listData; private ContentResolver mContentResolver; // sql查询条件(root) static final String SELECTION_SPECIAL = "( " + CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID + "= (select " + CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID + " from " + CloudStorgeContract.CloudStorge.TABLE_NAME + " where " + CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID + "=%d and " + CloudStorgeContract.CloudStorge.COLUMN_NAME_USERNAME + "='%s' limit 1)" + " and " + CloudStorgeContract.CloudStorge.COLUMN_NAME_USERNAME + " = '%s' " + " and " + CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID + "<> -1)"; // sql查询条件(root) static final String SELECTION_CHILD = "( " + CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID + "=%d " + "and " + CloudStorgeContract.CloudStorge.COLUMN_NAME_USERNAME + " = '%s' and " + CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID + "<> -1)"; static final String selection_folder_format = "(" + CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID + "=%d and " + CloudStorgeContract.CloudStorge.COLUMN_NAME_USERNAME + " = '%s')"; // 需要的字段 public static final String[] fromColumns = { CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID }; // view中的对象 public static final int[] toViews = {R.id.list_dialog_text, R.id.list_dialog_parentfolderid, R.id.list_dialog_folderid }; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (FolderListDialogListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement NoticeDialogListener"); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.fragment_folder_list_dialog, null); mDialogFolderList = (ListView) view.findViewById(R.id.list_folder_dialog); mDialogImageIcon = (ImageView) view.findViewById(R.id.dialog_folder_icon); mDialogFolderName = (TextView) view.findViewById(R.id.dialog_folder_name); mDialogImageIcon.setVisibility(View.GONE); mDialogFolderName.setText(R.string.app_activity_title); builder.setView(view); arraylist = getArguments().getString("arraylist"); currentFolderId = getArguments().getInt("currentFolderId"); parentFolderId = getArguments().getInt("parentFolderId"); username = getArguments().getString("currentUser"); isRoot = true; mContentResolver = this.getActivity().getContentResolver(); mDialogImageIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listData.clear(); String selection = String.format(SELECTION_CHILD, parentFolderId, username); String selectionParent = String.format(selection_folder_format, parentFolderId, username); Cursor parentCursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selectionParent, null, null); parentCursor.moveToFirst(); int parentFolderIdtmp = parentCursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID); String folderName = parentCursor.getString(Contract.PROJECTION_NAME); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_FOLDER_ID) + ""); listData.add(map); } mAdapter.notifyDataSetChanged(); if (-1 == parentFolderIdtmp) mDialogImageIcon.setVisibility(View.GONE); currentFolderId = parentFolderId; parentFolderId = parentFolderIdtmp; mDialogFolderName.setText(folderName); } }); listData = new ArrayList<Map<String, String>>(); String selection = String.format(SELECTION_SPECIAL, -1, username, username); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); - map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); + map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_FOLDER_ID) + ""); listData.add(map); } mDialogFolderList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { mDialogImageIcon.setVisibility(View.VISIBLE); Map<String, String> selectMap = listData.get(position); int folderId = Integer.parseInt(selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID)); int parentfolderId = Integer.parseInt(selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID)); String folderName = selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME); currentFolderId = folderId; parentFolderId = parentfolderId; listData.clear(); String selection = String.format(SELECTION_CHILD, folderId, username); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_FOLDER_ID) + ""); listData.add(map); } mAdapter.notifyDataSetChanged(); mDialogFolderName.setText(folderName); } }); mAdapter = new SimpleAdapter(getActivity().getApplicationContext(), listData, R.layout.list_item_dialog, fromColumns, toViews); mDialogFolderList.setAdapter(mAdapter); builder.setPositiveButton(R.string.menu_action_move, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { mListener.onFinishSelectFolder(currentFolderId, arraylist); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { listData.clear(); dialog.cancel(); } }); return builder.create(); } }
true
true
public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.fragment_folder_list_dialog, null); mDialogFolderList = (ListView) view.findViewById(R.id.list_folder_dialog); mDialogImageIcon = (ImageView) view.findViewById(R.id.dialog_folder_icon); mDialogFolderName = (TextView) view.findViewById(R.id.dialog_folder_name); mDialogImageIcon.setVisibility(View.GONE); mDialogFolderName.setText(R.string.app_activity_title); builder.setView(view); arraylist = getArguments().getString("arraylist"); currentFolderId = getArguments().getInt("currentFolderId"); parentFolderId = getArguments().getInt("parentFolderId"); username = getArguments().getString("currentUser"); isRoot = true; mContentResolver = this.getActivity().getContentResolver(); mDialogImageIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listData.clear(); String selection = String.format(SELECTION_CHILD, parentFolderId, username); String selectionParent = String.format(selection_folder_format, parentFolderId, username); Cursor parentCursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selectionParent, null, null); parentCursor.moveToFirst(); int parentFolderIdtmp = parentCursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID); String folderName = parentCursor.getString(Contract.PROJECTION_NAME); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_FOLDER_ID) + ""); listData.add(map); } mAdapter.notifyDataSetChanged(); if (-1 == parentFolderIdtmp) mDialogImageIcon.setVisibility(View.GONE); currentFolderId = parentFolderId; parentFolderId = parentFolderIdtmp; mDialogFolderName.setText(folderName); } }); listData = new ArrayList<Map<String, String>>(); String selection = String.format(SELECTION_SPECIAL, -1, username, username); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); listData.add(map); } mDialogFolderList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { mDialogImageIcon.setVisibility(View.VISIBLE); Map<String, String> selectMap = listData.get(position); int folderId = Integer.parseInt(selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID)); int parentfolderId = Integer.parseInt(selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID)); String folderName = selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME); currentFolderId = folderId; parentFolderId = parentfolderId; listData.clear(); String selection = String.format(SELECTION_CHILD, folderId, username); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_FOLDER_ID) + ""); listData.add(map); } mAdapter.notifyDataSetChanged(); mDialogFolderName.setText(folderName); } }); mAdapter = new SimpleAdapter(getActivity().getApplicationContext(), listData, R.layout.list_item_dialog, fromColumns, toViews); mDialogFolderList.setAdapter(mAdapter); builder.setPositiveButton(R.string.menu_action_move, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { mListener.onFinishSelectFolder(currentFolderId, arraylist); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { listData.clear(); dialog.cancel(); } }); return builder.create(); }
public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.fragment_folder_list_dialog, null); mDialogFolderList = (ListView) view.findViewById(R.id.list_folder_dialog); mDialogImageIcon = (ImageView) view.findViewById(R.id.dialog_folder_icon); mDialogFolderName = (TextView) view.findViewById(R.id.dialog_folder_name); mDialogImageIcon.setVisibility(View.GONE); mDialogFolderName.setText(R.string.app_activity_title); builder.setView(view); arraylist = getArguments().getString("arraylist"); currentFolderId = getArguments().getInt("currentFolderId"); parentFolderId = getArguments().getInt("parentFolderId"); username = getArguments().getString("currentUser"); isRoot = true; mContentResolver = this.getActivity().getContentResolver(); mDialogImageIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listData.clear(); String selection = String.format(SELECTION_CHILD, parentFolderId, username); String selectionParent = String.format(selection_folder_format, parentFolderId, username); Cursor parentCursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selectionParent, null, null); parentCursor.moveToFirst(); int parentFolderIdtmp = parentCursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID); String folderName = parentCursor.getString(Contract.PROJECTION_NAME); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_FOLDER_ID) + ""); listData.add(map); } mAdapter.notifyDataSetChanged(); if (-1 == parentFolderIdtmp) mDialogImageIcon.setVisibility(View.GONE); currentFolderId = parentFolderId; parentFolderId = parentFolderIdtmp; mDialogFolderName.setText(folderName); } }); listData = new ArrayList<Map<String, String>>(); String selection = String.format(SELECTION_SPECIAL, -1, username, username); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_FOLDER_ID) + ""); listData.add(map); } mDialogFolderList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { mDialogImageIcon.setVisibility(View.VISIBLE); Map<String, String> selectMap = listData.get(position); int folderId = Integer.parseInt(selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID)); int parentfolderId = Integer.parseInt(selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID)); String folderName = selectMap.get(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME); currentFolderId = folderId; parentFolderId = parentfolderId; listData.clear(); String selection = String.format(SELECTION_CHILD, folderId, username); Cursor cursor = mContentResolver.query(CloudStorgeContract.CloudStorge.CONTENT_URI, MainActivity.PROJECTION, selection, null, null); while (cursor.moveToNext()) { Map<String, String> map = new HashMap<String, String>(); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_NAME, cursor.getString(Contract.PROJECTION_NAME)); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_PARENT_FOLDER_ID, cursor.getInt(Contract.PROJECTION_PARENT_FOLDER_ID) + ""); map.put(CloudStorgeContract.CloudStorge.COLUMN_NAME_FOLDER_ID, cursor.getInt(Contract.PROJECTION_FOLDER_ID) + ""); listData.add(map); } mAdapter.notifyDataSetChanged(); mDialogFolderName.setText(folderName); } }); mAdapter = new SimpleAdapter(getActivity().getApplicationContext(), listData, R.layout.list_item_dialog, fromColumns, toViews); mDialogFolderList.setAdapter(mAdapter); builder.setPositiveButton(R.string.menu_action_move, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { mListener.onFinishSelectFolder(currentFolderId, arraylist); } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { listData.clear(); dialog.cancel(); } }); return builder.create(); }
diff --git a/src/edu/jhu/thrax/extraction/HierarchicalRuleExtractor.java b/src/edu/jhu/thrax/extraction/HierarchicalRuleExtractor.java index 7a5d615..d58aab3 100644 --- a/src/edu/jhu/thrax/extraction/HierarchicalRuleExtractor.java +++ b/src/edu/jhu/thrax/extraction/HierarchicalRuleExtractor.java @@ -1,391 +1,393 @@ package edu.jhu.thrax.extraction; import java.util.Collection; import java.util.HashSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ArrayList; import java.util.Queue; import java.util.LinkedList; import java.util.Scanner; import java.io.IOException; import edu.jhu.thrax.datatypes.*; import edu.jhu.thrax.util.exceptions.*; import edu.jhu.thrax.util.Vocabulary; import edu.jhu.thrax.util.ConfFileParser; import edu.jhu.thrax.util.io.InputUtilities; import edu.jhu.thrax.ThraxConfig; import org.apache.hadoop.conf.Configuration; /** * This class extracts Hiero-style SCFG rules. The inputs that are needed * are "source" "target" and "alignment", which are the source and target * sides of a parallel corpus, and an alignment between each of the sentences. */ public class HierarchicalRuleExtractor implements RuleExtractor { public int INIT_LENGTH_LIMIT = 10; public int NONLEX_SOURCE_LENGTH_LIMIT = 5; public int NONLEX_SOURCE_WORD_LIMIT = 5; public int NONLEX_TARGET_LENGTH_LIMIT = 5; public int NONLEX_TARGET_WORD_LIMIT = 5; public int NT_LIMIT = 2; public int LEXICAL_MINIMUM = 1; public boolean ALLOW_ADJACENT_NTS = false; public boolean ALLOW_LOOSE_BOUNDS = false; public boolean ALLOW_FULL_SENTENCE_RULES = true; public boolean ALLOW_ABSTRACT = false; public boolean ALLOW_X_NONLEX = false; public int RULE_SPAN_LIMIT = 12; public int LEX_TARGET_LENGTH_LIMIT = 12; public int LEX_SOURCE_LENGTH_LIMIT = 12; public boolean SOURCE_IS_PARSED = false; public boolean TARGET_IS_PARSED = false; public boolean REVERSE = false; private SpanLabeler labeler; private Collection<Integer> defaultLabel; /** * Default constructor. The grammar parameters are initalized according * to how they are set in the thrax config file. */ public HierarchicalRuleExtractor(Configuration conf, SpanLabeler labeler) { this.labeler = labeler; INIT_LENGTH_LIMIT = conf.getInt("thrax.initial-phrase-length", 10); NONLEX_SOURCE_LENGTH_LIMIT = conf.getInt("thrax.nonlex-source-length", 5); NONLEX_SOURCE_WORD_LIMIT = conf.getInt("thrax.nonlex-source-words", 5); NONLEX_TARGET_LENGTH_LIMIT = conf.getInt("thrax.nonlex-target-length", 5); NONLEX_TARGET_WORD_LIMIT = conf.getInt("thrax.nonlex-target-words", 5); NT_LIMIT = conf.getInt("thrax.arity", 2); LEXICAL_MINIMUM = conf.getInt("thrax.lexicality", 1); ALLOW_ADJACENT_NTS = conf.getBoolean("thrax.adjacent-nts", false); ALLOW_LOOSE_BOUNDS = conf.getBoolean("thrax.loose", false); ALLOW_FULL_SENTENCE_RULES = conf.getBoolean("thrax.allow-full-sentence-rules", true); ALLOW_ABSTRACT = conf.getBoolean("thrax.allow-abstract-rules", false); ALLOW_X_NONLEX = conf.getBoolean("thrax.allow-nonlexical-x", false); RULE_SPAN_LIMIT = conf.getInt("thrax.rule-span-limit", 12); LEX_TARGET_LENGTH_LIMIT = conf.getInt("thrax.lex-target-words", 12); LEX_SOURCE_LENGTH_LIMIT = conf.getInt("thrax.lex-source-words", 12); SOURCE_IS_PARSED = conf.getBoolean("thrax.source-is-parsed", false); TARGET_IS_PARSED = conf.getBoolean("thrax.target-is-parsed", false); // a backwards-compatibility hack for matt if (conf.get("thrax.english-is-parsed") != null) TARGET_IS_PARSED = conf.getBoolean("thrax.english-is-parsed", false); int defaultID = Vocabulary.getId(conf.get("thrax.default-nt", "X")); REVERSE = conf.getBoolean("thrax.reverse", false); defaultLabel = new HashSet<Integer>(); defaultLabel.add(defaultID); } public List<Rule> extract(String inp) throws MalformedInputException { String [] inputs = inp.split(ThraxConfig.DELIMITER_REGEX); if (inputs.length < 3) { throw new NotEnoughFieldsException(); } String [] sourceWords = InputUtilities.getWords(inputs[0], SOURCE_IS_PARSED); String [] targetWords = InputUtilities.getWords(inputs[1], TARGET_IS_PARSED); if (sourceWords.length == 0 || targetWords.length == 0) throw new EmptySentenceException(); int [] source = Vocabulary.getIds(sourceWords); int [] target = Vocabulary.getIds(targetWords); if (REVERSE) { int [] tmp = source; source = target; target = tmp; } Alignment alignment = new Alignment(inputs[2], REVERSE); if (alignment.isEmpty()) throw new EmptyAlignmentException(); if (!alignment.consistent(source.length, target.length)) { StringBuilder sb = new StringBuilder(); sb.append(String.format("source: %s (length %d)\n", inputs[0], source.length)); sb.append(String.format("target: %s (length %d)\n", inputs[1], target.length)); sb.append("alignment: " + inputs[2]); throw new InconsistentAlignmentException(sb.toString()); } PhrasePair [][] phrasesByStart = initialPhrasePairs(source, target, alignment); labeler.setInput(inp); Queue<Rule> q = new LinkedList<Rule>(); for (int i = 0; i < source.length; i++) q.offer(new Rule(source, target, alignment, i, NT_LIMIT)); return processQueue(q, phrasesByStart); } protected List<Rule> processQueue(Queue<Rule> q, PhrasePair [][] phrasesByStart) { List<Rule> rules = new ArrayList<Rule>(); while (q.peek() != null) { Rule r = q.poll(); for (Rule t : getAlignmentVariants(r)) { if (isWellFormed(t)) { for (Rule s : getLabelVariants(t)) { rules.add(s); } } } if (r.appendPoint > phrasesByStart.length - 1) continue; if (phrasesByStart[r.appendPoint] == null) continue; // if (r.numNTs + r.numTerminals < SOURCE_LENGTH_LIMIT && // r.appendPoint - r.rhs.sourceStart < RULE_SPAN_LIMIT) { if ((ALLOW_FULL_SENTENCE_RULES && r.rhs.sourceStart == 0) || (r.numNTs == 0 && r.appendPoint - r.rhs.sourceStart < LEX_SOURCE_LENGTH_LIMIT) || (r.numNTs + r.numTerminals < NONLEX_SOURCE_LENGTH_LIMIT && r.appendPoint - r.rhs.sourceStart < RULE_SPAN_LIMIT)) { Rule s = r.copy(); s.extendWithTerminal(); q.offer(s); } for (PhrasePair pp : phrasesByStart[r.appendPoint]) { if (pp.sourceEnd - r.rhs.sourceStart > RULE_SPAN_LIMIT || (r.rhs.targetStart >= 0 && pp.targetEnd - r.rhs.targetStart > RULE_SPAN_LIMIT)) { if (!ALLOW_FULL_SENTENCE_RULES || r.rhs.sourceStart != 0) continue; } if (r.numNTs < NT_LIMIT && r.numNTs + r.numTerminals < LEX_SOURCE_LENGTH_LIMIT && (!r.sourceEndsWithNT || ALLOW_ADJACENT_NTS)) { Rule s = r.copy(); s.extendWithNonterminal(pp); q.offer(s); } } } return rules; } protected boolean isWellFormed(Rule r) { if (r.rhs.targetStart < 0) return false; // if (r.rhs.targetEnd - r.rhs.targetStart > RULE_SPAN_LIMIT || // r.rhs.sourceEnd - r.rhs.sourceStart > RULE_SPAN_LIMIT) { // if (!ThraxConfig.ALLOW_FULL_SENTENCE_RULES || // r.rhs.sourceStart != 0 || // r.rhs.sourceEnd != r.source.length || // r.rhs.targetStart != 0 || // r.rhs.targetEnd != r.target.length) { // return false; // } // } // if (r.numNTs > 0) { // if (r.numTerminals > NONLEX_SOURCE_WORD_LIMIT) // return false; // if (r.numTerminals + r.numNTs > NONLEX_SOURCE_LENGTH_LIMIT) // return false; // } int targetTerminals = 0; for (int i = r.rhs.targetStart; i < r.rhs.targetEnd; i++) { if (r.targetLex[i] < 0) { if (r.alignment.targetIsAligned(i)) return false; else r.targetLex[i] = 0; } if (r.targetLex[i] == 0) targetTerminals++; if (r.targetLex[i] == 0 && r.alignment.targetIsAligned(i)) { for (int k : r.alignment.e2f[i]) { if (r.sourceLex[k] != 0) return false; } } } if (r.numNTs > 0) { if (r.numTerminals > NONLEX_SOURCE_WORD_LIMIT) return false; if (r.numTerminals + r.numNTs > NONLEX_SOURCE_LENGTH_LIMIT) return false; if (targetTerminals > NONLEX_TARGET_WORD_LIMIT) return false; if (targetTerminals + r.numNTs > NONLEX_TARGET_LENGTH_LIMIT) return false; } else if (r.numNTs == 0) { if (r.numTerminals > LEX_SOURCE_LENGTH_LIMIT || targetTerminals > LEX_TARGET_LENGTH_LIMIT) { // if (!ThraxConfig.ALLOW_FULL_SENTENCE_RULES || // r.rhs.sourceStart != 0 || // r.rhs.sourceEnd != r.source.length || // r.rhs.targetStart != 0 || // r.rhs.targetEnd != r.target.length) { return false; // } } } if (!ALLOW_ABSTRACT && r.numTerminals == 0 && targetTerminals == 0) return false; if (r.rhs.targetEnd - r.rhs.targetStart > RULE_SPAN_LIMIT || - r.rhs.sourceEnd - r.rhs.sourceStart > RULE_SPAN_LIMIT) { + r.rhs.targetEnd - r.rhs.targetStart > INIT_LENGTH_LIMIT || + r.rhs.sourceEnd - r.rhs.sourceStart > RULE_SPAN_LIMIT || + r.rhs.sourceEnd - r.rhs.sourceStart > INIT_LENGTH_LIMIT) { if (ALLOW_FULL_SENTENCE_RULES && r.rhs.sourceStart == 0 && r.rhs.sourceEnd == r.source.length && r.rhs.targetStart == 0 && r.rhs.targetEnd == r.target.length) { return true; } return false; } if (!ALLOW_LOOSE_BOUNDS && (!r.alignment.sourceIsAligned(r.rhs.sourceEnd - 1) || !r.alignment.sourceIsAligned(r.rhs.sourceStart) || !r.alignment.targetIsAligned(r.rhs.targetEnd - 1) || !r.alignment.targetIsAligned(r.rhs.targetStart))) return false; if (!r.rhs.consistentWith(r.alignment)) return false; return (r.alignedWords >= LEXICAL_MINIMUM); } private Collection<Rule> getAlignmentVariants(Rule r) { List<Rule> result = new ArrayList<Rule>(); result.add(r); if (!ALLOW_LOOSE_BOUNDS) return result; if (r.rhs.sourceStart < 0 || r.rhs.sourceEnd < 0 || r.rhs.targetStart < 0 || r.rhs.targetEnd < 0) return result; int targetStart = r.rhs.targetStart; while (targetStart > 0 && !r.alignment.targetIsAligned(targetStart - 1)) { targetStart--; } int targetEnd = r.rhs.targetEnd; while (targetEnd < r.target.length && !r.alignment.targetIsAligned(targetEnd)) { targetEnd++; } for (int i = targetStart; i < r.rhs.targetStart; i++) { Rule s = r.copy(); s.rhs.targetStart = i; s.targetLex[i] = 0; result.add(s); } if (targetEnd == r.rhs.targetEnd) { return result; } List<Rule> otherResult = new ArrayList<Rule>(); for (Rule x : result) { for (int j = r.rhs.targetEnd + 1; j <= targetEnd; j++) { Rule s = x.copy(); s.rhs.targetEnd = j; s.targetLex[j-1] = 0; otherResult.add(s); } } result.addAll(otherResult); return result; } protected Collection<Rule> getLabelVariants(Rule r) { Collection<Rule> result = new HashSet<Rule>(); Queue<Rule> q = new LinkedList<Rule>(); for (int i = 0; i < r.numNTs; i++) r.setNT(i, -1); Collection<Integer> lhsLabels = labeler.getLabels(new IntPair(r.rhs.targetStart, r.rhs.targetEnd)); if (lhsLabels == null || lhsLabels.isEmpty()) { // System.err.println("WARNING: no labels for left-hand side of rule. Span is " + new IntPair(r.rhs.targetStart, r.rhs.targetEnd)); if (!ALLOW_X_NONLEX && r.numNTs > 0) return result; lhsLabels = defaultLabel; } for (int lhs : lhsLabels) { Rule s = r.copy(); s.setLhs(lhs); q.offer(s); } for (int i = 0; i < r.numNTs; i++) { Collection<Integer> labels = labeler.getLabels(r.ntSpan(i)); if (labels == null || labels.isEmpty()) { // System.err.println("WARNING: no labels for target-side span of " + r.ntSpan(i)); if (!ALLOW_X_NONLEX) return result; labels = defaultLabel; } for (Rule s = q.peek(); s != null && s.getNT(i) == -1; s = q.peek()) { s = q.poll(); for (int l : labels) { Rule t = s.copy(); t.setNT(i, l); q.offer(t); } } } result.addAll(q); return result; } protected PhrasePair [][] initialPhrasePairs(int [] f, int [] e, Alignment a) { PhrasePair [][] result = new PhrasePair[f.length][]; List<PhrasePair> list = new ArrayList<PhrasePair>(); for (int i = 0; i < f.length; i++) { list.clear(); int maxlen = f.length - i < INIT_LENGTH_LIMIT ? f.length - i : INIT_LENGTH_LIMIT; for (int len = 1; len <= maxlen; len++) { if (!ALLOW_LOOSE_BOUNDS && (!a.sourceIsAligned(i) || !a.sourceIsAligned(i+len-1))) continue; for (PhrasePair pp : a.getAllPairsFromSource(i, i+len, ALLOW_LOOSE_BOUNDS, e.length)) { if (pp.targetEnd - pp.targetStart <= INIT_LENGTH_LIMIT) { list.add(pp); } } } result[i] = new PhrasePair[list.size()]; for (int j = 0; j < result[i].length; j++) result[i][j] = list.get(j); } return result; } public static void main(String [] argv) throws IOException,MalformedInputException { if (argv.length < 1) { System.err.println("usage: HierarchicalRuleExtractor <conf file>"); return; } Configuration conf = new Configuration(); Map<String,String> options = ConfFileParser.parse(argv[0]); for (String opt : options.keySet()) conf.set("thrax." + opt, options.get(opt)); Scanner scanner = new Scanner(System.in); HieroRuleExtractor extractor = new HieroRuleExtractor(conf); while (scanner.hasNextLine()) { String line = scanner.nextLine(); for (Rule r : extractor.extract(line)) System.out.println(r); } return; } }
true
true
protected boolean isWellFormed(Rule r) { if (r.rhs.targetStart < 0) return false; // if (r.rhs.targetEnd - r.rhs.targetStart > RULE_SPAN_LIMIT || // r.rhs.sourceEnd - r.rhs.sourceStart > RULE_SPAN_LIMIT) { // if (!ThraxConfig.ALLOW_FULL_SENTENCE_RULES || // r.rhs.sourceStart != 0 || // r.rhs.sourceEnd != r.source.length || // r.rhs.targetStart != 0 || // r.rhs.targetEnd != r.target.length) { // return false; // } // } // if (r.numNTs > 0) { // if (r.numTerminals > NONLEX_SOURCE_WORD_LIMIT) // return false; // if (r.numTerminals + r.numNTs > NONLEX_SOURCE_LENGTH_LIMIT) // return false; // } int targetTerminals = 0; for (int i = r.rhs.targetStart; i < r.rhs.targetEnd; i++) { if (r.targetLex[i] < 0) { if (r.alignment.targetIsAligned(i)) return false; else r.targetLex[i] = 0; } if (r.targetLex[i] == 0) targetTerminals++; if (r.targetLex[i] == 0 && r.alignment.targetIsAligned(i)) { for (int k : r.alignment.e2f[i]) { if (r.sourceLex[k] != 0) return false; } } } if (r.numNTs > 0) { if (r.numTerminals > NONLEX_SOURCE_WORD_LIMIT) return false; if (r.numTerminals + r.numNTs > NONLEX_SOURCE_LENGTH_LIMIT) return false; if (targetTerminals > NONLEX_TARGET_WORD_LIMIT) return false; if (targetTerminals + r.numNTs > NONLEX_TARGET_LENGTH_LIMIT) return false; } else if (r.numNTs == 0) { if (r.numTerminals > LEX_SOURCE_LENGTH_LIMIT || targetTerminals > LEX_TARGET_LENGTH_LIMIT) { // if (!ThraxConfig.ALLOW_FULL_SENTENCE_RULES || // r.rhs.sourceStart != 0 || // r.rhs.sourceEnd != r.source.length || // r.rhs.targetStart != 0 || // r.rhs.targetEnd != r.target.length) { return false; // } } } if (!ALLOW_ABSTRACT && r.numTerminals == 0 && targetTerminals == 0) return false; if (r.rhs.targetEnd - r.rhs.targetStart > RULE_SPAN_LIMIT || r.rhs.sourceEnd - r.rhs.sourceStart > RULE_SPAN_LIMIT) { if (ALLOW_FULL_SENTENCE_RULES && r.rhs.sourceStart == 0 && r.rhs.sourceEnd == r.source.length && r.rhs.targetStart == 0 && r.rhs.targetEnd == r.target.length) { return true; } return false; } if (!ALLOW_LOOSE_BOUNDS && (!r.alignment.sourceIsAligned(r.rhs.sourceEnd - 1) || !r.alignment.sourceIsAligned(r.rhs.sourceStart) || !r.alignment.targetIsAligned(r.rhs.targetEnd - 1) || !r.alignment.targetIsAligned(r.rhs.targetStart))) return false; if (!r.rhs.consistentWith(r.alignment)) return false; return (r.alignedWords >= LEXICAL_MINIMUM); }
protected boolean isWellFormed(Rule r) { if (r.rhs.targetStart < 0) return false; // if (r.rhs.targetEnd - r.rhs.targetStart > RULE_SPAN_LIMIT || // r.rhs.sourceEnd - r.rhs.sourceStart > RULE_SPAN_LIMIT) { // if (!ThraxConfig.ALLOW_FULL_SENTENCE_RULES || // r.rhs.sourceStart != 0 || // r.rhs.sourceEnd != r.source.length || // r.rhs.targetStart != 0 || // r.rhs.targetEnd != r.target.length) { // return false; // } // } // if (r.numNTs > 0) { // if (r.numTerminals > NONLEX_SOURCE_WORD_LIMIT) // return false; // if (r.numTerminals + r.numNTs > NONLEX_SOURCE_LENGTH_LIMIT) // return false; // } int targetTerminals = 0; for (int i = r.rhs.targetStart; i < r.rhs.targetEnd; i++) { if (r.targetLex[i] < 0) { if (r.alignment.targetIsAligned(i)) return false; else r.targetLex[i] = 0; } if (r.targetLex[i] == 0) targetTerminals++; if (r.targetLex[i] == 0 && r.alignment.targetIsAligned(i)) { for (int k : r.alignment.e2f[i]) { if (r.sourceLex[k] != 0) return false; } } } if (r.numNTs > 0) { if (r.numTerminals > NONLEX_SOURCE_WORD_LIMIT) return false; if (r.numTerminals + r.numNTs > NONLEX_SOURCE_LENGTH_LIMIT) return false; if (targetTerminals > NONLEX_TARGET_WORD_LIMIT) return false; if (targetTerminals + r.numNTs > NONLEX_TARGET_LENGTH_LIMIT) return false; } else if (r.numNTs == 0) { if (r.numTerminals > LEX_SOURCE_LENGTH_LIMIT || targetTerminals > LEX_TARGET_LENGTH_LIMIT) { // if (!ThraxConfig.ALLOW_FULL_SENTENCE_RULES || // r.rhs.sourceStart != 0 || // r.rhs.sourceEnd != r.source.length || // r.rhs.targetStart != 0 || // r.rhs.targetEnd != r.target.length) { return false; // } } } if (!ALLOW_ABSTRACT && r.numTerminals == 0 && targetTerminals == 0) return false; if (r.rhs.targetEnd - r.rhs.targetStart > RULE_SPAN_LIMIT || r.rhs.targetEnd - r.rhs.targetStart > INIT_LENGTH_LIMIT || r.rhs.sourceEnd - r.rhs.sourceStart > RULE_SPAN_LIMIT || r.rhs.sourceEnd - r.rhs.sourceStart > INIT_LENGTH_LIMIT) { if (ALLOW_FULL_SENTENCE_RULES && r.rhs.sourceStart == 0 && r.rhs.sourceEnd == r.source.length && r.rhs.targetStart == 0 && r.rhs.targetEnd == r.target.length) { return true; } return false; } if (!ALLOW_LOOSE_BOUNDS && (!r.alignment.sourceIsAligned(r.rhs.sourceEnd - 1) || !r.alignment.sourceIsAligned(r.rhs.sourceStart) || !r.alignment.targetIsAligned(r.rhs.targetEnd - 1) || !r.alignment.targetIsAligned(r.rhs.targetStart))) return false; if (!r.rhs.consistentWith(r.alignment)) return false; return (r.alignedWords >= LEXICAL_MINIMUM); }
diff --git a/src/edu/rpi/cmt/access/test/AccessTest.java b/src/edu/rpi/cmt/access/test/AccessTest.java index 070157d..df77227 100644 --- a/src/edu/rpi/cmt/access/test/AccessTest.java +++ b/src/edu/rpi/cmt/access/test/AccessTest.java @@ -1,201 +1,201 @@ /* ********************************************************************** Copyright 2006 Rensselaer Polytechnic Institute. All worldwide rights reserved. Redistribution and use of this distribution in source and binary forms, with or without modification, are permitted provided that: The above copyright notice and this permission notice appear in all copies and supporting documentation; The name, identifiers, and trademarks of Rensselaer Polytechnic Institute are not used in advertising or publicity without the express prior written permission of Rensselaer Polytechnic Institute; DISCLAIMER: The software is distributed" AS IS" without any express or implied warranty, including but not limited to, any implied warranties of merchantability or fitness for a particular purpose or any warrant)' of non-infringement of any current or pending patent rights. The authors of the software make no representations about the suitability of this software for any particular purpose. The entire risk as to the quality and performance of the software is with the user. Should the software prove defective, the user assumes the cost of all necessary servicing, repair or correction. In particular, neither Rensselaer Polytechnic Institute, nor the authors of the software are liable for any indirect, special, consequential, or incidental damages related to the software, to the maximum extent the law permits. */ package edu.rpi.cmt.access.test; import edu.rpi.cmt.access.Ace; import edu.rpi.cmt.access.Acl; import edu.rpi.cmt.access.Privilege; import edu.rpi.cmt.access.Privileges; import edu.rpi.cmt.access.Acl.CurrentAccess; import junit.framework.TestCase; /** Test the access classes * * @author Mike Douglass [email protected] @version 1.0 */ public class AccessTest extends TestCase { boolean debug = true; /** * */ public void testBasics() { try { - // Make sonme test objects + // Make some test objects User unauth = new User(); User owner = new User("anowner"); User auser = new User("auser"); User auserInGroup = new User("auseringroup"); Group agroup = new Group("agroup"); Group bgroup = new Group("bgroup"); auserInGroup.addGroup(agroup); auserInGroup.addGroup(bgroup); Group cgroup = new Group("cgroup"); cgroup.addGroup(agroup); User userInCgroup = new User("userincgroup"); userInCgroup.addGroup(cgroup); userInCgroup.addGroup(agroup); // cgroup is in agroup Privilege read = Privileges.makePriv(Privileges.privRead); Privilege delete = Privileges.makePriv(Privileges.privUnbind); Privilege write = Privileges.makePriv(Privileges.privWrite); Privilege writeContent = Privileges.makePriv(Privileges.privWriteContent); Privilege[] privSetRead = {read}; Privilege[] privSetWrite = {write}; Privilege[] privSetWriteContent = {writeContent}; Privilege[] privSetReadWrite = {read, write}; Privilege[] privSetReadWriteContent = {read, writeContent}; Privilege[] privSetDelete = {delete}; /* See what we get when we encode a null - that's default - acl. */ Acl acl = new Acl(debug); char[] encoded = logEncoded(acl, "default"); tryDecode(encoded, "default"); tryEvaluateAccess(owner, owner, privSetRead, encoded, true, "Owner access for default"); tryEvaluateAccess(auser, owner, privSetRead, encoded, false, "User access for default"); log("---------------------------------------------------------"); /* read others - i.e. not owner */ acl = new Acl(debug); acl.addAce(new Ace(null, false, Ace.whoTypeOther, Privileges.makePriv(Privileges.privRead))); encoded = logEncoded(acl, "read others"); tryDecode(encoded, "read others"); tryEvaluateAccess(owner, owner, privSetReadWrite, encoded, true, "Owner access for read others"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "User access for read others"); tryEvaluateAccess(unauth, owner, privSetRead, encoded, false, "Unauthenticated access for read others"); log("---------------------------------------------------------"); /* read for group "agroup", rw for user "auser" */ acl = new Acl(debug); Ace ace = new Ace("agroup", false, Ace.whoTypeGroup, Privileges.makePriv(Privileges.privRead)); acl.addAce(ace); ace = new Ace("auser", false, Ace.whoTypeUser); ace.addPriv(Privileges.makePriv(Privileges.privRead)); ace.addPriv(Privileges.makePriv(Privileges.privWriteContent)); acl.addAce(ace); encoded = logEncoded(acl, "read g=agroup,rw auser"); tryDecode(encoded, "read g=agroup,rw auser"); tryEvaluateAccess(owner, owner, privSetReadWriteContent, encoded, true, "Owner access for read g=agroup,rw auser"); tryEvaluateAccess(auserInGroup, owner, privSetRead, encoded, true, "User access for read g=agroup,rw auser"); tryEvaluateAccess(userInCgroup, owner, privSetRead, encoded, true, "userInCgroup access for read g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "auser access for read g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetWriteContent, encoded, true, "auser access for write g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetWrite, encoded, false, "auser access for write g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetDelete, encoded, false, "auser access for write g=agroup,rw auser"); log("---------------------------------------------------------"); /* read for group "agroup", rw for user "auser" */ acl = new Acl(debug); acl.addAce(new Ace(null, false, Ace.whoTypeAll, Privileges.makePriv(Privileges.privRead))); acl.addAce(new Ace(null, false, Ace.whoTypeUnauthenticated, Privileges.makePriv(Privileges.privNone))); encoded = logEncoded(acl, "read others,none unauthenticated"); tryDecode(encoded, "read others,none unauthenticated"); tryEvaluateAccess(owner, owner, privSetReadWrite, encoded, true, "Owner access for read others,none unauthenticated"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "User access for read others,none unauthenticated"); tryEvaluateAccess(unauth, owner, privSetRead, encoded, false, "Unauthenticated access for read others,none unauthenticated"); } catch (Throwable t) { t.printStackTrace(); fail("Exception testing access: " + t.getMessage()); } } /* ==================================================================== * Private methods. * ==================================================================== */ private void tryEvaluateAccess(Principal who, Principal owner, Privilege[] how,char[] encoded, boolean expected, String title) throws Throwable { CurrentAccess ca = new Acl(debug).evaluateAccess(who, owner.getAccount(), how, encoded, null); if (debug) { log(title + " got " + ca.accessAllowed + " and expected " + expected); } assertEquals(title, expected, ca.accessAllowed); } private void tryDecode(char[] encoded, String title) throws Throwable { Acl acl = new Acl(); acl.decode(encoded); log("Result of decoding " + title); log(acl.toString()); log(acl.toUserString()); } private char[] logEncoded(Acl acl, String title) throws Throwable { char [] encoded = acl.encode(); String s = new String(encoded); log(title + "='" + s + "'"); return encoded; } private void log(String msg) { System.out.println(this.getClass().getName() + ": " + msg); } }
true
true
public void testBasics() { try { // Make sonme test objects User unauth = new User(); User owner = new User("anowner"); User auser = new User("auser"); User auserInGroup = new User("auseringroup"); Group agroup = new Group("agroup"); Group bgroup = new Group("bgroup"); auserInGroup.addGroup(agroup); auserInGroup.addGroup(bgroup); Group cgroup = new Group("cgroup"); cgroup.addGroup(agroup); User userInCgroup = new User("userincgroup"); userInCgroup.addGroup(cgroup); userInCgroup.addGroup(agroup); // cgroup is in agroup Privilege read = Privileges.makePriv(Privileges.privRead); Privilege delete = Privileges.makePriv(Privileges.privUnbind); Privilege write = Privileges.makePriv(Privileges.privWrite); Privilege writeContent = Privileges.makePriv(Privileges.privWriteContent); Privilege[] privSetRead = {read}; Privilege[] privSetWrite = {write}; Privilege[] privSetWriteContent = {writeContent}; Privilege[] privSetReadWrite = {read, write}; Privilege[] privSetReadWriteContent = {read, writeContent}; Privilege[] privSetDelete = {delete}; /* See what we get when we encode a null - that's default - acl. */ Acl acl = new Acl(debug); char[] encoded = logEncoded(acl, "default"); tryDecode(encoded, "default"); tryEvaluateAccess(owner, owner, privSetRead, encoded, true, "Owner access for default"); tryEvaluateAccess(auser, owner, privSetRead, encoded, false, "User access for default"); log("---------------------------------------------------------"); /* read others - i.e. not owner */ acl = new Acl(debug); acl.addAce(new Ace(null, false, Ace.whoTypeOther, Privileges.makePriv(Privileges.privRead))); encoded = logEncoded(acl, "read others"); tryDecode(encoded, "read others"); tryEvaluateAccess(owner, owner, privSetReadWrite, encoded, true, "Owner access for read others"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "User access for read others"); tryEvaluateAccess(unauth, owner, privSetRead, encoded, false, "Unauthenticated access for read others"); log("---------------------------------------------------------"); /* read for group "agroup", rw for user "auser" */ acl = new Acl(debug); Ace ace = new Ace("agroup", false, Ace.whoTypeGroup, Privileges.makePriv(Privileges.privRead)); acl.addAce(ace); ace = new Ace("auser", false, Ace.whoTypeUser); ace.addPriv(Privileges.makePriv(Privileges.privRead)); ace.addPriv(Privileges.makePriv(Privileges.privWriteContent)); acl.addAce(ace); encoded = logEncoded(acl, "read g=agroup,rw auser"); tryDecode(encoded, "read g=agroup,rw auser"); tryEvaluateAccess(owner, owner, privSetReadWriteContent, encoded, true, "Owner access for read g=agroup,rw auser"); tryEvaluateAccess(auserInGroup, owner, privSetRead, encoded, true, "User access for read g=agroup,rw auser"); tryEvaluateAccess(userInCgroup, owner, privSetRead, encoded, true, "userInCgroup access for read g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "auser access for read g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetWriteContent, encoded, true, "auser access for write g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetWrite, encoded, false, "auser access for write g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetDelete, encoded, false, "auser access for write g=agroup,rw auser"); log("---------------------------------------------------------"); /* read for group "agroup", rw for user "auser" */ acl = new Acl(debug); acl.addAce(new Ace(null, false, Ace.whoTypeAll, Privileges.makePriv(Privileges.privRead))); acl.addAce(new Ace(null, false, Ace.whoTypeUnauthenticated, Privileges.makePriv(Privileges.privNone))); encoded = logEncoded(acl, "read others,none unauthenticated"); tryDecode(encoded, "read others,none unauthenticated"); tryEvaluateAccess(owner, owner, privSetReadWrite, encoded, true, "Owner access for read others,none unauthenticated"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "User access for read others,none unauthenticated"); tryEvaluateAccess(unauth, owner, privSetRead, encoded, false, "Unauthenticated access for read others,none unauthenticated"); } catch (Throwable t) { t.printStackTrace(); fail("Exception testing access: " + t.getMessage()); } }
public void testBasics() { try { // Make some test objects User unauth = new User(); User owner = new User("anowner"); User auser = new User("auser"); User auserInGroup = new User("auseringroup"); Group agroup = new Group("agroup"); Group bgroup = new Group("bgroup"); auserInGroup.addGroup(agroup); auserInGroup.addGroup(bgroup); Group cgroup = new Group("cgroup"); cgroup.addGroup(agroup); User userInCgroup = new User("userincgroup"); userInCgroup.addGroup(cgroup); userInCgroup.addGroup(agroup); // cgroup is in agroup Privilege read = Privileges.makePriv(Privileges.privRead); Privilege delete = Privileges.makePriv(Privileges.privUnbind); Privilege write = Privileges.makePriv(Privileges.privWrite); Privilege writeContent = Privileges.makePriv(Privileges.privWriteContent); Privilege[] privSetRead = {read}; Privilege[] privSetWrite = {write}; Privilege[] privSetWriteContent = {writeContent}; Privilege[] privSetReadWrite = {read, write}; Privilege[] privSetReadWriteContent = {read, writeContent}; Privilege[] privSetDelete = {delete}; /* See what we get when we encode a null - that's default - acl. */ Acl acl = new Acl(debug); char[] encoded = logEncoded(acl, "default"); tryDecode(encoded, "default"); tryEvaluateAccess(owner, owner, privSetRead, encoded, true, "Owner access for default"); tryEvaluateAccess(auser, owner, privSetRead, encoded, false, "User access for default"); log("---------------------------------------------------------"); /* read others - i.e. not owner */ acl = new Acl(debug); acl.addAce(new Ace(null, false, Ace.whoTypeOther, Privileges.makePriv(Privileges.privRead))); encoded = logEncoded(acl, "read others"); tryDecode(encoded, "read others"); tryEvaluateAccess(owner, owner, privSetReadWrite, encoded, true, "Owner access for read others"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "User access for read others"); tryEvaluateAccess(unauth, owner, privSetRead, encoded, false, "Unauthenticated access for read others"); log("---------------------------------------------------------"); /* read for group "agroup", rw for user "auser" */ acl = new Acl(debug); Ace ace = new Ace("agroup", false, Ace.whoTypeGroup, Privileges.makePriv(Privileges.privRead)); acl.addAce(ace); ace = new Ace("auser", false, Ace.whoTypeUser); ace.addPriv(Privileges.makePriv(Privileges.privRead)); ace.addPriv(Privileges.makePriv(Privileges.privWriteContent)); acl.addAce(ace); encoded = logEncoded(acl, "read g=agroup,rw auser"); tryDecode(encoded, "read g=agroup,rw auser"); tryEvaluateAccess(owner, owner, privSetReadWriteContent, encoded, true, "Owner access for read g=agroup,rw auser"); tryEvaluateAccess(auserInGroup, owner, privSetRead, encoded, true, "User access for read g=agroup,rw auser"); tryEvaluateAccess(userInCgroup, owner, privSetRead, encoded, true, "userInCgroup access for read g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "auser access for read g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetWriteContent, encoded, true, "auser access for write g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetWrite, encoded, false, "auser access for write g=agroup,rw auser"); tryEvaluateAccess(auser, owner, privSetDelete, encoded, false, "auser access for write g=agroup,rw auser"); log("---------------------------------------------------------"); /* read for group "agroup", rw for user "auser" */ acl = new Acl(debug); acl.addAce(new Ace(null, false, Ace.whoTypeAll, Privileges.makePriv(Privileges.privRead))); acl.addAce(new Ace(null, false, Ace.whoTypeUnauthenticated, Privileges.makePriv(Privileges.privNone))); encoded = logEncoded(acl, "read others,none unauthenticated"); tryDecode(encoded, "read others,none unauthenticated"); tryEvaluateAccess(owner, owner, privSetReadWrite, encoded, true, "Owner access for read others,none unauthenticated"); tryEvaluateAccess(auser, owner, privSetRead, encoded, true, "User access for read others,none unauthenticated"); tryEvaluateAccess(unauth, owner, privSetRead, encoded, false, "Unauthenticated access for read others,none unauthenticated"); } catch (Throwable t) { t.printStackTrace(); fail("Exception testing access: " + t.getMessage()); } }
diff --git a/src/free/jin/freechess/JinFreechessConnection.java b/src/free/jin/freechess/JinFreechessConnection.java index 77bf357..1ac04f4 100644 --- a/src/free/jin/freechess/JinFreechessConnection.java +++ b/src/free/jin/freechess/JinFreechessConnection.java @@ -1,2885 +1,2885 @@ /** * Jin - a chess client for internet chess servers. * More information is available at http://www.jinchess.com/. * Copyright (C) 2002, 2003 Alexander Maryanovsky. * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package free.jin.freechess; import free.chess.*; import free.chess.variants.BothSidesCastlingVariant; import free.chess.variants.NoCastlingVariant; import free.chess.variants.atomic.Atomic; import free.chess.variants.bughouse.Bughouse; import free.chess.variants.fischerrandom.FischerRandom; import free.chess.variants.suicide.Suicide; import free.chessclub.ChessclubConnection; import free.freechess.*; import free.jin.*; import free.jin.event.*; import free.jin.freechess.event.IvarStateChangeEvent; import free.util.Pair; import free.util.TextUtilities; import javax.swing.*; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * An implementation of the JinConnection interface for the freechess.org * server. */ public class JinFreechessConnection extends FreechessConnection implements Connection, SeekConnection, PGNConnection, ChannelsConnection, MessagesConnection, BughouseConnection{ //TODO add implementation of FreechessChannelsConnection. //TODO add methods and regular expressions to handle channel list events. /** * Overrides getConnectionName() method returning name of connection. whp 2006 */ public String getConnectionName(){ return "FreechessConnection"; } /** * Boolean indicating whether this connection's method waits for game info from * processing line about examined game. */ private boolean waiting = false; /** * The examined game Style12Struct. */ private Style12Struct examinedGameBoardData; /** * The number of examined game we are willing to gather information about. */ private int examinedGameId; /** * The variant of examined game. */ private String examinedGameVariant; /** * Boolean telling whether examined game is rated. */ private boolean isExaminedRated; /** * Boolean telling whether examined game is private. */ private boolean isExaminedPrivate; /** * Our listener manager. */ private final FreechessListenerManager listenerManager = new FreechessListenerManager(this); /** * Creates a new JinFreechessConnection with the specified hostname, port, * requested username and password. */ public JinFreechessConnection(String requestedUsername, String password){ super(requestedUsername, password, System.out); setInterface(Jin.getInstance().getAppName() + ' ' + Jin.getInstance().getAppVersion() + " (" + System.getProperty("java.vendor") + ' ' + System.getProperty("java.version") + ", " + System.getProperty("os.name") + ' ' + getSafeOSVersion() + ')'); setStyle(12); setIvarState(Ivar.GAMEINFO, true); setIvarState(Ivar.SHOWOWNSEEK, true); setIvarState(Ivar.PENDINFO, true); setIvarState(Ivar.MOVECASE, true); // setIvarState(Ivar.COMPRESSMOVE, true); Pending DAV's bugfixing spree setIvarState(Ivar.LOCK, true); } /** * <code>sendCommand()</code> method overriden * to get rid of bug [ 1642877 ] Non-channel numbers list pass to channel manager */ public void sendCommand(String command){ super.sendCommand(command); userChannelListNext = false; } /** * Returns the OS version after stripping out the patch level from it. * We do this to avoid revealing that information to everyone on the server. */ private static String getSafeOSVersion(){ String osVersion = System.getProperty("os.version"); int i = osVersion.indexOf(".", osVersion.indexOf(".") + 1); if (i != -1) osVersion = osVersion.substring(0, i) + ".x"; return osVersion; } /** * Returns a Player object corresponding to the specified string. If the * string is "W", returns <code>Player.WHITE</code>. If it's "B", returns * <code>Player.BLACK</code>. Otherwise, throws an IllegalArgumentException. */ public static Player playerForString(String s){ if (s.equals("B")) return Player.BLACK_PLAYER; else if (s.equals("W")) return Player.WHITE_PLAYER; else throw new IllegalArgumentException("Bad player string: "+s); } /** * Returns our ListenerManager. */ public ListenerManager getListenerManager(){ return getFreechessListenerManager(); } /** * Returns out ListenerManager as a reference to FreechessListenerManager. */ public FreechessListenerManager getFreechessListenerManager(){ return listenerManager; } /** * Fires an "attempting" connection event and invokes {@link free.util.Connection#initiateConnect(String, int)}. */ public void initiateConnectAndLogin(String hostname, int port){ listenerManager.fireConnectionAttempted(this, hostname, port); initiateConnect(hostname, port); } /** * Fires an "established" connection event. */ protected void handleConnected(){ listenerManager.fireConnectionEstablished(this); super.handleConnected(); } /** * Fires a "failed" connection event. */ protected void handleConnectingFailed(IOException e){ listenerManager.fireConnectingFailed(this, e.getMessage()); super.handleConnectingFailed(e); } /** * Fires a "login succeeded" connection event and performs other on-login tasks. */ protected void handleLoginSucceeded(){ super.handleLoginSucceeded(); sendCommand("$set bell 0"); filterLine("Bell off."); listenerManager.fireLoginSucceeded(this); } /** * Fires a "login failed" connection event. */ protected void handleLoginFailed(String reason){ listenerManager.fireLoginFailed(this, reason); super.handleLoginFailed(reason); } /** * Fires a "connection lost" connection event. */ protected void handleDisconnection(IOException e){ listenerManager.fireConnectionLost(this); super.handleDisconnection(e); } /** * Overrides {@link free.util.Connection#connectImpl(String, int)} to return a timesealing socket. */ protected Socket connectImpl(String hostname, int port) throws IOException{ // Comment this to disable timesealing return new free.freechess.timeseal.TimesealingSocket(hostname, port); // Comment this to enable timesealing // return new Socket(hostname, port); } /** * Notifies any interested PlainTextListener of the received line of otherwise * unidentified text. */ protected void processLine(String line){ listenerManager.firePlainTextEvent(new PlainTextEvent(this, line)); } /** * Gets called when the server notifies us of a change in the state of some * ivar. */ protected boolean processIvarStateChanged(Ivar ivar, boolean state){ IvarStateChangeEvent evt = new IvarStateChangeEvent(this, ivar, state); listenerManager.fireIvarStateChangeEvent(evt); return false; } /** * Fires an appropriate ChatEvent. */ protected boolean processPersonalTell(String username, String titles, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "tell", ChatEvent.PERSON_TO_PERSON_CHAT_CATEGORY, username, (titles == null ? "" : titles), -1, message, null)); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processSayTell(String username, String titles, int gameNumber, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "say", ChatEvent.PERSON_TO_PERSON_CHAT_CATEGORY, username, (titles == null ? "" : titles), -1, message, new Integer(gameNumber))); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processPTell(String username, String titles, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "ptell", ChatEvent.PERSON_TO_PERSON_CHAT_CATEGORY, username, (titles == null ? "" : titles), -1, message, null)); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processChannelTell(String username, String titles, int channelNumber, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "channel-tell", ChatEvent.ROOM_CHAT_CATEGORY, username, (titles == null ? "" : titles), -1, message, new Integer(channelNumber))); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processKibitz(String username, String titles, int rating, int gameNumber, String message){ if (titles == null) titles = ""; listenerManager.fireChatEvent(new ChatEvent(this, "kibitz", ChatEvent.GAME_CHAT_CATEGORY, username, titles, rating, message, new Integer(gameNumber))); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processWhisper(String username, String titles, int rating, int gameNumber, String message){ if (titles == null) titles = ""; listenerManager.fireChatEvent(new ChatEvent(this, "whisper", ChatEvent.GAME_CHAT_CATEGORY, username, titles, rating, message, new Integer(gameNumber))); return true; } /** * Regex for matching tourney tell qtells. */ private static final Pattern TOURNEY_TELL_REGEX = Pattern.compile("^("+USERNAME_REGEX+")("+TITLES_REGEX+")?\\(T(\\d+)\\): (.*)"); /** * Fires an appropriate ChatEvent. */ protected boolean processQTell(String message){ ChatEvent evt; Matcher matcher = TOURNEY_TELL_REGEX.matcher(message); if (matcher.matches()){ String sender = matcher.group(1); String title = matcher.group(2); if (title == null) title = ""; Integer tourneyIndex = new Integer(matcher.group(3)); message = matcher.group(4); evt = new ChatEvent(this, "qtell.tourney", ChatEvent.TOURNEY_CHAT_CATEGORY, sender, title, -1, message, tourneyIndex); } else{ evt = new ChatEvent(this, "qtell", ChatEvent.PERSON_TO_PERSON_CHAT_CATEGORY, null, null, -1, message, null); } listenerManager.fireChatEvent(evt); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processShout(String username, String titles, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "shout", ChatEvent.ROOM_CHAT_CATEGORY, username, (titles == null ? "" : titles), -1, message, null)); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processIShout(String username, String titles, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "ishout", ChatEvent.ROOM_CHAT_CATEGORY, username, (titles == null ? "" : titles), -1, message, null)); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processTShout(String username, String titles, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "tshout", ChatEvent.TOURNEY_CHAT_CATEGORY, username, (titles == null ? "" : titles), -1, message, null)); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processCShout(String username, String titles, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "cshout", ChatEvent.ROOM_CHAT_CATEGORY, username, (titles == null ? "" : titles), -1, message, null)); return true; } /** * Fires an appropriate ChatEvent. */ protected boolean processAnnouncement(String username, String message){ listenerManager.fireChatEvent(new ChatEvent(this, "announcement", ChatEvent.BROADCAST_CHAT_CATEGORY, username, "", -1, message, null)); return true; } /** * Fires an appropriate ChannelsEvent. */ protected boolean processChannelListChanged(String change, int channelNumber){ if (change.equals("added")){ int[] channelsNumbers = {999}; listenerManager.fireChannelsEvent(new ChannelsEvent(this, ChannelsEvent.CHANNEL_ADDED, channelNumber, channelsNumbers)); } if (change.equals("removed")){ int[] channelsNumbers = {999}; listenerManager.fireChannelsEvent(new ChannelsEvent(this, ChannelsEvent.CHANNEL_REMOVED, channelNumber, channelsNumbers)); } return false; } /** * Field that states wether next line is user's channel list. */ boolean userChannelListNext = true; /** * Assures wether the next line is user's channel list. */ protected boolean processUserChannelListNext(String userName){ if (!userName.equals(Jin.getInstance().getConnManager().getSession().getUser().getUsername())){ this.userChannelListNext = false; } else{ this.userChannelListNext = true; } if (userName.equals("ok")){ this.userChannelListNext = true; } else{ this.userChannelListNext = false; } if (!this.fromPlugin){ return false; } else { return true; } } /** * Fires an appropriate @{link}ChannelsEvent. */ protected boolean processChannelListArrives(String channelsNumbers){ //System.out.println(">>>USER_CHANNEL_LIST_NEXT = " + this.userChannelListNext); if (userChannelListNext == false){ return false; } else{ int channelNumber = 999; String[] channelsNumbersStrings = channelsNumbers.split("\\s{1,4}"); int[] channels = new int[channelsNumbersStrings.length]; for (int i = 0; i < channelsNumbersStrings.length; i++){ //System.out.println("#" + i + " CHANNEL = " + channelsNumbersStrings[i]); channels[i] = Integer.parseInt(channelsNumbersStrings[i]); } listenerManager.fireChannelsEvent(new ChannelsEvent(this, ChannelsEvent.USER_CHANNEL_LIST_RECEIVED, channelNumber, channels)); //this.userChannelListNext = false; } if (this.fromPlugin == false){ return false; } else { return true; } } /** * Fires an appropriate @{link}MessageEvent (the one with information about unread messages number). */ protected boolean processMessagesInfo(int allMessages, int unreadMessages){ System.out.println("YOU HAVE UNREAD MESSAGES. " + unreadMessages + " that is."); return false; } /** * Fires an appropriate @{link}MessageEvent (message's content, sender, date and number in messages list). */ protected boolean processMessages(int number, String user, String date, String content){ System.out.println("Message received:" + content); return false; } /*; * Returns the wild variant corresponding to the given server wild variant * name/category name, or <code>null</code> if that category is not supported. */ private static WildVariant getVariant(String categoryName){ if (categoryName.equalsIgnoreCase("lightning") || categoryName.equalsIgnoreCase("blitz") || categoryName.equalsIgnoreCase("standard") || categoryName.equalsIgnoreCase("untimed")) return Chess.getInstance(); if (categoryName.startsWith("wild/")){ String wildId = categoryName.substring("wild/".length()); if (wildId.equals("0") || wildId.equals("1")) return new BothSidesCastlingVariant(Chess.INITIAL_POSITION_FEN, categoryName); else if (wildId.equals("2") || wildId.equals("3")) return new NoCastlingVariant(Chess.INITIAL_POSITION_FEN, categoryName); else if (wildId.equals("5") || wildId.equals("8") || wildId.equals("8a")) return new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, categoryName); else if (wildId.equals("fr")) return FischerRandom.getInstance(); } else if (categoryName.equals("pawns/pawns-only")) return new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, categoryName); else if (categoryName.equals("nonstandard")) return new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, categoryName); else if (categoryName.equals("suicide")) return Suicide.getInstance(); else if (categoryName.equals("losers")) return new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, categoryName); else if (categoryName.equals("atomic")) return Atomic.getInstance(); else if (categoryName.equals("bughouse") || categoryName.equals("crazyhouse")){ return Bughouse.getInstance(); } // This means it's a fake variant we're using because the server hasn't told us the real one. else if (categoryName.equals("Unknown variant")) return Chess.getInstance(); return null; } /** * Returns the wild variant name corresponding to the specified wild variant, * that can be used for issuing a seek, e.g. "w1" or "fr". * Returns null if the specified wild variant is not supported by FICS. */ private String getWildName(WildVariant variant){ if (variant == null) throw new IllegalArgumentException("Null variant"); String variantName = variant.getName(); if (variantName.startsWith("wild/")) return "w" + variantName.substring("wild/".length()); else if (variant.equals(Chess.getInstance())) return ""; else if (variant.equals(FischerRandom.getInstance())) return "fr"; else if (variant.equals(Suicide.getInstance())) return "suicide"; else if (variant.equals(Atomic.getInstance())) return "atomic"; else if ("losers".equals(variantName)) return "losers"; else if (variantName.startsWith("uwild")) return "uwild" + variantName.substring("uwild".length()); else if (variantName.startsWith("pawns")) return "pawns" + variantName.substring("pawns".length()); else if (variantName.startsWith("odds")) return "odds" + variantName.substring("odds".length()); else if (variantName.startsWith("misc")) return "misc" + variantName.substring("misc".length()); else if (variantName.startsWith("openings")) return "openings" + variantName.substring("openings".length()); return null; } /** * A list of supported wild variants, initialized lazily. */ private static WildVariant [] wildVariants; //TODO: Describe all the variants /** * Returns a list of support wild variants. */ public WildVariant [] getSupportedVariants(){ if (wildVariants == null){ wildVariants = new WildVariant[]{ Chess.getInstance(), FischerRandom.getInstance(), Suicide.getInstance(), Atomic.getInstance(), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "losers"), new BothSidesCastlingVariant(Chess.INITIAL_POSITION_FEN, "wild/0"), new BothSidesCastlingVariant(Chess.INITIAL_POSITION_FEN, "wild/1"), new NoCastlingVariant(Chess.INITIAL_POSITION_FEN, "wild/2"), new NoCastlingVariant(Chess.INITIAL_POSITION_FEN, "wild/3"), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "wild/5"), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "wild/8"), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "wild/8a"), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "misc little-game"), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "pawns pawns-only"), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "odds"), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "openings"), new ChesslikeGenericVariant(Chess.INITIAL_POSITION_FEN, "uwild"), }; } return (WildVariant [])wildVariants.clone(); } /** * A HashMap where we keep game numbers mapped to GameInfoStruct objects * of games that haven't started yet. */ private final HashMap unstartedGamesData = new HashMap(1); /** * Maps game numbers to InternalGameData objects of ongoing games. */ private final HashMap ongoingGamesData = new HashMap(5); /** * A HashMap mapping Game objects to ArrayLists of moves which were sent for * these games but the server didn't tell us yet whether the move is legal * or not. */ private final HashMap unechoedMoves = new HashMap(1); /** * A list of game numbers of ongoing games which we can't support for some * reason (not a supported variant for example). */ private final ArrayList unsupportedGames = new ArrayList(); /** * The user's primary played (by the user) game, -1 if unknown. This is only * set when the user is playing more than one game. */ private int primaryPlayedGame = -1; /** * The user's primary observed game, -1 if unknown. This is only set when * the user is observing more than one game. */ private int primaryObservedGame = -1; /** * Returns the game with the specified number. * This method (currently) exists solely for the benefit of the arrow/circle * script. */ public Game getGame(int gameNumber) throws NoSuchGameException{ return getGameData(gameNumber).game; } /** * Returns the InternalGameData for the ongoing game with the specified * number. Throws a <code>NoSuchGameException</code> if there's no such game. */ private InternalGameData getGameData(int gameNumber) throws NoSuchGameException{ InternalGameData gameData = (InternalGameData)ongoingGamesData.get(new Integer(gameNumber)); if (gameData == null) throw new NoSuchGameException(); return gameData; } /** * Finds the (primary) game played by the user. Throws a * <code>NoSuchGameException</code> if there's no such game. */ private InternalGameData findMyGame() throws NoSuchGameException{ if (primaryPlayedGame != -1) return getGameData(primaryPlayedGame); Iterator gameNumbers = ongoingGamesData.keySet().iterator(); while (gameNumbers.hasNext()){ Integer gameNumber = (Integer)gameNumbers.next(); InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNumber); Game game = gameData.game; if (game.getGameType() == Game.MY_GAME) return gameData; } throw new NoSuchGameException(); } /** * Finds the played user's game against the specified opponent. * Returns the game number of null if no such game exists. */ private InternalGameData findMyGameAgainst(String playerName) throws NoSuchGameException{ Iterator gameNumbers = ongoingGamesData.keySet().iterator(); while (gameNumbers.hasNext()){ Integer gameNumber = (Integer)gameNumbers.next(); InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNumber); Game game = gameData.game; Player userPlayer = game.getUserPlayer(); if (userPlayer == null) // Not our game or not played continue; Player oppPlayer = userPlayer.getOpponent(); if ((oppPlayer.isWhite() && game.getWhiteName().equals(playerName)) || (oppPlayer.isBlack() && game.getBlackName().equals(playerName))) return gameData; } throw new NoSuchGameException(); } /** * Saves the GameInfoStruct until we receive enough info to fire a * GameStartEvent. */ protected boolean processGameInfo(GameInfoStruct data){ unstartedGamesData.put(new Integer(data.getGameNumber()), data); return true; } /** * Fires an appropriate GameEvent depending on the situation. */ @Override protected boolean processStyle12(Style12Struct boardData){ Integer gameNumber = new Integer(boardData.getGameNumber()); InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNumber); GameInfoStruct unstartedGameInfo = (GameInfoStruct)unstartedGamesData.remove(gameNumber); if (unstartedGameInfo != null) // A new game gameData = startGame(unstartedGameInfo, boardData); else if (gameData != null){ // A known game Style12Struct oldBoardData = gameData.boardData; int plyDifference = boardData.getPlayedPlyCount() - oldBoardData.getPlayedPlyCount(); if (plyDifference < 0) tryIssueTakeback(gameData, boardData); else if (plyDifference == 0){ if (!oldBoardData.getBoardFEN().equals(boardData.getBoardFEN())) changePosition(gameData, boardData); // This happens if you: // 1. Issue "refresh". // 2. Make an illegal move, because the server will re-send us the board // (although we don't need it) // 3. Issue board setup commands. // 4. Use "wname" or "bname" to change the names of the white or black // players. } else if (plyDifference == 1){ if (boardData.getMoveVerbose() != null) makeMove(gameData, boardData); else changePosition(gameData, boardData); // This shouldn't happen, but I'll leave it just in case } else if (plyDifference > 1){ changePosition(gameData, boardData); // This happens if you: // 1. Issue "forward" with an argument of 2 or bigger. } } else if (!unsupportedGames.contains(gameNumber)){ // Grr, the server started a game without sending us a GameInfo line. // Currently happens if you start examining a game (26.08.2002), or // doing "refresh <game>" (04.07.2004). //TODO: Implement getting info for starting examined game this.waiting = true; askForMoreGameInfo(boardData.getGameNumber(), boardData); // We have no choice but to fake the data, since the server simply doesn't // send us this information. } if (gameData != null) updateGame(gameData, boardData); return true; } /** * Method that process info about examined game. * @param gameNr * @param gameCategory * @return */ protected boolean processExaminedGameInfo(int gameNr, String gameCategory) { Style12Struct boardData = this.examinedGameBoardData; InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNr); if (this.examinedGameId == gameNr){ String[] category = parseExaminedGameCategory(gameCategory); System.out.println("CATEGORY STRING = " + category[0]); this.examinedGameVariant = category[0]; if (category[1].equals("rated")){ this.isExaminedRated = true; }else{ this.isExaminedRated = false; } System.out.println("RATED? = " + this.isExaminedRated); System.out.println("THIRD IN CATEGORY = " + category[2]); if (category[2].length() != 0){ this.isExaminedPrivate = true; } GameInfoStruct fakeGameInfo = new GameInfoStruct(boardData.getGameNumber(), this.isExaminedPrivate, this.examinedGameVariant, this.isExaminedRated, false, false, boardData.getInitialTime(), boardData.getIncrement(), boardData.getInitialTime(), boardData.getIncrement(), 0, -1, ' ', -1, ' ', false, false); gameData = startGame(fakeGameInfo, boardData); if (gameData != null){ updateGame(gameData, boardData); } this.waiting = false; } return false; } /** * Method that parses through category string of examined game. * @param s * @return array of strings that is further processed */ private String[] parseExaminedGameCategory(String s) { String[] categories = new String[3]; switch(s.charAt(s.length()-1)){ case 'r': categories[1] = "rated"; break; case 'u': categories[1] = "unrated"; break; } switch(s.charAt(s.length()-2)){ case 's': categories[0] = "standard"; break; case 'b': categories[0] = "blitz"; break; case 'l': categories[0] = "lightning"; break; case 'w': categories[0] = "wild"; break; case 'x': categories[0] = "atomic"; break; case 'B': categories[0] = "bughouse"; break; case 'z': categories[0] = "crazyhouse"; break; case 'L': categories[0] = "losers"; break; case 'S': categories[0] = "suicide"; break; case 'n': categories[0] = "nonstandard"; break; default: categories[0] = "unknown"; } if (s.length()>2){ categories[2] = "private"; }else { categories[2] = ""; } return categories; } /** * Method that sends to server question for more info about game with specified number. */ private void askForMoreGameInfo(int gameNumber, Style12Struct boardData) { this.examinedGameId = gameNumber; this.examinedGameBoardData = boardData; this.sendCommFromPlugin("games " + String.valueOf(gameNumber)); } /** * Processes a delta-board. Instead of actually handing the delta-board, this * method, instead, creates a Style12Struct object and then asks * <code>processStyle12</code> to handle it. */ protected boolean processDeltaBoard(DeltaBoardStruct data){ Integer gameNumber = new Integer(data.getGameNumber()); InternalGameData gameData = (InternalGameData)ongoingGamesData.get(gameNumber); Game game = gameData.game; if (game.getVariant() != Chess.getInstance()) throw new IllegalStateException("delta-boards should only be sent for regular chess"); Style12Struct lastBoardData = gameData.boardData; ArrayList moveList = gameData.moveList; Position pos = game.getInitialPosition(); for (int i = 0; i < moveList.size(); i++) pos.makeMove((Move)moveList.get(i)); ChessMove move = (ChessMove)(Move.parseWarrenSmith(data.getMoveSmith(), pos, data.getMoveAlgebraic())); Square startSquare = move.getStartingSquare(); ChessPiece movingPiece = (ChessPiece)((startSquare == null) ? null : pos.getPieceAt(startSquare)); pos.makeMove(move); String boardLexigraphic = pos.getLexigraphic(); String currentPlayer = pos.getCurrentPlayer().isWhite() ? "W" : "B"; int doublePawnPushFile = move.getDoublePawnPushFile(); boolean kingMoved = movingPiece.isKing(); boolean canWhiteCastleKingside = lastBoardData.canWhiteCastleKingside() && !kingMoved && !Square.getInstance(7, 0).equals(startSquare); boolean canWhiteCastleQueenside = lastBoardData.canBlackCastleQueenside() && !kingMoved && !Square.getInstance(0, 0).equals(startSquare); boolean canBlackCastleKingside = lastBoardData.canBlackCastleKingside() && !kingMoved && !Square.getInstance(7, 7).equals(startSquare); boolean canBlackCastleQueenside = lastBoardData.canBlackCastleQueenside() && !kingMoved && !Square.getInstance(0, 7).equals(startSquare); boolean isIrreversibleMove = movingPiece.isPawn() || move.isCapture() || (canWhiteCastleKingside != lastBoardData.canWhiteCastleKingside()) || (canWhiteCastleQueenside != lastBoardData.canWhiteCastleQueenside()) || (canBlackCastleKingside != lastBoardData.canBlackCastleKingside()) || (canBlackCastleQueenside != lastBoardData.canBlackCastleQueenside()); int pliesSinceIrreversible = isIrreversibleMove ? 0 : lastBoardData.getPliesSinceIrreversible() + 1; String whiteName = lastBoardData.getWhiteName(); String blackName = lastBoardData.getBlackName(); int gameType = lastBoardData.getGameType(); boolean isPlayedGame = lastBoardData.isPlayedGame(); boolean isMyTurn = pos.getCurrentPlayer() == game.getUserPlayer(); int initTime = lastBoardData.getInitialTime(); int inc = lastBoardData.getIncrement(); int whiteStrength = calcStrength(pos, Player.WHITE_PLAYER); int blackStrength = calcStrength(pos, Player.BLACK_PLAYER); int whiteTime = pos.getCurrentPlayer().isBlack() ? data.getRemainingTime() : lastBoardData.getWhiteTime(); int blackTime = pos.getCurrentPlayer().isWhite() ? data.getRemainingTime() : lastBoardData.getBlackTime(); int nextMoveNumber = lastBoardData.getNextMoveNumber() + (pos.getCurrentPlayer().isWhite() ? 1 : 0); String moveVerbose = createVerboseMove(pos, move); String moveSAN = data.getMoveAlgebraic(); int moveTime = data.getTakenTime(); boolean isBoardFlipped = lastBoardData.isBoardFlipped(); boolean isClockRunning = true; int lag = 0; // The server doesn't currently send us this information Style12Struct boardData = new Style12Struct(boardLexigraphic, currentPlayer, doublePawnPushFile, canWhiteCastleKingside, canWhiteCastleQueenside, canBlackCastleKingside, canBlackCastleQueenside, pliesSinceIrreversible, gameNumber.intValue(), whiteName, blackName, gameType, isPlayedGame, isMyTurn, initTime, inc, whiteStrength, blackStrength, whiteTime, blackTime, nextMoveNumber, moveVerbose, moveSAN, moveTime, isBoardFlipped, isClockRunning, lag); processStyle12(boardData); return true; } /** * Calculates the material strength of the specified player in the specified * position. */ private static int calcStrength(Position pos, Player player){ int count = 0; for (int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++){ ChessPiece piece = (ChessPiece)(pos.getPieceAt(i, j)); if ((piece != null) && (piece.getPlayer() == player)){ if (piece.isPawn()) count += 1; else if (piece.isBishop()) count += 3; else if (piece.isKnight()) count += 3; else if (piece.isRook()) count += 5; else if (piece.isQueen()) count += 9; else if (piece.isKing()) count += 0; } } } return count; } /** * Creates a verbose representation of the specified move in the specified * position. The move has already been made in the position. */ private static String createVerboseMove(Position pos, ChessMove move){ if (move.isShortCastling()) return "o-o"; else if (move.isLongCastling()) return "o-o-o"; else{ ChessPiece piece = (ChessPiece)pos.getPieceAt(move.getEndingSquare()); String moveVerbose = piece.toShortString() + '/' + move.getStartingSquare() + '-' + move.getEndingSquare(); if (move.isPromotion()) return moveVerbose + '=' + move.getPromotionTarget().toShortString(); else return moveVerbose; } } /** * Changes the bsetup state of the game. */ protected boolean processBSetupMode(boolean entered){ try{ findMyGame().isBSetup = entered; } catch (NoSuchGameException e){} return super.processBSetupMode(entered); } /** * Sends command to server saying to clear messages from messageFromNumber to * messageToNumber. If both numbers are set to zeros then all messages are cleared. * If you pass invalid values to this method's params it will do nothing. * @param messageFromNumber - message to start from * @param messageToNumber - message to end with */ public void clearMessage(int messageFromNumber, int messageToNumber) { if (messageFromNumber == 0 && messageToNumber == 0 ){ sendCommand("clearmessages *"); return; } else if (messageFromNumber == messageToNumber){ sendCommand("clearmessages " + String.valueOf(messageToNumber)); return; } else if (messageFromNumber < messageToNumber){ sendCommand("clearmessages " + String.valueOf(messageFromNumber) + "-" + String.valueOf(messageToNumber)); return; } else{return;} } /** * Sends command to server for getting messages from messageFromNumber to * messageToNumber. If both numbers are set to zeros then this method calls for all * messages from server. * @param messageFromNumber - message number to start from * @param messageToNumber - message number to end with */ public void getMessages(int messageFromNumber, int messageToNumber) { if (messageFromNumber == 0 && messageToNumber == 0){ sendCommand("messages"); return; } else if (messageFromNumber == messageToNumber){ sendCommand("messages " + String.valueOf(messageToNumber)); return; } else if (messageFromNumber < messageToNumber){ sendCommand("messages " + String.valueOf(messageFromNumber) + "-" + String.valueOf(messageToNumber)); return; } else{return;} } /** * A small class for keeping internal data about a game. */ private static class InternalGameData{ /** * The Game object representing the game. */ public final Game game; /** * A list of Moves done in the game. */ public ArrayList moveList = new ArrayList(); /** * The last Style12Struct we got for this game. */ public Style12Struct boardData = null; /** * Is this game in bsetup mode? */ public boolean isBSetup = false; /** * Maps offer indices to offers. Offers are Pairs where the first element * is the <code>Player</code> who made the offer and the 2nd is the offer * id. Takeback offers are kept separately. */ public final HashMap indicesToOffers = new HashMap(); /** * Maps takeback offer indices to takeback offers. Takeback offers are Pairs * where the first element is the <code>Player</code> who made the offer * and the 2nd is an <code>Integer</code> specifying the amount of plies * offered to take back. */ public final HashMap indicesToTakebackOffers = new HashMap(); /** * Works as a set of the offers currently in this game. The elements are * Pairs in which the first item is the <code>Player</code> who made the * offer and the second one is the offer id. Takeback offers are kept * separately. */ private final HashMap offers = new HashMap(); /** * The number of plies the white player offerred to takeback. */ private int whiteTakeback; /** * The number of plies the black player offerred to takeback. */ private int blackTakeback; /** * Creates a new InternalGameData. */ public InternalGameData(Game game){ this.game = game; } /** * Returns the amount of moves made in the game (as far as we counted). */ public int getMoveCount(){ return moveList.size(); } /** * Adds the specified move to the moves list. */ public void addMove(Move move){ moveList.add(move); } /** * Removes the last <code>count</code> moves from the movelist, if possible. * Otherwise, throws an <code>IllegalArgumentException</code>. */ public void removeLastMoves(int count){ if (count > moveList.size()) throw new IllegalArgumentException("Can't remove more elements than there are elements"); int first = moveList.size() - 1; int last = moveList.size() - count; for (int i = first; i >= last; i--) moveList.remove(i); } /** * Removes all the moves made in the game. */ public void clearMoves(){ moveList.clear(); } /** * Returns true if the specified offer is currently made by the specified * player in this game. */ public boolean isOffered(int offerId, Player player){ return offers.containsKey(new Pair(player, new Integer(offerId))); } /** * Sets the state of the specified offer in the game. Takeback offers are * handled by the setTakebackCount method. */ public void setOffer(int offerId, Player player, boolean isMade){ Pair offer = new Pair(player, new Integer(offerId)); if (isMade) offers.put(offer, offer); else offers.remove(offer); } /** * Sets the takeback offer in the game to the specified amount of plies. */ public void setTakebackOffer(Player player, int plies){ if (player.isWhite()) whiteTakeback = plies; else blackTakeback = plies; } /** * Returns the amount of plies offered to take back by the specified player. */ public int getTakebackOffer(Player player){ if (player.isWhite()) return whiteTakeback; else return blackTakeback; } } /** * Changes the primary played game. */ protected boolean processSimulCurrentBoardChanged(int gameNumber, String oppName){ primaryPlayedGame = gameNumber; return true; } /** * Changes the primary observed game. */ protected boolean processPrimaryGameChanged(int gameNumber){ primaryObservedGame = gameNumber; return true; } /** * Method that processes information about available pieces for players in Bughouse game. * Eventually it fire apopriate BughouseEvent * @param gameNumber * @param whiteAvailablePieces * @param blackAvailablePieces * @return */ protected boolean processBughouseHoldings(int gameNumber, String whiteAvailablePieces, String blackAvailablePieces) { //System.out.println(">>>BUGHOUSE event occured with data: " + gameNumber + whiteAvailablePieces + blackAvailablePieces); listenerManager.fireBughouseEvent(new BughouseEvent(this, gameNumber, whiteAvailablePieces, blackAvailablePieces)); return true; } /** * Invokes <code>closeGame(int)</code>. */ //TODO review and make it smarter. Involves changing Game and GameEvent (Not sure // about that. protected boolean processGameEnd(int gameNumber, String whiteName, String blackName, String reason, String result){ int resultCode; if ("1-0".equals(result)) resultCode = Game.WHITE_WINS; else if ("0-1".equals(result)) resultCode = Game.BLACK_WINS; else if ("1/2-1/2".equals(result)) resultCode = Game.DRAW; else resultCode = Game.UNKNOWN_RESULT; closeGame(gameNumber, resultCode); return false; } /** * Invokes <code>closeGame(int)</code>. */ protected boolean processStoppedObserving(int gameNumber){ closeGame(gameNumber, Game.UNKNOWN_RESULT); return false; } /** * Invokes <code>closeGame(int)</code>. */ protected boolean processStoppedExamining(int gameNumber){ closeGame(gameNumber, Game.UNKNOWN_RESULT); return false; } /** * Invokes <code>illegalMoveAttempted</code>. */ protected boolean processIllegalMove(String moveString, String reason){ illegalMoveAttempted(moveString); return false; } /** * Called when a new game is starting. Responsible for creating the game on * the client side and firing appropriate events. Returns an InternalGameData * instance for the newly created Game. */ private InternalGameData startGame(GameInfoStruct gameInfo, Style12Struct boardData){ String categoryName = gameInfo.getGameCategory(); WildVariant variant = getVariant(categoryName); if (variant == null){ String starsPad = TextUtilities.padStart("", '*', categoryName.length()+2); String spacePad = TextUtilities.padStart("", ' ', categoryName.length()+1) + '*'; processLine("********************************************************" + starsPad); processLine("* This version of Tonic does not support the wild variant " + categoryName + " *"); processLine("* and is thus unable to display the game. " + spacePad); processLine("* Please use the appropriate command to close the game. " + spacePad); processLine("********************************************************" + starsPad); unsupportedGames.add(new Integer(gameInfo.getGameNumber())); return null; } int gameType; switch (boardData.getGameType()){ case Style12Struct.MY_GAME: gameType = Game.MY_GAME; break; case Style12Struct.OBSERVED_GAME: gameType = Game.OBSERVED_GAME; break; case Style12Struct.ISOLATED_BOARD: gameType = Game.ISOLATED_BOARD; break; default: throw new IllegalArgumentException("Bad game type value: "+boardData.getGameType()); } Position initPos = new Position(variant); initPos.setFEN(boardData.getBoardFEN()); String whiteName = boardData.getWhiteName(); String blackName = boardData.getBlackName(); int whiteTime = 1000 * gameInfo.getWhiteTime(); int blackTime = 1000 * gameInfo.getBlackTime(); int whiteInc = 1000 * gameInfo.getWhiteInc(); int blackInc = 1000 * gameInfo.getBlackInc(); int whiteRating = gameInfo.isWhiteRegistered() ? -1 : gameInfo.getWhiteRating(); int blackRating = gameInfo.isBlackRegistered() ? -1 : gameInfo.getBlackRating(); String gameID = String.valueOf(gameInfo.getGameNumber()); boolean isRated = gameInfo.isGameRated(); boolean isPlayed = boardData.isPlayedGame(); String whiteTitles = ""; String blackTitles = ""; boolean initiallyFlipped = boardData.isBoardFlipped(); Player currentPlayer = playerForString(boardData.getCurrentPlayer()); Player userPlayer = null; if ((gameType == Game.MY_GAME) && isPlayed) userPlayer = boardData.isMyTurn() ? currentPlayer : currentPlayer.getOpponent(); Game game = new Game(gameType, initPos, boardData.getPlayedPlyCount(), whiteName, blackName, whiteTime, whiteInc, blackTime, blackInc, whiteRating, blackRating, gameID, categoryName, isRated, isPlayed, whiteTitles, blackTitles, initiallyFlipped, userPlayer); InternalGameData gameData = new InternalGameData(game); ongoingGamesData.put(new Integer(gameInfo.getGameNumber()), gameData); listenerManager.fireGameEvent(new GameStartEvent(this, game)); // The server doesn't send us seek remove lines during games, so we have // no choice but to remove *all* seeks during a game. The seeks are restored // when a game ends by setting seekinfo to 1 again. if (gameType == Game.MY_GAME) removeAllSeeks(); return gameData; } /** * Updates any game parameters that differ in the board data from the current * game data. */ private void updateGame(InternalGameData gameData, Style12Struct boardData){ Game game = gameData.game; Style12Struct oldBoardData = gameData.boardData; updateClocks(gameData, boardData); // Update the clocks // Flip board if ((oldBoardData != null) && (oldBoardData.isBoardFlipped() != boardData.isBoardFlipped())) flipBoard(gameData, boardData); game.setWhiteName(boardData.getWhiteName()); // Change white name game.setBlackName(boardData.getBlackName()); // Change black name game.setWhiteTime(1000 * boardData.getInitialTime()); // Change white's initial time game.setWhiteInc(1000 * boardData.getIncrement()); // Change white's increment game.setBlackTime(1000 * boardData.getInitialTime()); // Change black's initial time game.setBlackInc(1000 * boardData.getIncrement()); // Change black's increment gameData.boardData = boardData; } /** * Gets called when a move is made. Fires an appropriate MoveMadeEvent. */ private void makeMove(InternalGameData gameData, Style12Struct boardData){ Game game = gameData.game; Style12Struct oldBoardData = gameData.boardData; String moveVerbose = boardData.getMoveVerbose(); String moveSAN = boardData.getMoveSAN(); String currentPlayerName = boardData.getMovingPlayerName(); WildVariant variant = game.getVariant(); Position position = new Position(variant); position.setLexigraphic(oldBoardData.getBoardLexigraphic()); Player currentPlayer = playerForString(oldBoardData.getCurrentPlayer()); position.setCurrentPlayer(currentPlayer); Move move; Square fromSquare, toSquare; Piece promotionPiece = null; //TODO: Start implementing bughouse and crazyhouse support from here. Look at second else if. Piece dropPiece = null; if (moveVerbose.equals("o-o")) move = variant.createShortCastling(position); else if (moveVerbose.equals("o-o-o")) move = variant.createLongCastling(position); else if (moveVerbose.indexOf('@') != -1){ toSquare = Square.parseSquare(moveVerbose.substring(5,7)); String dropPieceString = String.valueOf(moveVerbose.charAt(0)); if (currentPlayer.isBlack()){ dropPieceString = dropPieceString.toLowerCase(); } dropPiece = variant.parsePiece(dropPieceString); move = variant.createMove(position, dropPiece,null, toSquare, promotionPiece, moveSAN); } else{ fromSquare = Square.parseSquare(moveVerbose.substring(2, 4)); toSquare = Square.parseSquare(moveVerbose.substring(5, 7)); int promotionCharIndex = moveVerbose.indexOf("=")+1; if (promotionCharIndex != 0){ String pieceString = moveVerbose.substring(promotionCharIndex, promotionCharIndex + 1); if (currentPlayer.isBlack()) // The server always sends upper case characters, even for black pieces. pieceString = pieceString.toLowerCase(); promotionPiece = variant.parsePiece(pieceString); } move = variant.createMove(position, fromSquare, toSquare, promotionPiece, moveSAN); } listenerManager.fireGameEvent(new MoveMadeEvent(this, game, move, true, currentPlayerName)); // (isNew == true) because FICS never sends the entire move history ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game); if ((unechoedGameMoves != null) && (unechoedGameMoves.size() != 0)){ // Looks like it's our move. Move madeMove = (Move)unechoedGameMoves.get(0); if (moveToString(game, move).equals(moveToString(game, madeMove))) // Same move. unechoedGameMoves.remove(0); } gameData.addMove(move); } /** * Fires an appropriate ClockAdjustmentEvent. */ private void updateClocks(InternalGameData gameData, Style12Struct boardData){ Game game = gameData.game; int whiteTime = boardData.getWhiteTime(); int blackTime = boardData.getBlackTime(); Player currentPlayer = playerForString(boardData.getCurrentPlayer()); // Don't make clocks run for an isolated position. boolean isIsolatedBoard = game.getGameType() == Game.ISOLATED_BOARD; boolean whiteRunning = (!isIsolatedBoard) && boardData.isClockRunning() && currentPlayer.isWhite(); boolean blackRunning = (!isIsolatedBoard) && boardData.isClockRunning() && currentPlayer.isBlack(); listenerManager.fireGameEvent(new ClockAdjustmentEvent(this, game, Player.WHITE_PLAYER, whiteTime, whiteRunning)); listenerManager.fireGameEvent(new ClockAdjustmentEvent(this, game, Player.BLACK_PLAYER, blackTime, blackRunning)); } /** * Fires an appropriate GameEndEvent. */ private void closeGame(int gameNumber, int result){ Integer gameID = new Integer(gameNumber); if (gameID.intValue() == primaryPlayedGame) primaryPlayedGame = -1; else if (gameID.intValue() == primaryObservedGame) primaryObservedGame = -1; InternalGameData gameData = (InternalGameData)ongoingGamesData.remove(gameID); if (gameData != null){ Game game = gameData.game; game.setResult(result); listenerManager.fireGameEvent(new GameEndEvent(this, game, result)); if ((game.getGameType() == Game.MY_GAME) && getIvarState(Ivar.SEEKINFO)) setIvarState(Ivar.SEEKINFO, true); // Refresh the seeks } else unsupportedGames.remove(gameID); } /** * Fires an appropriate BoardFlipEvent. */ private void flipBoard(InternalGameData gameData, Style12Struct newBoardData){ listenerManager.fireGameEvent(new BoardFlipEvent(this, gameData.game, newBoardData.isBoardFlipped())); } /** * Fires an appropriate IllegalMoveEvent. */ private void illegalMoveAttempted(String moveString){ try{ InternalGameData gameData = findMyGame(); Game game = gameData.game; ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game); // Not a move we made (probably the user typed it in) if ((unechoedGameMoves == null) || (unechoedGameMoves.size() == 0)) return; Move move = (Move)unechoedGameMoves.get(0); // We have no choice but to allow (moveString == null) because the server // doesn't always send us the move string (for example if it's not our turn). if ((moveString == null) || moveToString(game, move).equals(moveString)){ // Our move, probably unechoedGameMoves.clear(); listenerManager.fireGameEvent(new IllegalMoveEvent(this, game, move)); } } catch (NoSuchGameException e){} } /** * Determines whether it's possible to issue a takeback for the specified * game change and if so calls issueTakeback, otherwise calls changePosition. */ private void tryIssueTakeback(InternalGameData gameData, Style12Struct boardData){ Style12Struct oldBoardData = gameData.boardData; int plyDifference = oldBoardData.getPlayedPlyCount() - boardData.getPlayedPlyCount(); if ((gameData.getMoveCount() < plyDifference)) // Can't issue takeback changePosition(gameData, boardData); else if (gameData.isBSetup) changePosition(gameData, boardData); else{ Game game = gameData.game; ArrayList moveList = gameData.moveList; // Check whether the positions match, otherwise it could just be someone // issuing "bsetup fen ..." after making a few moves which resets the ply // count. Position oldPos = game.getInitialPosition(); for (int i = 0; i < moveList.size() - plyDifference; i++){ Move move = (Move)moveList.get(i); oldPos.makeMove(move); } Position newPos = game.getInitialPosition(); newPos.setFEN(boardData.getBoardFEN()); if (newPos.equals(oldPos)){ issueTakeback(gameData, boardData); }else if (gameData.game.getVariant() instanceof Bughouse){ issueTakeback(gameData, boardData); }else{ changePosition(gameData, boardData); } } } /** * Fires an appropriate TakebackEvent. */ private void issueTakeback(InternalGameData gameData, Style12Struct newBoardData){ Style12Struct oldBoardData = gameData.boardData; int takebackCount = oldBoardData.getPlayedPlyCount() - newBoardData.getPlayedPlyCount(); listenerManager.fireGameEvent(new TakebackEvent(this, gameData.game, takebackCount)); gameData.removeLastMoves(takebackCount); } /** * Fires an appropriate PositionChangedEvent. */ private void changePosition(InternalGameData gameData, Style12Struct newBoardData){ Game game = gameData.game; Position newPos = game.getInitialPosition(); newPos.setFEN(newBoardData.getBoardFEN()); game.setInitialPosition(newPos); game.setPliesSinceStart(newBoardData.getPlayedPlyCount()); listenerManager.fireGameEvent(new PositionChangedEvent(this, game, newPos)); gameData.clearMoves(); // We do this because moves in bsetup mode cause position change events, not move events if (gameData.isBSetup){ ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game); if ((unechoedGameMoves != null) && (unechoedGameMoves.size() != 0)) unechoedGameMoves.remove(0); } } /** * Maps seek IDs to Seek objects currently in the sought list. */ private final HashMap seeks = new HashMap(); /** * Returns the SeekListenerManager via which you can register and unregister * SeekListeners. */ public SeekListenerManager getSeekListenerManager(){ return getFreechessListenerManager(); } /** * Creates an appropriate Seek object and fires a SeekEvent. */ protected boolean processSeekAdded(SeekInfoStruct seekInfo){ // We may get seeks after setting seekinfo to false because the server // already sent them when we sent it the request to set seekInfo to false. if (getRequestedIvarState(Ivar.SEEKINFO)){ WildVariant variant = getVariant(seekInfo.getMatchType()); if (variant != null){ String seekID = String.valueOf(seekInfo.getSeekIndex()); StringBuffer titlesBuf = new StringBuffer(); int titles = seekInfo.getSeekerTitles(); if ((titles & SeekInfoStruct.COMPUTER) != 0) titlesBuf.append("(C)"); if ((titles & SeekInfoStruct.GM) != 0) titlesBuf.append("(GM)"); if ((titles & SeekInfoStruct.IM) != 0) titlesBuf.append("(IM)"); if ((titles & SeekInfoStruct.FM) != 0) titlesBuf.append("(FM)"); if ((titles & SeekInfoStruct.WGM) != 0) titlesBuf.append("(WGM)"); if ((titles & SeekInfoStruct.WIM) != 0) titlesBuf.append("(WIM)"); if ((titles & SeekInfoStruct.WFM) != 0) titlesBuf.append("(WFM)"); boolean isProvisional = (seekInfo.getSeekerProvShow() == 'P'); boolean isSeekerRated = (seekInfo.getSeekerRating() != 0); boolean isRegistered = ((seekInfo.getSeekerTitles() & SeekInfoStruct.UNREGISTERED) == 0); boolean isComputer = ((seekInfo.getSeekerTitles() & SeekInfoStruct.COMPUTER) != 0); Player color; switch (seekInfo.getSeekerColor()){ case 'W': color = Player.WHITE_PLAYER; break; case 'B': color = Player.BLACK_PLAYER; break; case '?': color = null; break; default: throw new IllegalStateException("Bad desired color char: "+seekInfo.getSeekerColor()); } boolean isRatingLimited = ((seekInfo.getOpponentMinRating() > 0) || (seekInfo.getOpponentMaxRating() < 9999)); Seek seek = new Seek(seekID, seekInfo.getSeekerHandle(), titlesBuf.toString(), seekInfo.getSeekerRating(), isProvisional, isRegistered, isSeekerRated, isComputer, variant, seekInfo.getMatchType(), seekInfo.getMatchTime()*60*1000, seekInfo.getMatchIncrement()*1000, seekInfo.isMatchRated(), color, isRatingLimited, seekInfo.getOpponentMinRating(), seekInfo.getOpponentMaxRating(), !seekInfo.isAutomaticAccept(), seekInfo.isFormulaUsed()); Integer seekIndex = new Integer(seekInfo.getSeekIndex()); Seek oldSeek = (Seek)seeks.get(seekIndex); if (oldSeek != null) listenerManager.fireSeekEvent(new SeekEvent(this, SeekEvent.SEEK_REMOVED, oldSeek)); seeks.put(seekIndex, seek); listenerManager.fireSeekEvent(new SeekEvent(this, SeekEvent.SEEK_ADDED, seek)); } } return true; } /** * Issues the appropriate SeekEvents and removes the seeks. */ protected boolean processSeeksRemoved(int [] removedSeeks){ for (int i = 0; i < removedSeeks.length; i++){ Integer seekIndex = new Integer(removedSeeks[i]); Seek seek = (Seek)seeks.get(seekIndex); if (seek == null) // Happens if the seek is one we didn't fire an event for, continue; // for example if we don't support the variant. listenerManager.fireSeekEvent(new SeekEvent(this, SeekEvent.SEEK_REMOVED, seek)); seeks.remove(seekIndex); } return true; } /** * Issues the appropriate SeeksEvents and removes the seeks. */ protected boolean processSeeksCleared(){ removeAllSeeks(); return true; } /** * Removes all the seeks and notifies the listeners. */ private void removeAllSeeks(){ int seeksCount = seeks.size(); if (seeksCount != 0){ Object [] seeksIndices = new Object[seeksCount]; // Copy all the keys into a temporary array Iterator seekIDsEnum = seeks.keySet().iterator(); for (int i = 0; i < seeksCount; i++) seeksIndices[i] = seekIDsEnum.next(); // Remove all the seeks one by one, notifying any interested listeners. for (int i = 0; i < seeksCount; i++){ Object seekIndex = seeksIndices[i]; Seek seek = (Seek)seeks.get(seekIndex); listenerManager.fireSeekEvent(new SeekEvent(this, SeekEvent.SEEK_REMOVED, seek)); seeks.remove(seekIndex); } } } /** * This method is called by our FreechessJinListenerManager when a new * SeekListener is added and we already had registered listeners (meaning that * iv_seekinfo was already on, so we need to notify the new listeners of all * existing seeks as well). */ void notFirstListenerAdded(SeekListener listener){ Iterator seeksEnum = seeks.values().iterator(); while (seeksEnum.hasNext()){ Seek seek = (Seek)seeksEnum.next(); SeekEvent evt = new SeekEvent(this, SeekEvent.SEEK_ADDED, seek); listener.seekAdded(evt); } } /** * This method is called by our ChessclubJinListenerManager when the last * SeekListener is removed. */ void lastSeekListenerRemoved(){ seeks.clear(); } /** * Maps offer indices to the <code>InternalGameData</code> objects * representing the games in which the offer was made. */ private final HashMap offerIndicesToGameData = new HashMap(); /** * Override processOffer to always return true, since we don't want the * user to ever see these messages. */ protected boolean processOffer(boolean toUser, String offerType, int offerIndex, String oppName, String offerParams){ super.processOffer(toUser, offerType, offerIndex, oppName, offerParams); return true; } /** * Overrides the superclass' method only to return true. */ protected boolean processMatchOffered(boolean toUser, int offerIndex, String oppName, String matchDetails){ super.processMatchOffered(toUser, offerIndex, oppName, matchDetails); return true; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processTakebackOffered(boolean toUser, int offerIndex, String oppName, int takebackCount){ super.processTakebackOffered(toUser, offerIndex, oppName, takebackCount); try{ InternalGameData gameData = findMyGameAgainst(oppName); Player userPlayer = gameData.game.getUserPlayer(); Player player = toUser ? userPlayer.getOpponent() : userPlayer; offerIndicesToGameData.put(new Integer(offerIndex), gameData); gameData.indicesToTakebackOffers.put(new Integer(offerIndex), new Pair(player, new Integer(takebackCount))); updateTakebackOffer(gameData, player, takebackCount); } catch (NoSuchGameException e){} return true; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processDrawOffered(boolean toUser, int offerIndex, String oppName){ super.processDrawOffered(toUser, offerIndex, oppName); processOffered(toUser, offerIndex, oppName, OfferEvent.DRAW_OFFER); return true; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processAbortOffered(boolean toUser, int offerIndex, String oppName){ super.processAbortOffered(toUser, offerIndex, oppName); processOffered(toUser, offerIndex, oppName, OfferEvent.ABORT_OFFER); return true; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processAdjournOffered(boolean toUser, int offerIndex, String oppName){ super.processAdjournOffered(toUser, offerIndex, oppName); processOffered(toUser, offerIndex, oppName, OfferEvent.ADJOURN_OFFER); return true; } /** * Gets called by the various process[offerType]Offered() methods to handle * the offers uniformly. */ private void processOffered(boolean toUser, int offerIndex, String oppName, int offerId){ try{ InternalGameData gameData = findMyGameAgainst(oppName); Player userPlayer = gameData.game.getUserPlayer(); Player player = toUser ? userPlayer.getOpponent() : userPlayer; offerIndicesToGameData.put(new Integer(offerIndex), gameData); gameData.indicesToOffers.put(new Integer(offerIndex), new Pair(player, new Integer(offerId))); updateOffers(gameData, offerId, player, true); } catch (NoSuchGameException e){} } /** * Fires the appropriate OfferEvent(s). */ protected boolean processOfferRemoved(int offerIndex){ super.processOfferRemoved(offerIndex); InternalGameData gameData = (InternalGameData)offerIndicesToGameData.remove(new Integer(offerIndex)); if (gameData != null){ // Check regular offers Pair offer = (Pair)gameData.indicesToOffers.remove(new Integer(offerIndex)); if (offer != null){ Player player = (Player)offer.getFirst(); int offerId = ((Integer)offer.getSecond()).intValue(); updateOffers(gameData, offerId, player, false); } else{ // Check takeback offers offer = (Pair)gameData.indicesToTakebackOffers.remove(new Integer(offerIndex)); if (offer != null){ Player player = (Player)offer.getFirst(); updateTakebackOffer(gameData, player, 0); } } } return true; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processPlayerCounteredTakebackOffer(int gameNum, String playerName, int takebackCount){ super.processPlayerCounteredTakebackOffer(gameNum, playerName, takebackCount); try{ InternalGameData gameData = getGameData(gameNum); Player player = gameData.game.getPlayerNamed(playerName); updateTakebackOffer(gameData, player.getOpponent(), 0); updateTakebackOffer(gameData, player, takebackCount); } catch (NoSuchGameException e){} return false; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processPlayerOffered(int gameNum, String playerName, String offerName){ super.processPlayerOffered(gameNum, playerName, offerName); try{ InternalGameData gameData = getGameData(gameNum); Player player = gameData.game.getPlayerNamed(playerName); int offerId; try{ offerId = offerIdForOfferName(offerName); updateOffers(gameData, offerId, player, true); } catch (IllegalArgumentException e){} } catch (NoSuchGameException e){} return false; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processPlayerDeclined(int gameNum, String playerName, String offerName){ super.processPlayerDeclined(gameNum, playerName, offerName); try{ InternalGameData gameData = getGameData(gameNum); Player player = gameData.game.getPlayerNamed(playerName); int offerId; try{ offerId = offerIdForOfferName(offerName); updateOffers(gameData, offerId, player.getOpponent(), false); } catch (IllegalArgumentException e){} } catch (NoSuchGameException e){} return false; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processPlayerWithdrew(int gameNum, String playerName, String offerName){ super.processPlayerWithdrew(gameNum, playerName, offerName); try{ InternalGameData gameData = getGameData(gameNum); Player player = gameData.game.getPlayerNamed(playerName); int offerId; try{ offerId = offerIdForOfferName(offerName); updateOffers(gameData, offerId, player, false); } catch (IllegalArgumentException e){} } catch (NoSuchGameException e){} return false; } /** * Fires the appropriate OfferEvent(s). */ protected boolean processPlayerOfferedTakeback(int gameNum, String playerName, int takebackCount){ super.processPlayerOfferedTakeback(gameNum, playerName, takebackCount); try{ InternalGameData gameData = getGameData(gameNum); Player player = gameData.game.getPlayerNamed(playerName); updateTakebackOffer(gameData, player, takebackCount); } catch (NoSuchGameException e){} return false; } /** * Returns the offerId (as defined by OfferEvent) corresponding to the * specified offer name. Throws an IllegalArgumentException if the offer name * is not recognizes. */ private static int offerIdForOfferName(String offerName) throws IllegalArgumentException{ if ("draw".equals(offerName)) return OfferEvent.DRAW_OFFER; else if ("abort".equals(offerName)) return OfferEvent.ABORT_OFFER; else if ("adjourn".equals(offerName)) return OfferEvent.ADJOURN_OFFER; else if ("takeback".equals(offerName)) return OfferEvent.TAKEBACK_OFFER; else throw new IllegalArgumentException("Unknown offer name: "+offerName); } /** * Updates the specified offer, firing any necessary events. */ private void updateOffers(InternalGameData gameData, int offerId, Player player, boolean on){ Game game = gameData.game; if (offerId == OfferEvent.TAKEBACK_OFFER){ // We're forced to fake this so that an event is fired even if we start observing a game // with an existing takeback offer (of which we're not aware). if ((!on) && (gameData.getTakebackOffer(player) == 0)) gameData.setTakebackOffer(player, 1); updateTakebackOffer(gameData, player.getOpponent(), 0); // Remove any existing offers updateTakebackOffer(gameData, player, on ? 1 : 0); // 1 as the server doesn't tell us how many } else{// if (gameData.isOffered(offerId, player) != on){ this // We check this because we might get such an event if we start observing a game with // an existing offer. gameData.setOffer(offerId, player, on); listenerManager.fireGameEvent(new OfferEvent(this, game, offerId, on, player)); } } /** * Updates the takeback offer in the specified game to the specified amount of * plies. */ private void updateTakebackOffer(InternalGameData gameData, Player player, int takebackCount){ Game game = gameData.game; int oldTakeback = gameData.getTakebackOffer(player); if (oldTakeback != 0) listenerManager.fireGameEvent(new OfferEvent(this, game, false, player, oldTakeback)); gameData.setTakebackOffer(player, takebackCount); if (takebackCount != 0) listenerManager.fireGameEvent(new OfferEvent(this, game, true, player, takebackCount)); } /** * Accepts the given seek. Note that the given seek must be an instance generated * by this SeekJinConnection and it must be in the current sought list. */ public void acceptSeek(Seek seek){ if (!seeks.containsValue(seek)) throw new IllegalArgumentException("The specified seek is not on the seek list"); sendCommand("$play "+seek.getID()); } /** * Issues the specified seek. */ public void issueSeek(UserSeek seek){ WildVariant variant = seek.getVariant(); String wildName = getWildName(variant); if (wildName == null) throw new IllegalArgumentException("Unsupported variant: " + variant); Player color = seek.getColor(); String seekCommand = "seek " + seek.getTime() + ' ' + seek.getInc() + ' ' + (seek.isRated() ? "rated" : "unrated") + ' ' + (color == null ? "" : color.isWhite() ? "white " : "black ") + wildName + ' ' + (seek.isManualAccept() ? "manual " : "") + (seek.isFormula() ? "formula " : "") + (seek.getMinRating() == Integer.MIN_VALUE ? "0" : String.valueOf(seek.getMinRating())) + '-' + (seek.getMaxRating() == Integer.MAX_VALUE ? "9999" : String.valueOf(seek.getMaxRating())) + ' '; sendCommand(seekCommand); } /** * Sends the "exit" command to the server. */ public void exit(){ sendCommand("$quit"); } /** * Quits the specified game. */ public void quitGame(Game game){ Object id = game.getID(); switch (game.getGameType()){ case Game.MY_GAME: if (game.isPlayed()) sendCommand("$resign"); else sendCommand("$unexamine"); break; case Game.OBSERVED_GAME: sendCommand("$unobserve "+id); break; case Game.ISOLATED_BOARD: break; } } /** * Makes the given move in the given game. */ public void makeMove(Game game, Move move){ - Iterator gamesDataEnum = ongoingGamesData.keySet().iterator(); + Iterator gamesDataEnum = ongoingGamesData.values().iterator(); boolean ourGame = false; while (gamesDataEnum.hasNext()){ InternalGameData gameData = (InternalGameData)gamesDataEnum.next(); if (gameData.game == game){ ourGame = true; break; } } if (!ourGame) throw new IllegalArgumentException("The specified Game object was not created by this JinConnection or the game has ended."); sendCommand(moveToString(game, move)); ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game); if (unechoedGameMoves == null){ unechoedGameMoves = new ArrayList(2); unechoedMoves.put(game, unechoedGameMoves); } unechoedGameMoves.add(move); } /** * Converts the given move into a string we can send to the server. */ private static String moveToString(Game game, Move move){ WildVariant variant = game.getVariant(); if (move instanceof ChessMove){ ChessMove cmove = (ChessMove)move; if (cmove.isShortCastling()) return "O-O"; else if (cmove.isLongCastling()) return "O-O-O"; String s = cmove.getStartingSquare().toString() + cmove.getEndingSquare().toString(); if (cmove.isPromotion()) return s + '=' + variant.pieceToString(cmove.getPromotionTarget()); else return s; } else throw new IllegalArgumentException("Unsupported Move type: "+move.getClass()); } /** * Resigns the given game. The given game must be a played game and of type * Game.MY_GAME. */ public void resign(Game game){ checkGameMineAndPlayed(game); sendCommand("$resign"); } /** * Sends a request to draw the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestDraw(Game game){ checkGameMineAndPlayed(game); sendCommand("$draw"); } /** * Returns <code>true</code>. */ public boolean isAbortSupported(){ return true; } /** * Sends a request to abort the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestAbort(Game game){ checkGameMineAndPlayed(game); sendCommand("$abort"); } /** * Returns <code>true</code>. */ public boolean isAdjournSupported(){ return true; } /** * Sends a request to adjourn the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestAdjourn(Game game){ checkGameMineAndPlayed(game); sendCommand("$adjourn"); } /** * Returns <code>true</code>. */ public boolean isTakebackSupported(){ return true; } /** * Sends "takeback 1" to the server. */ public void requestTakeback(Game game){ checkGameMineAndPlayed(game); sendCommand("$takeback 1"); } /** * Returns <code>true</code>. */ public boolean isMultipleTakebackSupported(){ return true; } /** * Sends "takeback plyCount" to the server. */ public void requestTakeback(Game game, int plyCount){ checkGameMineAndPlayed(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$takeback " + plyCount); } /** * Goes back the given amount of plies in the given game. If the given amount * of plies is bigger than the amount of plies since the beginning of the game, * goes to the beginning of the game. */ public void goBackward(Game game, int plyCount){ checkGameMineAndExamined(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$backward " + plyCount); } /** * Goes forward the given amount of plies in the given game. If the given amount * of plies is bigger than the amount of plies remaining until the end of the * game, goes to the end of the game. */ public void goForward(Game game, int plyCount){ checkGameMineAndExamined(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$forward " + plyCount); } /** * Goes to the beginning of the given game. */ public void goToBeginning(Game game){ checkGameMineAndExamined(game); sendCommand("$backward 999"); } /** * Goes to the end of the given game. */ public void goToEnd(Game game){ checkGameMineAndExamined(game); sendCommand("$forward 999"); } /** * Throws an IllegalArgumentException if the given Game is not of type * Game.MY_GAME or is not a played game. Otherwise, simply returns. */ private void checkGameMineAndPlayed(Game game){ if ((game.getGameType() != Game.MY_GAME) || (!game.isPlayed())) throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and a played one"); } /** * Throws an IllegalArgumentException if the given Game is not of type * Game.MY_GAME or is a played game. Otherwise, simply returns. */ private void checkGameMineAndExamined(Game game){ if ((game.getGameType() != Game.MY_GAME)||game.isPlayed()) throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and an examined one"); } /** * Sends the "help" command to the server. */ public void showServerHelp(){ sendCommand("help"); } /** * Sends the specified question string to channel 1. */ public void sendHelpQuestion(String question){ sendCommand("tell 1 [" + Jin.getInstance().getAppName() + ' ' + Jin.getInstance().getAppVersion() + "] "+ question); } /** * Overrides ChessclubConnection.execRunnable(Runnable) to execute the * runnable on the AWT thread using SwingUtilities.invokeLater(Runnable), * since this class is meant to be used by Jin, a graphical interface using * Swing. * * @see ChessclubConnection#execRunnable(Runnable) * @see SwingUtilities.invokeLater(Runnable) */ public void execRunnable(Runnable runnable){ SwingUtilities.invokeLater(runnable); } /** * Method called to get user's channel list from server. */ public void updateChannelsList() { sendCommand("inch " + this.getUsername()); } /** * Method called to remove channel from user's channel list. * * @param channelNumber - the number of removed channel. */ public void removeChannel(int channelNumber) { sendCommand("-channel " + channelNumber); } /** * Method called to add channel to user's channel list. * * @param channelNumber - the number of added channel. */ public void addChannel(int channelNumber) { sendCommand("+channel " + channelNumber); } /** * Returns ListenerManager that lets us register listeners */ public ChannelsListenerManager getChannelsListenerManager() { return getFreechessListenerManager(); } }
true
true
private void updateOffers(InternalGameData gameData, int offerId, Player player, boolean on){ Game game = gameData.game; if (offerId == OfferEvent.TAKEBACK_OFFER){ // We're forced to fake this so that an event is fired even if we start observing a game // with an existing takeback offer (of which we're not aware). if ((!on) && (gameData.getTakebackOffer(player) == 0)) gameData.setTakebackOffer(player, 1); updateTakebackOffer(gameData, player.getOpponent(), 0); // Remove any existing offers updateTakebackOffer(gameData, player, on ? 1 : 0); // 1 as the server doesn't tell us how many } else{// if (gameData.isOffered(offerId, player) != on){ this // We check this because we might get such an event if we start observing a game with // an existing offer. gameData.setOffer(offerId, player, on); listenerManager.fireGameEvent(new OfferEvent(this, game, offerId, on, player)); } } /** * Updates the takeback offer in the specified game to the specified amount of * plies. */ private void updateTakebackOffer(InternalGameData gameData, Player player, int takebackCount){ Game game = gameData.game; int oldTakeback = gameData.getTakebackOffer(player); if (oldTakeback != 0) listenerManager.fireGameEvent(new OfferEvent(this, game, false, player, oldTakeback)); gameData.setTakebackOffer(player, takebackCount); if (takebackCount != 0) listenerManager.fireGameEvent(new OfferEvent(this, game, true, player, takebackCount)); } /** * Accepts the given seek. Note that the given seek must be an instance generated * by this SeekJinConnection and it must be in the current sought list. */ public void acceptSeek(Seek seek){ if (!seeks.containsValue(seek)) throw new IllegalArgumentException("The specified seek is not on the seek list"); sendCommand("$play "+seek.getID()); } /** * Issues the specified seek. */ public void issueSeek(UserSeek seek){ WildVariant variant = seek.getVariant(); String wildName = getWildName(variant); if (wildName == null) throw new IllegalArgumentException("Unsupported variant: " + variant); Player color = seek.getColor(); String seekCommand = "seek " + seek.getTime() + ' ' + seek.getInc() + ' ' + (seek.isRated() ? "rated" : "unrated") + ' ' + (color == null ? "" : color.isWhite() ? "white " : "black ") + wildName + ' ' + (seek.isManualAccept() ? "manual " : "") + (seek.isFormula() ? "formula " : "") + (seek.getMinRating() == Integer.MIN_VALUE ? "0" : String.valueOf(seek.getMinRating())) + '-' + (seek.getMaxRating() == Integer.MAX_VALUE ? "9999" : String.valueOf(seek.getMaxRating())) + ' '; sendCommand(seekCommand); } /** * Sends the "exit" command to the server. */ public void exit(){ sendCommand("$quit"); } /** * Quits the specified game. */ public void quitGame(Game game){ Object id = game.getID(); switch (game.getGameType()){ case Game.MY_GAME: if (game.isPlayed()) sendCommand("$resign"); else sendCommand("$unexamine"); break; case Game.OBSERVED_GAME: sendCommand("$unobserve "+id); break; case Game.ISOLATED_BOARD: break; } } /** * Makes the given move in the given game. */ public void makeMove(Game game, Move move){ Iterator gamesDataEnum = ongoingGamesData.keySet().iterator(); boolean ourGame = false; while (gamesDataEnum.hasNext()){ InternalGameData gameData = (InternalGameData)gamesDataEnum.next(); if (gameData.game == game){ ourGame = true; break; } } if (!ourGame) throw new IllegalArgumentException("The specified Game object was not created by this JinConnection or the game has ended."); sendCommand(moveToString(game, move)); ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game); if (unechoedGameMoves == null){ unechoedGameMoves = new ArrayList(2); unechoedMoves.put(game, unechoedGameMoves); } unechoedGameMoves.add(move); } /** * Converts the given move into a string we can send to the server. */ private static String moveToString(Game game, Move move){ WildVariant variant = game.getVariant(); if (move instanceof ChessMove){ ChessMove cmove = (ChessMove)move; if (cmove.isShortCastling()) return "O-O"; else if (cmove.isLongCastling()) return "O-O-O"; String s = cmove.getStartingSquare().toString() + cmove.getEndingSquare().toString(); if (cmove.isPromotion()) return s + '=' + variant.pieceToString(cmove.getPromotionTarget()); else return s; } else throw new IllegalArgumentException("Unsupported Move type: "+move.getClass()); } /** * Resigns the given game. The given game must be a played game and of type * Game.MY_GAME. */ public void resign(Game game){ checkGameMineAndPlayed(game); sendCommand("$resign"); } /** * Sends a request to draw the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestDraw(Game game){ checkGameMineAndPlayed(game); sendCommand("$draw"); } /** * Returns <code>true</code>. */ public boolean isAbortSupported(){ return true; } /** * Sends a request to abort the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestAbort(Game game){ checkGameMineAndPlayed(game); sendCommand("$abort"); } /** * Returns <code>true</code>. */ public boolean isAdjournSupported(){ return true; } /** * Sends a request to adjourn the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestAdjourn(Game game){ checkGameMineAndPlayed(game); sendCommand("$adjourn"); } /** * Returns <code>true</code>. */ public boolean isTakebackSupported(){ return true; } /** * Sends "takeback 1" to the server. */ public void requestTakeback(Game game){ checkGameMineAndPlayed(game); sendCommand("$takeback 1"); } /** * Returns <code>true</code>. */ public boolean isMultipleTakebackSupported(){ return true; } /** * Sends "takeback plyCount" to the server. */ public void requestTakeback(Game game, int plyCount){ checkGameMineAndPlayed(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$takeback " + plyCount); } /** * Goes back the given amount of plies in the given game. If the given amount * of plies is bigger than the amount of plies since the beginning of the game, * goes to the beginning of the game. */ public void goBackward(Game game, int plyCount){ checkGameMineAndExamined(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$backward " + plyCount); } /** * Goes forward the given amount of plies in the given game. If the given amount * of plies is bigger than the amount of plies remaining until the end of the * game, goes to the end of the game. */ public void goForward(Game game, int plyCount){ checkGameMineAndExamined(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$forward " + plyCount); } /** * Goes to the beginning of the given game. */ public void goToBeginning(Game game){ checkGameMineAndExamined(game); sendCommand("$backward 999"); } /** * Goes to the end of the given game. */ public void goToEnd(Game game){ checkGameMineAndExamined(game); sendCommand("$forward 999"); } /** * Throws an IllegalArgumentException if the given Game is not of type * Game.MY_GAME or is not a played game. Otherwise, simply returns. */ private void checkGameMineAndPlayed(Game game){ if ((game.getGameType() != Game.MY_GAME) || (!game.isPlayed())) throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and a played one"); } /** * Throws an IllegalArgumentException if the given Game is not of type * Game.MY_GAME or is a played game. Otherwise, simply returns. */ private void checkGameMineAndExamined(Game game){ if ((game.getGameType() != Game.MY_GAME)||game.isPlayed()) throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and an examined one"); } /** * Sends the "help" command to the server. */ public void showServerHelp(){ sendCommand("help"); } /** * Sends the specified question string to channel 1. */ public void sendHelpQuestion(String question){ sendCommand("tell 1 [" + Jin.getInstance().getAppName() + ' ' + Jin.getInstance().getAppVersion() + "] "+ question); } /** * Overrides ChessclubConnection.execRunnable(Runnable) to execute the * runnable on the AWT thread using SwingUtilities.invokeLater(Runnable), * since this class is meant to be used by Jin, a graphical interface using * Swing. * * @see ChessclubConnection#execRunnable(Runnable) * @see SwingUtilities.invokeLater(Runnable) */ public void execRunnable(Runnable runnable){ SwingUtilities.invokeLater(runnable); } /** * Method called to get user's channel list from server. */ public void updateChannelsList() { sendCommand("inch " + this.getUsername()); } /** * Method called to remove channel from user's channel list. * * @param channelNumber - the number of removed channel. */ public void removeChannel(int channelNumber) { sendCommand("-channel " + channelNumber); } /** * Method called to add channel to user's channel list. * * @param channelNumber - the number of added channel. */ public void addChannel(int channelNumber) { sendCommand("+channel " + channelNumber); } /** * Returns ListenerManager that lets us register listeners */ public ChannelsListenerManager getChannelsListenerManager() { return getFreechessListenerManager(); } }
private void updateOffers(InternalGameData gameData, int offerId, Player player, boolean on){ Game game = gameData.game; if (offerId == OfferEvent.TAKEBACK_OFFER){ // We're forced to fake this so that an event is fired even if we start observing a game // with an existing takeback offer (of which we're not aware). if ((!on) && (gameData.getTakebackOffer(player) == 0)) gameData.setTakebackOffer(player, 1); updateTakebackOffer(gameData, player.getOpponent(), 0); // Remove any existing offers updateTakebackOffer(gameData, player, on ? 1 : 0); // 1 as the server doesn't tell us how many } else{// if (gameData.isOffered(offerId, player) != on){ this // We check this because we might get such an event if we start observing a game with // an existing offer. gameData.setOffer(offerId, player, on); listenerManager.fireGameEvent(new OfferEvent(this, game, offerId, on, player)); } } /** * Updates the takeback offer in the specified game to the specified amount of * plies. */ private void updateTakebackOffer(InternalGameData gameData, Player player, int takebackCount){ Game game = gameData.game; int oldTakeback = gameData.getTakebackOffer(player); if (oldTakeback != 0) listenerManager.fireGameEvent(new OfferEvent(this, game, false, player, oldTakeback)); gameData.setTakebackOffer(player, takebackCount); if (takebackCount != 0) listenerManager.fireGameEvent(new OfferEvent(this, game, true, player, takebackCount)); } /** * Accepts the given seek. Note that the given seek must be an instance generated * by this SeekJinConnection and it must be in the current sought list. */ public void acceptSeek(Seek seek){ if (!seeks.containsValue(seek)) throw new IllegalArgumentException("The specified seek is not on the seek list"); sendCommand("$play "+seek.getID()); } /** * Issues the specified seek. */ public void issueSeek(UserSeek seek){ WildVariant variant = seek.getVariant(); String wildName = getWildName(variant); if (wildName == null) throw new IllegalArgumentException("Unsupported variant: " + variant); Player color = seek.getColor(); String seekCommand = "seek " + seek.getTime() + ' ' + seek.getInc() + ' ' + (seek.isRated() ? "rated" : "unrated") + ' ' + (color == null ? "" : color.isWhite() ? "white " : "black ") + wildName + ' ' + (seek.isManualAccept() ? "manual " : "") + (seek.isFormula() ? "formula " : "") + (seek.getMinRating() == Integer.MIN_VALUE ? "0" : String.valueOf(seek.getMinRating())) + '-' + (seek.getMaxRating() == Integer.MAX_VALUE ? "9999" : String.valueOf(seek.getMaxRating())) + ' '; sendCommand(seekCommand); } /** * Sends the "exit" command to the server. */ public void exit(){ sendCommand("$quit"); } /** * Quits the specified game. */ public void quitGame(Game game){ Object id = game.getID(); switch (game.getGameType()){ case Game.MY_GAME: if (game.isPlayed()) sendCommand("$resign"); else sendCommand("$unexamine"); break; case Game.OBSERVED_GAME: sendCommand("$unobserve "+id); break; case Game.ISOLATED_BOARD: break; } } /** * Makes the given move in the given game. */ public void makeMove(Game game, Move move){ Iterator gamesDataEnum = ongoingGamesData.values().iterator(); boolean ourGame = false; while (gamesDataEnum.hasNext()){ InternalGameData gameData = (InternalGameData)gamesDataEnum.next(); if (gameData.game == game){ ourGame = true; break; } } if (!ourGame) throw new IllegalArgumentException("The specified Game object was not created by this JinConnection or the game has ended."); sendCommand(moveToString(game, move)); ArrayList unechoedGameMoves = (ArrayList)unechoedMoves.get(game); if (unechoedGameMoves == null){ unechoedGameMoves = new ArrayList(2); unechoedMoves.put(game, unechoedGameMoves); } unechoedGameMoves.add(move); } /** * Converts the given move into a string we can send to the server. */ private static String moveToString(Game game, Move move){ WildVariant variant = game.getVariant(); if (move instanceof ChessMove){ ChessMove cmove = (ChessMove)move; if (cmove.isShortCastling()) return "O-O"; else if (cmove.isLongCastling()) return "O-O-O"; String s = cmove.getStartingSquare().toString() + cmove.getEndingSquare().toString(); if (cmove.isPromotion()) return s + '=' + variant.pieceToString(cmove.getPromotionTarget()); else return s; } else throw new IllegalArgumentException("Unsupported Move type: "+move.getClass()); } /** * Resigns the given game. The given game must be a played game and of type * Game.MY_GAME. */ public void resign(Game game){ checkGameMineAndPlayed(game); sendCommand("$resign"); } /** * Sends a request to draw the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestDraw(Game game){ checkGameMineAndPlayed(game); sendCommand("$draw"); } /** * Returns <code>true</code>. */ public boolean isAbortSupported(){ return true; } /** * Sends a request to abort the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestAbort(Game game){ checkGameMineAndPlayed(game); sendCommand("$abort"); } /** * Returns <code>true</code>. */ public boolean isAdjournSupported(){ return true; } /** * Sends a request to adjourn the given game. The given game must be a played * game and of type Game.MY_GAME. */ public void requestAdjourn(Game game){ checkGameMineAndPlayed(game); sendCommand("$adjourn"); } /** * Returns <code>true</code>. */ public boolean isTakebackSupported(){ return true; } /** * Sends "takeback 1" to the server. */ public void requestTakeback(Game game){ checkGameMineAndPlayed(game); sendCommand("$takeback 1"); } /** * Returns <code>true</code>. */ public boolean isMultipleTakebackSupported(){ return true; } /** * Sends "takeback plyCount" to the server. */ public void requestTakeback(Game game, int plyCount){ checkGameMineAndPlayed(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$takeback " + plyCount); } /** * Goes back the given amount of plies in the given game. If the given amount * of plies is bigger than the amount of plies since the beginning of the game, * goes to the beginning of the game. */ public void goBackward(Game game, int plyCount){ checkGameMineAndExamined(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$backward " + plyCount); } /** * Goes forward the given amount of plies in the given game. If the given amount * of plies is bigger than the amount of plies remaining until the end of the * game, goes to the end of the game. */ public void goForward(Game game, int plyCount){ checkGameMineAndExamined(game); if (plyCount < 1) throw new IllegalArgumentException("Illegal ply count: " + plyCount); sendCommand("$forward " + plyCount); } /** * Goes to the beginning of the given game. */ public void goToBeginning(Game game){ checkGameMineAndExamined(game); sendCommand("$backward 999"); } /** * Goes to the end of the given game. */ public void goToEnd(Game game){ checkGameMineAndExamined(game); sendCommand("$forward 999"); } /** * Throws an IllegalArgumentException if the given Game is not of type * Game.MY_GAME or is not a played game. Otherwise, simply returns. */ private void checkGameMineAndPlayed(Game game){ if ((game.getGameType() != Game.MY_GAME) || (!game.isPlayed())) throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and a played one"); } /** * Throws an IllegalArgumentException if the given Game is not of type * Game.MY_GAME or is a played game. Otherwise, simply returns. */ private void checkGameMineAndExamined(Game game){ if ((game.getGameType() != Game.MY_GAME)||game.isPlayed()) throw new IllegalArgumentException("The given game must be of type Game.MY_GAME and an examined one"); } /** * Sends the "help" command to the server. */ public void showServerHelp(){ sendCommand("help"); } /** * Sends the specified question string to channel 1. */ public void sendHelpQuestion(String question){ sendCommand("tell 1 [" + Jin.getInstance().getAppName() + ' ' + Jin.getInstance().getAppVersion() + "] "+ question); } /** * Overrides ChessclubConnection.execRunnable(Runnable) to execute the * runnable on the AWT thread using SwingUtilities.invokeLater(Runnable), * since this class is meant to be used by Jin, a graphical interface using * Swing. * * @see ChessclubConnection#execRunnable(Runnable) * @see SwingUtilities.invokeLater(Runnable) */ public void execRunnable(Runnable runnable){ SwingUtilities.invokeLater(runnable); } /** * Method called to get user's channel list from server. */ public void updateChannelsList() { sendCommand("inch " + this.getUsername()); } /** * Method called to remove channel from user's channel list. * * @param channelNumber - the number of removed channel. */ public void removeChannel(int channelNumber) { sendCommand("-channel " + channelNumber); } /** * Method called to add channel to user's channel list. * * @param channelNumber - the number of added channel. */ public void addChannel(int channelNumber) { sendCommand("+channel " + channelNumber); } /** * Returns ListenerManager that lets us register listeners */ public ChannelsListenerManager getChannelsListenerManager() { return getFreechessListenerManager(); } }
diff --git a/abbyy-server-impl/src/main/java/de/uni_goettingen/sub/commons/ocr/abbyy/server/Hotfolder.java b/abbyy-server-impl/src/main/java/de/uni_goettingen/sub/commons/ocr/abbyy/server/Hotfolder.java index e56dbdb2..3cb07ca8 100644 --- a/abbyy-server-impl/src/main/java/de/uni_goettingen/sub/commons/ocr/abbyy/server/Hotfolder.java +++ b/abbyy-server-impl/src/main/java/de/uni_goettingen/sub/commons/ocr/abbyy/server/Hotfolder.java @@ -1,53 +1,54 @@ package de.uni_goettingen.sub.commons.ocr.abbyy.server; import java.net.URL; import java.util.List; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemException; import org.apache.commons.vfs.FileSystemManager; import org.apache.commons.vfs.VFS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Hotfolder { final Logger logger = LoggerFactory.getLogger(Hotfolder.class); FileSystemManager fsManager = null; public Hotfolder () throws FileSystemException { fsManager = VFS.getManager(); } - protected void copyFilesToServer(List<AbbyyOCRFile> files) { + protected void copyFilesToServer(List<AbbyyOCRFile> files) throws FileSystemException { // iterate over all Files and put them to Abbyy-server inputFolder: for (AbbyyOCRFile info : files) { URL AbbyyFileName = info.getRemoteURL(); FileObject remoteFile = fsManager.resolveFile(AbbyyFileName.toString()); remoteFile.delete(); if (AbbyyFileName.toString().endsWith("/")) { logger.trace("Creating new directory " + AbbyyFileName + "!"); //TODO: Create the directory //mkCol(AbbyyFileName); } else { - logger.trace("Copy from " + info.getLocalFile().getAbsolutePath() + " to " + AbbyyFileName); - put(AbbyyFileName, info.getLocalFile()); + logger.trace("Copy from " + info.getUrl().toString() + " to " + info.getRemoteFileName()); + //TODO: Upload the file + //put(AbbyyFileName, info.getLocalFile()); } } } //Implement a method to download the files //abstract void protected getResults (); protected Long getSize(String path) { return null; } }
false
true
protected void copyFilesToServer(List<AbbyyOCRFile> files) { // iterate over all Files and put them to Abbyy-server inputFolder: for (AbbyyOCRFile info : files) { URL AbbyyFileName = info.getRemoteURL(); FileObject remoteFile = fsManager.resolveFile(AbbyyFileName.toString()); remoteFile.delete(); if (AbbyyFileName.toString().endsWith("/")) { logger.trace("Creating new directory " + AbbyyFileName + "!"); //TODO: Create the directory //mkCol(AbbyyFileName); } else { logger.trace("Copy from " + info.getLocalFile().getAbsolutePath() + " to " + AbbyyFileName); put(AbbyyFileName, info.getLocalFile()); } } }
protected void copyFilesToServer(List<AbbyyOCRFile> files) throws FileSystemException { // iterate over all Files and put them to Abbyy-server inputFolder: for (AbbyyOCRFile info : files) { URL AbbyyFileName = info.getRemoteURL(); FileObject remoteFile = fsManager.resolveFile(AbbyyFileName.toString()); remoteFile.delete(); if (AbbyyFileName.toString().endsWith("/")) { logger.trace("Creating new directory " + AbbyyFileName + "!"); //TODO: Create the directory //mkCol(AbbyyFileName); } else { logger.trace("Copy from " + info.getUrl().toString() + " to " + info.getRemoteFileName()); //TODO: Upload the file //put(AbbyyFileName, info.getLocalFile()); } } }
diff --git a/src/com/android/mms/ui/RecipientsAdapter.java b/src/com/android/mms/ui/RecipientsAdapter.java index c1e933be..15516607 100644 --- a/src/com/android/mms/ui/RecipientsAdapter.java +++ b/src/com/android/mms/ui/RecipientsAdapter.java @@ -1,259 +1,259 @@ /* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.ui; import com.android.common.ArrayListCursor; import com.android.mms.MmsApp; import com.android.mms.R; import com.android.mms.data.Contact; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.database.MergeCursor; import android.net.Uri; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.DataUsageFeedback; import android.telephony.PhoneNumberUtils; import android.text.Annotation; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.view.View; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import java.util.ArrayList; /** * This adapter is used to filter contacts on both name and number. */ public class RecipientsAdapter extends ResourceCursorAdapter { public static final int CONTACT_ID_INDEX = 1; public static final int TYPE_INDEX = 2; public static final int NUMBER_INDEX = 3; public static final int LABEL_INDEX = 4; public static final int NAME_INDEX = 5; public static final int NORMALIZED_NUMBER = 6; private static final String[] PROJECTION_PHONE = { Phone._ID, // 0 Phone.CONTACT_ID, // 1 Phone.TYPE, // 2 Phone.NUMBER, // 3 Phone.LABEL, // 4 Phone.DISPLAY_NAME, // 5 Phone.NORMALIZED_NUMBER, // 6 }; private static final String SORT_ORDER = Contacts.TIMES_CONTACTED + " DESC," + Contacts.DISPLAY_NAME + "," + Phone.TYPE; private final Context mContext; private final ContentResolver mContentResolver; private final String mDefaultCountryIso; public RecipientsAdapter(Context context) { // Note that the RecipientsAdapter doesn't support auto-requeries. If we // want to respond to changes in the contacts we're displaying in the drop-down, // code using this adapter would have to add a line such as: // mRecipientsAdapter.setOnDataSetChangedListener(mDataSetChangedListener); // See ComposeMessageActivity for an example. super(context, R.layout.recipient_filter_item, null, false /* no auto-requery */); mContext = context; mContentResolver = context.getContentResolver(); mDefaultCountryIso = MmsApp.getApplication().getCurrentCountryIso(); } @Override public final CharSequence convertToString(Cursor cursor) { String number = cursor.getString(RecipientsAdapter.NUMBER_INDEX); if (number == null) { return ""; } number = number.trim(); String name = cursor.getString(RecipientsAdapter.NAME_INDEX); int type = cursor.getInt(RecipientsAdapter.TYPE_INDEX); String label = cursor.getString(RecipientsAdapter.LABEL_INDEX); CharSequence displayLabel = Phone.getDisplayLabel(mContext, type, label); if (name == null) { name = ""; } else { // Names with commas are the bane of the recipient editor's existence. // We've worked around them by using spans, but there are edge cases // where the spans get deleted. Furthermore, having commas in names // can be confusing to the user since commas are used as separators // between recipients. The best solution is to simply remove commas // from names. name = name.replace(", ", " ") .replace(",", " "); // Make sure we leave a space between parts of names. } String nameAndNumber = Contact.formatNameAndNumber( name, number, cursor.getString(NORMALIZED_NUMBER), mDefaultCountryIso); SpannableString out = new SpannableString(nameAndNumber); int len = out.length(); if (!TextUtils.isEmpty(name)) { out.setSpan(new Annotation("name", name), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { out.setSpan(new Annotation("name", number), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } String person_id = cursor.getString(RecipientsAdapter.CONTACT_ID_INDEX); out.setSpan(new Annotation("person_id", person_id), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); out.setSpan(new Annotation("label", displayLabel.toString()), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); out.setSpan(new Annotation("number", number), 0, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return out; } @Override public final void bindView(View view, Context context, Cursor cursor) { TextView name = (TextView) view.findViewById(R.id.name); name.setText(cursor.getString(NAME_INDEX)); TextView label = (TextView) view.findViewById(R.id.label); int type = cursor.getInt(TYPE_INDEX); CharSequence labelText = Phone.getDisplayLabel(mContext, type, cursor.getString(LABEL_INDEX)); // When there's no label, getDisplayLabel() returns a CharSequence of length==1 containing // a unicode non-breaking space. Need to check for that and consider that as "no label". if (labelText.length() == 0 || (labelText.length() == 1 && labelText.charAt(0) == '\u00A0')) { label.setVisibility(View.GONE); } else { label.setText(labelText); label.setVisibility(View.VISIBLE); } TextView number = (TextView) view.findViewById(R.id.number); number.setText( PhoneNumberUtils.formatNumber(cursor.getString(NUMBER_INDEX), cursor.getString(NORMALIZED_NUMBER), mDefaultCountryIso)); } @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String phone = ""; String cons = null; if (constraint != null) { cons = constraint.toString(); if (usefulAsDigits(cons)) { phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons); if (phone.equals(cons)) { phone = ""; } else { phone = phone.trim(); } } } Uri uri = Phone.CONTENT_FILTER_URI.buildUpon() - .appendPath(Uri.encode(cons)) + .appendPath(cons) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, DataUsageFeedback.USAGE_TYPE_SHORT_TEXT) .build(); /* * if we decide to filter based on phone types use a selection * like this. String selection = String.format("%s=%s OR %s=%s OR %s=%s", Phone.TYPE, Phone.TYPE_MOBILE, Phone.TYPE, Phone.TYPE_WORK_MOBILE, Phone.TYPE, Phone.TYPE_MMS); */ Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, null, //selection, null, null); if (phone.length() > 0) { ArrayList result = new ArrayList(); result.add(Integer.valueOf(-1)); // ID result.add(Long.valueOf(-1)); // CONTACT_ID result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE result.add(phone); // NUMBER /* * The "\u00A0" keeps Phone.getDisplayLabel() from deciding * to display the default label ("Home") next to the transformation * of the letters into numbers. */ result.add("\u00A0"); // LABEL result.add(cons); // NAME result.add(phone); // NORMALIZED_NUMBER ArrayList<ArrayList> wrap = new ArrayList<ArrayList>(); wrap.add(result); ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap); return new MergeCursor(new Cursor[] { translated, phoneCursor }); } else { return phoneCursor; } } /** * Returns true if all the characters are meaningful as digits * in a phone number -- letters, digits, and a few punctuation marks. */ private boolean usefulAsDigits(CharSequence cons) { int len = cons.length(); for (int i = 0; i < len; i++) { char c = cons.charAt(i); if ((c >= '0') && (c <= '9')) { continue; } if ((c == ' ') || (c == '-') || (c == '(') || (c == ')') || (c == '.') || (c == '+') || (c == '#') || (c == '*')) { continue; } if ((c >= 'A') && (c <= 'Z')) { continue; } if ((c >= 'a') && (c <= 'z')) { continue; } return false; } return true; } }
true
true
public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String phone = ""; String cons = null; if (constraint != null) { cons = constraint.toString(); if (usefulAsDigits(cons)) { phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons); if (phone.equals(cons)) { phone = ""; } else { phone = phone.trim(); } } } Uri uri = Phone.CONTENT_FILTER_URI.buildUpon() .appendPath(Uri.encode(cons)) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, DataUsageFeedback.USAGE_TYPE_SHORT_TEXT) .build(); /* * if we decide to filter based on phone types use a selection * like this. String selection = String.format("%s=%s OR %s=%s OR %s=%s", Phone.TYPE, Phone.TYPE_MOBILE, Phone.TYPE, Phone.TYPE_WORK_MOBILE, Phone.TYPE, Phone.TYPE_MMS); */ Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, null, //selection, null, null); if (phone.length() > 0) { ArrayList result = new ArrayList(); result.add(Integer.valueOf(-1)); // ID result.add(Long.valueOf(-1)); // CONTACT_ID result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE result.add(phone); // NUMBER /* * The "\u00A0" keeps Phone.getDisplayLabel() from deciding * to display the default label ("Home") next to the transformation * of the letters into numbers. */ result.add("\u00A0"); // LABEL result.add(cons); // NAME result.add(phone); // NORMALIZED_NUMBER ArrayList<ArrayList> wrap = new ArrayList<ArrayList>(); wrap.add(result); ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap); return new MergeCursor(new Cursor[] { translated, phoneCursor }); } else { return phoneCursor; } }
public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String phone = ""; String cons = null; if (constraint != null) { cons = constraint.toString(); if (usefulAsDigits(cons)) { phone = PhoneNumberUtils.convertKeypadLettersToDigits(cons); if (phone.equals(cons)) { phone = ""; } else { phone = phone.trim(); } } } Uri uri = Phone.CONTENT_FILTER_URI.buildUpon() .appendPath(cons) .appendQueryParameter(DataUsageFeedback.USAGE_TYPE, DataUsageFeedback.USAGE_TYPE_SHORT_TEXT) .build(); /* * if we decide to filter based on phone types use a selection * like this. String selection = String.format("%s=%s OR %s=%s OR %s=%s", Phone.TYPE, Phone.TYPE_MOBILE, Phone.TYPE, Phone.TYPE_WORK_MOBILE, Phone.TYPE, Phone.TYPE_MMS); */ Cursor phoneCursor = mContentResolver.query(uri, PROJECTION_PHONE, null, //selection, null, null); if (phone.length() > 0) { ArrayList result = new ArrayList(); result.add(Integer.valueOf(-1)); // ID result.add(Long.valueOf(-1)); // CONTACT_ID result.add(Integer.valueOf(Phone.TYPE_CUSTOM)); // TYPE result.add(phone); // NUMBER /* * The "\u00A0" keeps Phone.getDisplayLabel() from deciding * to display the default label ("Home") next to the transformation * of the letters into numbers. */ result.add("\u00A0"); // LABEL result.add(cons); // NAME result.add(phone); // NORMALIZED_NUMBER ArrayList<ArrayList> wrap = new ArrayList<ArrayList>(); wrap.add(result); ArrayListCursor translated = new ArrayListCursor(PROJECTION_PHONE, wrap); return new MergeCursor(new Cursor[] { translated, phoneCursor }); } else { return phoneCursor; } }
diff --git a/encuestame-mvc/src/test/java/org/encuestame/mvc/test/json/DashboardJsonControllerTestCase.java b/encuestame-mvc/src/test/java/org/encuestame/mvc/test/json/DashboardJsonControllerTestCase.java index 30b506bf4..9c054cd86 100644 --- a/encuestame-mvc/src/test/java/org/encuestame/mvc/test/json/DashboardJsonControllerTestCase.java +++ b/encuestame-mvc/src/test/java/org/encuestame/mvc/test/json/DashboardJsonControllerTestCase.java @@ -1,93 +1,93 @@ /* ************************************************************************************ * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011 * encuestame Development Team. * Licensed under the Apache Software License version 2.0 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. ************************************************************************************ */ package org.encuestame.mvc.test.json; import java.io.IOException; import javax.servlet.ServletException; import junit.framework.Assert; import org.encuestame.mvc.controller.json.MethodJson; import org.encuestame.mvc.test.config.AbstractJsonMvcUnitBeans; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.junit.Test; /** * Description. * @author Picado, Juan juanATencuestame.org * @since 04/08/2011 */ public class DashboardJsonControllerTestCase extends AbstractJsonMvcUnitBeans{ /** * @throws IOException * @throws ServletException * */ @Test public void testCreateDashboard() throws ServletException, IOException{ initService("/api/common/dashboard/create-dashboard.json", MethodJson.POST); setParameter("name", "test"); setParameter("desc", "test"); setParameter("favorite", "true"); setParameter("layout", "AAA"); final JSONObject response = callJsonService(); //{"error":{},"success":{"dashboard":{"dashboard_name":"test","id":7608,"sequence":null, //"layout":"AAA","favorite":true,"favorite_counter":null,"dashboard_description":"test"}}} final JSONObject success = getSucess(response); final JSONObject dashboard = (JSONObject) success.get("dashboard"); Assert.assertEquals(dashboard.get("dashboard_name").toString(), "test"); Assert.assertEquals(dashboard.get("layout").toString(), "AAA"); Assert.assertEquals(dashboard.get("favorite").toString(), "true"); Assert.assertEquals(dashboard.get("dashboard_description").toString(), "test"); } /** * * @throws ServletException * @throws IOException */ @Test public void testgetGadgets() throws ServletException, IOException{ initService("/api/common/gadgets/list.json", MethodJson.GET); setParameter("dashboardId", "1"); final JSONObject response = callJsonService(); System.out.println(response); final JSONObject success = getSucess(response); final JSONArray gadgets = (JSONArray) success.get("gadgets"); Assert.assertEquals(gadgets.size(), 0); initService("/api/common/gadgets/list.json", MethodJson.GET); createGadgetDefault(createDashboardDefault(getSpringSecurityLoggedUserAccount())); createGadgetDefault(createDashboardDefault(getSpringSecurityLoggedUserAccount())); initService("/api/common/gadgets/list.json", MethodJson.GET); setParameter("dashboardId", "2"); final JSONObject response2 = callJsonService(); System.out.println(response2); final JSONObject success2 = getSucess(response2); final JSONArray gadgets2 = (JSONArray) success2.get("gadgets"); - Assert.assertEquals(gadgets2.size(), 0); + Assert.assertEquals(gadgets2.size(), 1); } /*@Test public void testMoveGadgets() throws ServletException, IOException{ initService("/api/common/move-gadgets.json", MethodJson.GET); setParameter("gadgetId", "gadgetId"); setParameter("position", "position"); setParameter("column", "column"); final JSONObject response = callJsonService(); final JSONObject success = getSucess(response); }*/ }
true
true
public void testgetGadgets() throws ServletException, IOException{ initService("/api/common/gadgets/list.json", MethodJson.GET); setParameter("dashboardId", "1"); final JSONObject response = callJsonService(); System.out.println(response); final JSONObject success = getSucess(response); final JSONArray gadgets = (JSONArray) success.get("gadgets"); Assert.assertEquals(gadgets.size(), 0); initService("/api/common/gadgets/list.json", MethodJson.GET); createGadgetDefault(createDashboardDefault(getSpringSecurityLoggedUserAccount())); createGadgetDefault(createDashboardDefault(getSpringSecurityLoggedUserAccount())); initService("/api/common/gadgets/list.json", MethodJson.GET); setParameter("dashboardId", "2"); final JSONObject response2 = callJsonService(); System.out.println(response2); final JSONObject success2 = getSucess(response2); final JSONArray gadgets2 = (JSONArray) success2.get("gadgets"); Assert.assertEquals(gadgets2.size(), 0); }
public void testgetGadgets() throws ServletException, IOException{ initService("/api/common/gadgets/list.json", MethodJson.GET); setParameter("dashboardId", "1"); final JSONObject response = callJsonService(); System.out.println(response); final JSONObject success = getSucess(response); final JSONArray gadgets = (JSONArray) success.get("gadgets"); Assert.assertEquals(gadgets.size(), 0); initService("/api/common/gadgets/list.json", MethodJson.GET); createGadgetDefault(createDashboardDefault(getSpringSecurityLoggedUserAccount())); createGadgetDefault(createDashboardDefault(getSpringSecurityLoggedUserAccount())); initService("/api/common/gadgets/list.json", MethodJson.GET); setParameter("dashboardId", "2"); final JSONObject response2 = callJsonService(); System.out.println(response2); final JSONObject success2 = getSucess(response2); final JSONArray gadgets2 = (JSONArray) success2.get("gadgets"); Assert.assertEquals(gadgets2.size(), 1); }
diff --git a/src/me/chaseoes/supercraftbrothers/listeners/PlayerInteractListener.java b/src/me/chaseoes/supercraftbrothers/listeners/PlayerInteractListener.java index 6586599..aa13b17 100644 --- a/src/me/chaseoes/supercraftbrothers/listeners/PlayerInteractListener.java +++ b/src/me/chaseoes/supercraftbrothers/listeners/PlayerInteractListener.java @@ -1,36 +1,36 @@ package me.chaseoes.supercraftbrothers.listeners; import me.chaseoes.supercraftbrothers.SCBGame; import me.chaseoes.supercraftbrothers.SCBGameManager; import me.chaseoes.supercraftbrothers.classes.SCBClass; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Sign; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; public class PlayerInteractListener implements Listener { public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && event.getClickedBlock().getType() == Material.WALL_SIGN) { Sign s = (Sign) event.getClickedBlock().getState(); if (s.getLine(0).equalsIgnoreCase("") && !s.getLine(1).equalsIgnoreCase("") && s.getLine(2).equalsIgnoreCase("") && s.getLine(3).equalsIgnoreCase("")) { String className = ChatColor.stripColor(s.getLine(1)); SCBClass sc = new SCBClass(className); sc.apply(SCBGameManager.getInstance().getCraftBrother(event.getPlayer())); } if (s.getLine(0).equalsIgnoreCase("SuperCraftBros")) { String mapName = ChatColor.stripColor(s.getLine(1)); - SCBGameManager.getInstance().getGame(mapName).joinGame(event.getPlayer()); + SCBGameManager.getInstance().getGame(mapName).joinLobby(event.getPlayer()); } } for (SCBGame game : SCBGameManager.getInstance().getAllGames()) { } } }
true
true
public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && event.getClickedBlock().getType() == Material.WALL_SIGN) { Sign s = (Sign) event.getClickedBlock().getState(); if (s.getLine(0).equalsIgnoreCase("") && !s.getLine(1).equalsIgnoreCase("") && s.getLine(2).equalsIgnoreCase("") && s.getLine(3).equalsIgnoreCase("")) { String className = ChatColor.stripColor(s.getLine(1)); SCBClass sc = new SCBClass(className); sc.apply(SCBGameManager.getInstance().getCraftBrother(event.getPlayer())); } if (s.getLine(0).equalsIgnoreCase("SuperCraftBros")) { String mapName = ChatColor.stripColor(s.getLine(1)); SCBGameManager.getInstance().getGame(mapName).joinGame(event.getPlayer()); } } for (SCBGame game : SCBGameManager.getInstance().getAllGames()) { } }
public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.hasBlock() && event.getClickedBlock().getType() == Material.WALL_SIGN) { Sign s = (Sign) event.getClickedBlock().getState(); if (s.getLine(0).equalsIgnoreCase("") && !s.getLine(1).equalsIgnoreCase("") && s.getLine(2).equalsIgnoreCase("") && s.getLine(3).equalsIgnoreCase("")) { String className = ChatColor.stripColor(s.getLine(1)); SCBClass sc = new SCBClass(className); sc.apply(SCBGameManager.getInstance().getCraftBrother(event.getPlayer())); } if (s.getLine(0).equalsIgnoreCase("SuperCraftBros")) { String mapName = ChatColor.stripColor(s.getLine(1)); SCBGameManager.getInstance().getGame(mapName).joinLobby(event.getPlayer()); } } for (SCBGame game : SCBGameManager.getInstance().getAllGames()) { } }
diff --git a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/engine/SourceBasedSourceGenerator.java b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/engine/SourceBasedSourceGenerator.java index 25e7e1c31..2a9b959a4 100644 --- a/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/engine/SourceBasedSourceGenerator.java +++ b/org.eclipse.jdt.debug/eval/org/eclipse/jdt/internal/debug/eval/ast/engine/SourceBasedSourceGenerator.java @@ -1,1733 +1,1733 @@ /******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.eval.ast.engine; import java.util.Iterator; import java.util.List; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.ArrayAccess; import org.eclipse.jdt.core.dom.ArrayCreation; import org.eclipse.jdt.core.dom.ArrayInitializer; import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.AssertStatement; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.BlockComment; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.BooleanLiteral; import org.eclipse.jdt.core.dom.BreakStatement; import org.eclipse.jdt.core.dom.CastExpression; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.CharacterLiteral; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConditionalExpression; import org.eclipse.jdt.core.dom.ConstructorInvocation; import org.eclipse.jdt.core.dom.ContinueStatement; import org.eclipse.jdt.core.dom.DoStatement; import org.eclipse.jdt.core.dom.EmptyStatement; import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.EnumConstantDeclaration; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.Initializer; import org.eclipse.jdt.core.dom.InstanceofExpression; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.LabeledStatement; import org.eclipse.jdt.core.dom.LineComment; import org.eclipse.jdt.core.dom.MarkerAnnotation; import org.eclipse.jdt.core.dom.MemberRef; import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.MethodRef; import org.eclipse.jdt.core.dom.MethodRefParameter; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.NullLiteral; import org.eclipse.jdt.core.dom.NumberLiteral; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.ParenthesizedExpression; import org.eclipse.jdt.core.dom.PostfixExpression; import org.eclipse.jdt.core.dom.PrefixExpression; import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.QualifiedType; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleMemberAnnotation; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.StringLiteral; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.SuperFieldAccess; import org.eclipse.jdt.core.dom.SuperMethodInvocation; import org.eclipse.jdt.core.dom.SwitchCase; import org.eclipse.jdt.core.dom.SwitchStatement; import org.eclipse.jdt.core.dom.SynchronizedStatement; import org.eclipse.jdt.core.dom.TagElement; import org.eclipse.jdt.core.dom.TextElement; import org.eclipse.jdt.core.dom.ThisExpression; import org.eclipse.jdt.core.dom.ThrowStatement; import org.eclipse.jdt.core.dom.TryStatement; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.TypeDeclarationStatement; import org.eclipse.jdt.core.dom.TypeLiteral; import org.eclipse.jdt.core.dom.TypeParameter; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jdt.core.dom.WhileStatement; import org.eclipse.jdt.core.dom.WildcardType; public class SourceBasedSourceGenerator extends ASTVisitor { private static final String RUN_METHOD_NAME= "___run"; //$NON-NLS-1$ private static final String EVAL_METHOD_NAME= "___eval"; //$NON-NLS-1$ private static final String EVAL_FIELD_NAME= "___field"; //$NON-NLS-1$ private String[] fLocalVariableTypeNames; private String[] fLocalVariableNames; private String fCodeSnippet; private boolean fRightTypeFound; private boolean fCreateInAStaticMethod; private boolean fEvaluateNextEndTypeDeclaration; private String fError; private CompilationUnit fUnit; private String fTypeName; private int fPosition; private StringBuffer fSource; private String fLastTypeName; private String fCompilationUnitName; private int fSnippetStartPosition; private int fRunMethodStartOffset; private int fRunMethodLength; /** * if the <code>createInAnInstanceMethod</code> flag is set, the method created * which contains the code snippet is an no-static method, even if <code>position</code> * is in a static method. */ public SourceBasedSourceGenerator(CompilationUnit unit, String typeName, int position, boolean createInAStaticMethod, String[] localTypesNames, String[] localVariables, String codeSnippet) { fRightTypeFound= false; fUnit= unit; fTypeName= typeName; fPosition= position; fLocalVariableTypeNames= localTypesNames; fLocalVariableNames= localVariables; fCodeSnippet= codeSnippet; fCreateInAStaticMethod= createInAStaticMethod; } /** * Returns the generated source or <code>null</code> if no source can be generated. */ public String getSource() { if (fSource == null) { return null; } return fSource.toString(); } private CompilationUnit getCompilationUnit() { return fUnit; } public String getCompilationUnitName() { return fCompilationUnitName; } public int getSnippetStart() { return fSnippetStartPosition; } public int getRunMethodStart() { return fSnippetStartPosition - fRunMethodStartOffset; } public int getRunMethodLength() { return fRunMethodLength; } private int getPosition() { return fPosition; } private int getCorrespondingLineNumber(int charOffset) { return getCompilationUnit().lineNumber(charOffset); } private boolean rightTypeFound() { return fRightTypeFound; } private void setRightTypeFound(boolean value) { fRightTypeFound= value; } public boolean hasError() { return fError != null; } public void setError(String errorDesc) { fError= errorDesc; } public String getError() { return fError; } private StringBuffer buildRunMethod(List bodyDeclarations) { StringBuffer buffer = new StringBuffer(); if (fCreateInAStaticMethod) { buffer.append("static "); //$NON-NLS-1$ } buffer.append("void "); //$NON-NLS-1$ buffer.append(getUniqueMethodName(RUN_METHOD_NAME, bodyDeclarations)); buffer.append('('); for(int i= 0, length= fLocalVariableNames.length; i < length; i++) { buffer.append(getDotName(fLocalVariableTypeNames[i])); buffer.append(' '); buffer.append(fLocalVariableNames[i]); if (i + 1 < length) buffer.append(", "); //$NON-NLS-1$ } buffer.append(") throws Throwable {"); //$NON-NLS-1$ buffer.append('\n'); fSnippetStartPosition= buffer.length() - 2; fRunMethodStartOffset= fSnippetStartPosition; String codeSnippet= new String(fCodeSnippet).trim(); buffer.append(codeSnippet); buffer.append('\n'); buffer.append('}').append('\n'); fRunMethodLength= buffer.length(); return buffer; } private String getDotName(String typeName) { return typeName.replace('$', '.'); } private boolean isRightType(ASTNode node) { int position= getPosition(); int startLineNumber= getCorrespondingLineNumber(node.getStartPosition()); int endLineNumber= getCorrespondingLineNumber(node.getStartPosition() + node.getLength() - 1); if (startLineNumber <= position && position <= endLineNumber) { // check the typeName String typeName= fTypeName; while (node != null) { if (node instanceof TypeDeclaration || node instanceof EnumDeclaration) { AbstractTypeDeclaration abstractTypeDeclaration= (AbstractTypeDeclaration) node; String name= abstractTypeDeclaration.getName().getIdentifier(); if (abstractTypeDeclaration.isLocalTypeDeclaration()) { if (! typeName.endsWith('$' + name)) { return false; } typeName= typeName.substring(0, typeName.length() - name.length() - 1); int index= typeName.lastIndexOf('$'); if (index < 0) { return false; } for (int i= typeName.length() - 1; i > index; i--) { if (!Character.isDigit(typeName.charAt(i))) { return false; } } typeName= typeName.substring(0, index); ASTNode parent= node.getParent(); while (!(parent instanceof CompilationUnit)) { node= parent; parent= node.getParent(); } } else { if (abstractTypeDeclaration.isPackageMemberTypeDeclaration()) { PackageDeclaration packageDeclaration= ((CompilationUnit) node.getParent()).getPackage(); if (packageDeclaration == null) { return typeName.equals(name); } return typeName.equals(getQualifiedIdentifier(packageDeclaration.getName()) + '.' + name); } if (!typeName.endsWith('$' + name)) { return false; } typeName= typeName.substring(0, typeName.length() - name.length() - 1); node= node.getParent(); } } else if (node instanceof ClassInstanceCreation) { int index= typeName.lastIndexOf('$'); if (index < 0) { return false; } for (int i= typeName.length() - 1; i > index; i--) { if (!Character.isDigit(typeName.charAt(i))) { return false; } } typeName= typeName.substring(0, index); ASTNode parent= node.getParent(); while (!(parent instanceof CompilationUnit)) { node= parent; parent= node.getParent(); } } } } return false; } private StringBuffer buildTypeBody(StringBuffer buffer, List list) { StringBuffer source = new StringBuffer(); source.append('{').append('\n'); if (buffer != null) { fSnippetStartPosition+= source.length(); } source.append(buildBody(buffer, list)); source.append('}').append('\n'); return source; } private StringBuffer buildEnumBody(StringBuffer buffer, List constantDeclarations, List bodyDeclarations) { StringBuffer source = new StringBuffer(); source.append('{').append('\n'); if (constantDeclarations.isEmpty()) { source.append(';').append('\n'); } else { for (Iterator iter= constantDeclarations.iterator(); iter.hasNext();) { source.append(((EnumConstantDeclaration) iter.next()).getName().getIdentifier()); if (iter.hasNext()) { source.append(','); } else { source.append(';'); } source.append('\n'); } } if (buffer != null) { fSnippetStartPosition+= source.length(); } source.append(buildBody(buffer, bodyDeclarations)); source.append('}').append('\n'); return source; } /** * @param buffer * @param list * @param source */ private StringBuffer buildBody(StringBuffer buffer, List list) { StringBuffer source= new StringBuffer(); if (buffer != null) { fSnippetStartPosition += source.length(); source.append(buffer.toString()); } for (Iterator iterator= list.iterator(); iterator.hasNext();) { BodyDeclaration bodyDeclaration= (BodyDeclaration) iterator.next(); if (bodyDeclaration instanceof FieldDeclaration) { source.append(buildFieldDeclaration((FieldDeclaration) bodyDeclaration)); } else if (bodyDeclaration instanceof MethodDeclaration) { source.append(buildMethodDeclaration((MethodDeclaration) bodyDeclaration)); } else if (bodyDeclaration instanceof TypeDeclaration) { TypeDeclaration typeDeclaration = (TypeDeclaration) bodyDeclaration; if (!typeDeclaration.getName().getIdentifier().equals(fLastTypeName)) { source.append(buildTypeDeclaration(null, typeDeclaration)); } } else if (bodyDeclaration instanceof EnumDeclaration) { EnumDeclaration enumDeclaration= (EnumDeclaration) bodyDeclaration; if (!enumDeclaration.getName().getIdentifier().equals(fLastTypeName)) { source.append(buildEnumDeclaration(null, enumDeclaration)); } } } return source; } private StringBuffer buildFieldDeclaration(FieldDeclaration fieldDeclaration) { StringBuffer source = new StringBuffer(); source.append(Flags.toString(fieldDeclaration.getModifiers())); source.append(' '); source.append(getDotName(getTypeName(fieldDeclaration.getType()))); source.append(' '); boolean first= true; for (Iterator iterator= fieldDeclaration.fragments().iterator(); iterator.hasNext();) { VariableDeclarationFragment variableDeclarationFragment= (VariableDeclarationFragment) iterator.next(); if (first) { first = false; } else { source.append(','); } source.append(variableDeclarationFragment.getName().getIdentifier()); for (int i= 0, dim= variableDeclarationFragment.getExtraDimensions(); i < dim; i++) { source.append('[').append(']'); } } source.append(';').append('\n'); return source; } private StringBuffer buildMethodDeclaration(MethodDeclaration methodDeclaration) { StringBuffer source = new StringBuffer(); int modifiers= methodDeclaration.getModifiers(); source.append(Flags.toString(modifiers)); source.append(' '); boolean isConstructor= methodDeclaration.isConstructor(); if (!isConstructor) { source.append(getDotName(getTypeName(methodDeclaration.getReturnType2()))); source.append(' '); } source.append(methodDeclaration.getName().getIdentifier()); source.append(' ').append('('); boolean first= true; for (Iterator iterator = methodDeclaration.parameters().iterator(); iterator.hasNext();) { SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration) iterator.next(); if (first) { first = false; } else { source.append(','); } source.append(getDotName(getTypeName(singleVariableDeclaration.getType()))); if (singleVariableDeclaration.isVarargs()) { source.append("..."); //$NON-NLS-1$ } source.append(' '); source.append(singleVariableDeclaration.getName().getIdentifier()); appendExtraDimensions(source, singleVariableDeclaration.getExtraDimensions()); } source.append(')'); appendExtraDimensions(source, methodDeclaration.getExtraDimensions()); first = true; for (Iterator iterator = methodDeclaration.thrownExceptions().iterator(); iterator.hasNext();) { Name name = (Name) iterator.next(); if (first) { first = false; source.append(" throws "); //$NON-NLS-1$ } else { source.append(','); } source.append(getQualifiedIdentifier(name)); } if (Flags.isAbstract(modifiers) || Flags.isNative(modifiers)) { // No body for abstract and native methods source.append(";\n"); //$NON-NLS-1$ } else { source.append('{').append('\n'); if (!isConstructor) { source.append(getReturnExpression(methodDeclaration.getReturnType2())); } source.append('}').append('\n'); } return source; } private void appendExtraDimensions(StringBuffer source, int extraDimension) { if (extraDimension > 0) { source.append(' '); for (int i= 0; i < extraDimension; i ++) { source.append("[]"); //$NON-NLS-1$ } } } private StringBuffer buildEnumDeclaration(StringBuffer buffer, EnumDeclaration enumDeclaration) { StringBuffer source = new StringBuffer(); source.append(Flags.toString(enumDeclaration.getModifiers())); source.append(" enum "); //$NON-NLS-1$ source.append(enumDeclaration.getName().getIdentifier()); Iterator iterator= enumDeclaration.superInterfaceTypes().iterator(); if (iterator.hasNext()) { source.append(" implements "); //$NON-NLS-1$ source.append(getTypeName((Type) iterator.next())); while (iterator.hasNext()) { source.append(','); source.append(getTypeName((Type) iterator.next())); } } if (buffer != null) { fSnippetStartPosition+= source.length(); } source.append(buildEnumBody(buffer, enumDeclaration.enumConstants(), enumDeclaration.bodyDeclarations())); return source; } private StringBuffer buildTypeDeclaration(StringBuffer buffer, TypeDeclaration typeDeclaration) { StringBuffer source = new StringBuffer(); source.append(Flags.toString(typeDeclaration.getModifiers())); if (typeDeclaration.isInterface()) { source.append(" interface "); //$NON-NLS-1$ } else { source.append(" class "); //$NON-NLS-1$ } source.append(typeDeclaration.getName().getIdentifier()); List typeParameters= typeDeclaration.typeParameters(); if (!typeParameters.isEmpty()) { source.append('<'); Iterator iter= typeParameters.iterator(); TypeParameter typeParameter= (TypeParameter) iter.next(); source.append(typeParameter.getName().getIdentifier()); List typeBounds= typeParameter.typeBounds(); if (!typeBounds.isEmpty()) { source.append(" extends "); //$NON-NLS-1$ Iterator iter2= typeBounds.iterator(); source.append(getTypeName((Type) iter2.next())); - while (iter.hasNext()) { + while (iter2.hasNext()) { source.append('&'); source.append(getTypeName((Type) iter2.next())); } } while (iter.hasNext()) { source.append(','); typeParameter= (TypeParameter) iter.next(); source.append(typeParameter.getName().getIdentifier()); typeBounds= typeParameter.typeBounds(); if (!typeBounds.isEmpty()) { source.append(" extends "); //$NON-NLS-1$ Iterator iter2= typeBounds.iterator(); source.append(getTypeName((Type) iter2.next())); - while (iter.hasNext()) { + while (iter2.hasNext()) { source.append('&'); source.append(getTypeName((Type) iter2.next())); } } } source.append('>'); } Type superClass = typeDeclaration.getSuperclassType(); if (superClass != null) { source.append(" extends "); //$NON-NLS-1$ source.append(getTypeName(superClass)); } Iterator iter= typeDeclaration.superInterfaceTypes().iterator(); if (iter.hasNext()) { if (typeDeclaration.isInterface()) { source.append(" extends "); //$NON-NLS-1$ } else { source.append(" implements "); //$NON-NLS-1$ } source.append(getTypeName((Type) iter.next())); while (iter.hasNext()) { source.append(','); source.append(getTypeName((Type) iter.next())); } } if (buffer != null) { fSnippetStartPosition+= source.length(); } source.append(buildTypeBody(buffer, typeDeclaration.bodyDeclarations())); return source; } private StringBuffer buildCompilationUnit(StringBuffer buffer, CompilationUnit compilationUnit) { StringBuffer source = new StringBuffer(); PackageDeclaration packageDeclaration = compilationUnit.getPackage(); if (packageDeclaration != null) { source.append("package "); //$NON-NLS-1$ source.append(getQualifiedIdentifier(packageDeclaration.getName())); source.append(";\n"); //$NON-NLS-1$ } for (Iterator iterator = compilationUnit.imports().iterator(); iterator.hasNext();) { ImportDeclaration importDeclaration = (ImportDeclaration) iterator.next(); source.append("import "); //$NON-NLS-1$ if (importDeclaration.isStatic()) { source.append("static "); //$NON-NLS-1$ } source.append(getQualifiedIdentifier(importDeclaration.getName())); if (importDeclaration.isOnDemand()) { source.append(".*"); //$NON-NLS-1$ } source.append(";\n"); //$NON-NLS-1$ } fSnippetStartPosition += source.length(); source.append(buffer); for (Iterator iterator = compilationUnit.types().iterator(); iterator.hasNext();) { AbstractTypeDeclaration typeDeclaration = (AbstractTypeDeclaration) iterator.next(); if (Flags.isPublic(typeDeclaration.getModifiers())) { fCompilationUnitName = typeDeclaration.getName().getIdentifier(); } if (!fLastTypeName.equals(typeDeclaration.getName().getIdentifier())) { if (typeDeclaration instanceof TypeDeclaration) { source.append(buildTypeDeclaration(null, (TypeDeclaration)typeDeclaration)); } else if (typeDeclaration instanceof EnumDeclaration) { source.append(buildEnumDeclaration(null, (EnumDeclaration)typeDeclaration)); } } } if (fCompilationUnitName == null) { // If no public class was found, the compilation unit // name doesn't matter. fCompilationUnitName= "Eval"; //$NON-NLS-1$ } return source; } /** * Returns a method name that will be unique in the generated source. * The generated name is baseName plus as many '_' characters as necessary * to not duplicate an existing method name. */ private String getUniqueMethodName(String methodName, List bodyDeclarations) { Iterator iter= bodyDeclarations.iterator(); BodyDeclaration bodyDeclaration; MethodDeclaration method; String foundName; while (iter.hasNext()) { bodyDeclaration= (BodyDeclaration) iter.next(); if (bodyDeclaration instanceof MethodDeclaration) { method= (MethodDeclaration)bodyDeclaration; foundName= method.getName().getIdentifier(); if (foundName.startsWith(methodName)) { methodName= foundName + '_'; } } } return methodName; } /** * Returns a field name that will be unique in the generated source. * The generated name is baseName plus as many '_' characters as necessary * to not duplicate an existing method name. */ private String getUniqueFieldName(String fieldName, List bodyDeclarations) { Iterator iter= bodyDeclarations.iterator(); BodyDeclaration bodyDeclaration; FieldDeclaration fieldDeclaration; String foundName; while (iter.hasNext()) { bodyDeclaration= (BodyDeclaration) iter.next(); if (bodyDeclaration instanceof FieldDeclaration) { fieldDeclaration= (FieldDeclaration)bodyDeclaration; for (Iterator iterator= fieldDeclaration.fragments().iterator(); iterator.hasNext();) { foundName= ((VariableDeclarationFragment) iterator.next()).getName().getIdentifier(); if (foundName.startsWith(fieldName)) { fieldName= foundName + '_'; } } } } return fieldName; } private String getQualifiedIdentifier(Name name) { String typeName= ""; //$NON-NLS-1$ while (name.isQualifiedName()) { QualifiedName qualifiedName = (QualifiedName) name; typeName= "." + qualifiedName.getName().getIdentifier() + typeName; //$NON-NLS-1$ name= qualifiedName.getQualifier(); } if (name.isSimpleName()) { typeName= ((SimpleName)name).getIdentifier() + typeName; } else { return null; } return typeName; } public String getTypeName(Type type) { if (type.isSimpleType()) { return getQualifiedIdentifier(((SimpleType) type).getName()); } else if (type.isArrayType()) { return getTypeName(((ArrayType) type).getComponentType()) + "[]"; //$NON-NLS-1$ } else if (type.isPrimitiveType()) { return ((PrimitiveType) type).getPrimitiveTypeCode().toString(); } else if (type.isQualifiedType()) { QualifiedType qualifiedType= (QualifiedType) type; return getTypeName(qualifiedType.getQualifier()) + '.' + qualifiedType.getName().getIdentifier(); } else if (type.isParameterizedType()) { ParameterizedType parameterizedType= (ParameterizedType)type; StringBuffer buff= new StringBuffer(getTypeName(parameterizedType.getType())); Iterator iter= parameterizedType.typeArguments().iterator(); if (iter.hasNext()) { buff.append('<'); buff.append(getTypeName((Type)iter.next())); while (iter.hasNext()) { buff.append(','); buff.append(getTypeName((Type)iter.next())); } buff.append('>'); } return buff.toString(); } else if (type.isWildcardType()) { WildcardType wildcardType= (WildcardType)type; StringBuffer buff= new StringBuffer("?"); //$NON-NLS-1$ Type bound= wildcardType.getBound(); if (bound != null) { buff.append(wildcardType.isUpperBound() ? " extends " : " super "); //$NON-NLS-1$ //$NON-NLS-2$ buff.append(getTypeName(bound)); } return buff.toString(); } return null; } public String getReturnExpression(Type type) { if (type.isSimpleType() || type.isArrayType() || type.isQualifiedType() || type.isWildcardType() || type.isParameterizedType()) { return "return null;"; //$NON-NLS-1$ } else if (type.isPrimitiveType()) { String typeName= ((PrimitiveType) type).getPrimitiveTypeCode().toString(); char char0 = typeName.charAt(0); if (char0 == 'v') { return ""; //$NON-NLS-1$ } char char1 = typeName.charAt(1); if (char0 == 'b' && char1 == 'o') { return "return false;"; //$NON-NLS-1$ } return "return 0;"; //$NON-NLS-1$ } return null; } //---------------------- /** * @see ASTVisitor#endVisit(ClassInstanceCreation) */ public void endVisit(ClassInstanceCreation node) { if (hasError()) { return; } AnonymousClassDeclaration anonymousClassDeclaration = node.getAnonymousClassDeclaration(); if (anonymousClassDeclaration != null) { if (!rightTypeFound() && isRightType(node)) { setRightTypeFound(true); fSource= buildRunMethod(anonymousClassDeclaration.bodyDeclarations()); fEvaluateNextEndTypeDeclaration = true; } if (rightTypeFound()) { List bodyDeclarations= anonymousClassDeclaration.bodyDeclarations(); StringBuffer source = buildTypeBody(fSource, bodyDeclarations); ASTNode parent = node.getParent(); while (!(parent instanceof MethodDeclaration || parent instanceof FieldDeclaration)) { parent= parent.getParent(); } fSource= new StringBuffer(); if (parent instanceof MethodDeclaration) { MethodDeclaration enclosingMethodDeclaration = (MethodDeclaration) parent; if (Flags.isStatic(enclosingMethodDeclaration.getModifiers())) { fSource.append("static "); //$NON-NLS-1$ } fSource.append("void "); //$NON-NLS-1$ fSource.append(getUniqueMethodName(EVAL_METHOD_NAME, bodyDeclarations)); fSource.append("() {\n"); //$NON-NLS-1$ fSource.append("new "); //$NON-NLS-1$ fSource.append(getTypeName(node.getType())); fSource.append("()"); //$NON-NLS-1$ fSnippetStartPosition+= fSource.length(); fSource.append(source); fSource.append(";}\n"); //$NON-NLS-1$ } else if (parent instanceof FieldDeclaration) { FieldDeclaration enclosingFieldDeclaration = (FieldDeclaration) parent; if (Flags.isStatic(enclosingFieldDeclaration.getModifiers())) { fSource.append("static "); //$NON-NLS-1$ } Type type= enclosingFieldDeclaration.getType(); while (type instanceof ArrayType) { type= ((ArrayType)type).getComponentType(); } fSource.append(getQualifiedIdentifier(((SimpleType)type).getName())); fSource.append(' '); fSource.append(getUniqueFieldName(EVAL_FIELD_NAME, bodyDeclarations)); fSource.append(" = new "); //$NON-NLS-1$ fSource.append(getTypeName(node.getType())); fSource.append("()"); //$NON-NLS-1$ fSnippetStartPosition+= fSource.length(); fSource.append(source); fSource.append(";\n"); //$NON-NLS-1$ } fLastTypeName= ""; //$NON-NLS-1$ } } } /** * @see ASTVisitor#endVisit(CompilationUnit) */ public void endVisit(CompilationUnit node) { if (hasError()) { return; } if (!rightTypeFound()) { // if the right type hasn't been found fSource= null; return; } fSource = buildCompilationUnit(fSource, node); } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.EnumDeclaration) */ public void endVisit(EnumDeclaration node) { if (hasError()) { return; } if (!rightTypeFound() && isRightType(node)) { setRightTypeFound(true); fSource= buildRunMethod(node.bodyDeclarations()); fEvaluateNextEndTypeDeclaration = true; } if (!fEvaluateNextEndTypeDeclaration) { fEvaluateNextEndTypeDeclaration = true; return; } if (rightTypeFound()) { StringBuffer source = buildEnumDeclaration(fSource, node); if (node.isLocalTypeDeclaration()) { // enclose in a method if nessecary ASTNode parent = node.getParent(); while (!(parent instanceof MethodDeclaration)) { parent= parent.getParent(); } MethodDeclaration enclosingMethodDeclaration = (MethodDeclaration) parent; fSource = new StringBuffer(); if (Flags.isStatic(enclosingMethodDeclaration.getModifiers())) { fSource.append("static "); //$NON-NLS-1$ } fSource.append("void ___eval() {\n"); //$NON-NLS-1$ fSnippetStartPosition+= fSource.length(); fSource.append(source); fSource.append("}\n"); //$NON-NLS-1$ fLastTypeName = ""; //$NON-NLS-1$ } else { fSource = source; fLastTypeName = node.getName().getIdentifier(); } } } /** * @see ASTVisitor#endVisit(TypeDeclaration) */ public void endVisit(TypeDeclaration node) { if (hasError()) { return; } if (!rightTypeFound() && isRightType(node)) { setRightTypeFound(true); fSource= buildRunMethod(node.bodyDeclarations()); fEvaluateNextEndTypeDeclaration = true; } if (!fEvaluateNextEndTypeDeclaration) { fEvaluateNextEndTypeDeclaration = true; return; } if (rightTypeFound()) { StringBuffer source = buildTypeDeclaration(fSource, node); if (node.isLocalTypeDeclaration()) { // enclose in a method if nessecary ASTNode parent = node.getParent(); while (!(parent instanceof MethodDeclaration)) { parent= parent.getParent(); } MethodDeclaration enclosingMethodDeclaration = (MethodDeclaration) parent; fSource = new StringBuffer(); if (Flags.isStatic(enclosingMethodDeclaration.getModifiers())) { fSource.append("static "); //$NON-NLS-1$ } fSource.append("void ___eval() {\n"); //$NON-NLS-1$ fSnippetStartPosition+= fSource.length(); fSource.append(source); fSource.append("}\n"); //$NON-NLS-1$ fLastTypeName = ""; //$NON-NLS-1$ } else { fSource = source; fLastTypeName = node.getName().getIdentifier(); } } } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) */ public boolean visit(AnnotationTypeDeclaration node) { return false; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration) */ public boolean visit(AnnotationTypeMemberDeclaration node) { return false; } /** * @see ASTVisitor#visit(AnonymousClassDeclaration) */ public boolean visit(AnonymousClassDeclaration node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ArrayAccess) */ public boolean visit(ArrayAccess node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ArrayCreation) */ public boolean visit(ArrayCreation node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ArrayInitializer) */ public boolean visit(ArrayInitializer node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ArrayType) */ public boolean visit(ArrayType node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(AssertStatement) */ public boolean visit(AssertStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(Assignment) */ public boolean visit(Assignment node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(Block) */ public boolean visit(Block node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.BlockComment) */ public boolean visit(BlockComment node) { return false; } /** * @see ASTVisitor#visit(BooleanLiteral) */ public boolean visit(BooleanLiteral node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(BreakStatement) */ public boolean visit(BreakStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(CastExpression) */ public boolean visit(CastExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(CatchClause) */ public boolean visit(CatchClause node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(CharacterLiteral) */ public boolean visit(CharacterLiteral node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ClassInstanceCreation) */ public boolean visit(ClassInstanceCreation node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(CompilationUnit) */ public boolean visit(CompilationUnit node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ConditionalExpression) */ public boolean visit(ConditionalExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ConstructorInvocation) */ public boolean visit(ConstructorInvocation node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ContinueStatement) */ public boolean visit(ContinueStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(DoStatement) */ public boolean visit(DoStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(EmptyStatement) */ public boolean visit(EmptyStatement node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnhancedForStatement) */ public boolean visit(EnhancedForStatement node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnumConstantDeclaration) */ public boolean visit(EnumConstantDeclaration node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnumDeclaration) */ public boolean visit(EnumDeclaration node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ExpressionStatement) */ public boolean visit(ExpressionStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(FieldAccess) */ public boolean visit(FieldAccess node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(FieldDeclaration) */ public boolean visit(FieldDeclaration node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ForStatement) */ public boolean visit(ForStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(IfStatement) */ public boolean visit(IfStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ImportDeclaration) */ public boolean visit(ImportDeclaration node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(InfixExpression) */ public boolean visit(InfixExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(Initializer) */ public boolean visit(Initializer node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.InstanceofExpression) */ public boolean visit(InstanceofExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(Javadoc) */ public boolean visit(Javadoc node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(LabeledStatement) */ public boolean visit(LabeledStatement node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.LineComment) */ public boolean visit(LineComment node) { return false; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MarkerAnnotation) */ public boolean visit(MarkerAnnotation node) { return false; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MemberRef) */ public boolean visit(MemberRef node) { return false; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MemberValuePair) */ public boolean visit(MemberValuePair node) { return false; } /** * @see ASTVisitor#visit(MethodDeclaration) */ public boolean visit(MethodDeclaration node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(MethodInvocation) */ public boolean visit(MethodInvocation node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodRef) */ public boolean visit(MethodRef node) { return false; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodRefParameter) */ public boolean visit(MethodRefParameter node) { return false; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.Modifier) */ public boolean visit(Modifier node) { return false; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.NormalAnnotation) */ public boolean visit(NormalAnnotation node) { return false; } /** * @see ASTVisitor#visit(NullLiteral) */ public boolean visit(NullLiteral node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(NumberLiteral) */ public boolean visit(NumberLiteral node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(PackageDeclaration) */ public boolean visit(PackageDeclaration node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ParameterizedType) */ public boolean visit(ParameterizedType node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ParenthesizedExpression) */ public boolean visit(ParenthesizedExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(PostfixExpression) */ public boolean visit(PostfixExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(PrefixExpression) */ public boolean visit(PrefixExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(PrimitiveType) */ public boolean visit(PrimitiveType node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(QualifiedName) */ public boolean visit(QualifiedName node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.QualifiedType) */ public boolean visit(QualifiedType node) { return false; } /** * @see ASTVisitor#visit(ReturnStatement) */ public boolean visit(ReturnStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(SimpleName) */ public boolean visit(SimpleName node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(SimpleType) */ public boolean visit(SimpleType node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.SingleMemberAnnotation) */ public boolean visit(SingleMemberAnnotation node) { return false; } /** * @see ASTVisitor#visit(SingleVariableDeclaration) */ public boolean visit(SingleVariableDeclaration node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(StringLiteral) */ public boolean visit(StringLiteral node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(SuperConstructorInvocation) */ public boolean visit(SuperConstructorInvocation node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(SuperFieldAccess) */ public boolean visit(SuperFieldAccess node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(SuperMethodInvocation) */ public boolean visit(SuperMethodInvocation node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(SwitchCase) */ public boolean visit(SwitchCase node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(SwitchStatement) */ public boolean visit(SwitchStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(SynchronizedStatement) */ public boolean visit(SynchronizedStatement node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TagElement) */ public boolean visit(TagElement node) { return false; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TextElement) */ public boolean visit(TextElement node) { return false; } /** * @see ASTVisitor#visit(ThisExpression) */ public boolean visit(ThisExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(ThrowStatement) */ public boolean visit(ThrowStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(TryStatement) */ public boolean visit(TryStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(TypeDeclaration) */ public boolean visit(TypeDeclaration node) { if (rightTypeFound()) { fEvaluateNextEndTypeDeclaration = false; return false; } return true; } /** * @see ASTVisitor#visit(TypeDeclarationStatement) */ public boolean visit(TypeDeclarationStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(TypeLiteral) */ public boolean visit(TypeLiteral node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TypeParameter) */ public boolean visit(TypeParameter node) { return false; } /** * @see ASTVisitor#visit(VariableDeclarationExpression) */ public boolean visit(VariableDeclarationExpression node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(VariableDeclarationFragment) */ public boolean visit(VariableDeclarationFragment node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(VariableDeclarationStatement) */ public boolean visit(VariableDeclarationStatement node) { if (rightTypeFound()) { return false; } return true; } /** * @see ASTVisitor#visit(WhileStatement) */ public boolean visit(WhileStatement node) { if (rightTypeFound()) { return false; } return true; } /* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.WildcardType) */ public boolean visit(WildcardType node) { return false; } }
false
true
private StringBuffer buildTypeDeclaration(StringBuffer buffer, TypeDeclaration typeDeclaration) { StringBuffer source = new StringBuffer(); source.append(Flags.toString(typeDeclaration.getModifiers())); if (typeDeclaration.isInterface()) { source.append(" interface "); //$NON-NLS-1$ } else { source.append(" class "); //$NON-NLS-1$ } source.append(typeDeclaration.getName().getIdentifier()); List typeParameters= typeDeclaration.typeParameters(); if (!typeParameters.isEmpty()) { source.append('<'); Iterator iter= typeParameters.iterator(); TypeParameter typeParameter= (TypeParameter) iter.next(); source.append(typeParameter.getName().getIdentifier()); List typeBounds= typeParameter.typeBounds(); if (!typeBounds.isEmpty()) { source.append(" extends "); //$NON-NLS-1$ Iterator iter2= typeBounds.iterator(); source.append(getTypeName((Type) iter2.next())); while (iter.hasNext()) { source.append('&'); source.append(getTypeName((Type) iter2.next())); } } while (iter.hasNext()) { source.append(','); typeParameter= (TypeParameter) iter.next(); source.append(typeParameter.getName().getIdentifier()); typeBounds= typeParameter.typeBounds(); if (!typeBounds.isEmpty()) { source.append(" extends "); //$NON-NLS-1$ Iterator iter2= typeBounds.iterator(); source.append(getTypeName((Type) iter2.next())); while (iter.hasNext()) { source.append('&'); source.append(getTypeName((Type) iter2.next())); } } } source.append('>'); } Type superClass = typeDeclaration.getSuperclassType(); if (superClass != null) { source.append(" extends "); //$NON-NLS-1$ source.append(getTypeName(superClass)); } Iterator iter= typeDeclaration.superInterfaceTypes().iterator(); if (iter.hasNext()) { if (typeDeclaration.isInterface()) { source.append(" extends "); //$NON-NLS-1$ } else { source.append(" implements "); //$NON-NLS-1$ } source.append(getTypeName((Type) iter.next())); while (iter.hasNext()) { source.append(','); source.append(getTypeName((Type) iter.next())); } } if (buffer != null) { fSnippetStartPosition+= source.length(); } source.append(buildTypeBody(buffer, typeDeclaration.bodyDeclarations())); return source; }
private StringBuffer buildTypeDeclaration(StringBuffer buffer, TypeDeclaration typeDeclaration) { StringBuffer source = new StringBuffer(); source.append(Flags.toString(typeDeclaration.getModifiers())); if (typeDeclaration.isInterface()) { source.append(" interface "); //$NON-NLS-1$ } else { source.append(" class "); //$NON-NLS-1$ } source.append(typeDeclaration.getName().getIdentifier()); List typeParameters= typeDeclaration.typeParameters(); if (!typeParameters.isEmpty()) { source.append('<'); Iterator iter= typeParameters.iterator(); TypeParameter typeParameter= (TypeParameter) iter.next(); source.append(typeParameter.getName().getIdentifier()); List typeBounds= typeParameter.typeBounds(); if (!typeBounds.isEmpty()) { source.append(" extends "); //$NON-NLS-1$ Iterator iter2= typeBounds.iterator(); source.append(getTypeName((Type) iter2.next())); while (iter2.hasNext()) { source.append('&'); source.append(getTypeName((Type) iter2.next())); } } while (iter.hasNext()) { source.append(','); typeParameter= (TypeParameter) iter.next(); source.append(typeParameter.getName().getIdentifier()); typeBounds= typeParameter.typeBounds(); if (!typeBounds.isEmpty()) { source.append(" extends "); //$NON-NLS-1$ Iterator iter2= typeBounds.iterator(); source.append(getTypeName((Type) iter2.next())); while (iter2.hasNext()) { source.append('&'); source.append(getTypeName((Type) iter2.next())); } } } source.append('>'); } Type superClass = typeDeclaration.getSuperclassType(); if (superClass != null) { source.append(" extends "); //$NON-NLS-1$ source.append(getTypeName(superClass)); } Iterator iter= typeDeclaration.superInterfaceTypes().iterator(); if (iter.hasNext()) { if (typeDeclaration.isInterface()) { source.append(" extends "); //$NON-NLS-1$ } else { source.append(" implements "); //$NON-NLS-1$ } source.append(getTypeName((Type) iter.next())); while (iter.hasNext()) { source.append(','); source.append(getTypeName((Type) iter.next())); } } if (buffer != null) { fSnippetStartPosition+= source.length(); } source.append(buildTypeBody(buffer, typeDeclaration.bodyDeclarations())); return source; }
diff --git a/android/src/tw/edu/ttu/network/NetworkStatus.java b/android/src/tw/edu/ttu/network/NetworkStatus.java index 589b43d..1ba4295 100644 --- a/android/src/tw/edu/ttu/network/NetworkStatus.java +++ b/android/src/tw/edu/ttu/network/NetworkStatus.java @@ -1,31 +1,32 @@ package tw.edu.ttu.network; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; public class NetworkStatus { private WifiManager wifiManager; private WifiInfo wifiInfo; public NetworkStatus(Context context) { wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); } public void update() { wifiInfo = wifiManager.getConnectionInfo(); } public String getSSID() { update(); String ssid = wifiInfo.getSSID(); + if(ssid == null) return ""; if (ssid.startsWith("\"") && ssid.endsWith("\"")) { ssid = ssid.substring(1, ssid.length() - 1); } return ssid; } }
true
true
public String getSSID() { update(); String ssid = wifiInfo.getSSID(); if (ssid.startsWith("\"") && ssid.endsWith("\"")) { ssid = ssid.substring(1, ssid.length() - 1); } return ssid; }
public String getSSID() { update(); String ssid = wifiInfo.getSSID(); if(ssid == null) return ""; if (ssid.startsWith("\"") && ssid.endsWith("\"")) { ssid = ssid.substring(1, ssid.length() - 1); } return ssid; }
diff --git a/framework/src/main/java/org/radargun/stages/GarbageCollectionStage.java b/framework/src/main/java/org/radargun/stages/GarbageCollectionStage.java index 5e4d02d..cd06c07 100644 --- a/framework/src/main/java/org/radargun/stages/GarbageCollectionStage.java +++ b/framework/src/main/java/org/radargun/stages/GarbageCollectionStage.java @@ -1,31 +1,31 @@ package org.radargun.stages; import org.radargun.DistStageAck; import org.radargun.utils.Utils; /** * @author Diego Didona, [email protected] * Date: 25/12/12 */ /* This is needed because invoking System.gc() on a node while another one is populating may induce timeouts on that node, avoiding the completion of the warmup phase. This happens when the gc takes a long time wrt to the timeout */ public class GarbageCollectionStage extends AbstractDistStage { @Override public DistStageAck executeOnSlave() { DefaultDistStageAck defaultDistStageAck = newDefaultStageAck(); long start = System.currentTimeMillis(); log.info("Going to invoke the garbage collection"); - Utils.printMemoryFootprint(true); + log.info(Utils.printMemoryFootprint(true)); System.gc(); log.info("Garbage collection ended"); - Utils.printMemoryFootprint(false); + log.info(Utils.printMemoryFootprint(false)); long duration = System.currentTimeMillis() - start; defaultDistStageAck.setDuration(duration); return defaultDistStageAck; } }
false
true
public DistStageAck executeOnSlave() { DefaultDistStageAck defaultDistStageAck = newDefaultStageAck(); long start = System.currentTimeMillis(); log.info("Going to invoke the garbage collection"); Utils.printMemoryFootprint(true); System.gc(); log.info("Garbage collection ended"); Utils.printMemoryFootprint(false); long duration = System.currentTimeMillis() - start; defaultDistStageAck.setDuration(duration); return defaultDistStageAck; }
public DistStageAck executeOnSlave() { DefaultDistStageAck defaultDistStageAck = newDefaultStageAck(); long start = System.currentTimeMillis(); log.info("Going to invoke the garbage collection"); log.info(Utils.printMemoryFootprint(true)); System.gc(); log.info("Garbage collection ended"); log.info(Utils.printMemoryFootprint(false)); long duration = System.currentTimeMillis() - start; defaultDistStageAck.setDuration(duration); return defaultDistStageAck; }
diff --git a/src/plugins/WebOfTrust/WebOfTrust.java b/src/plugins/WebOfTrust/WebOfTrust.java index 4d83c642..85b21f70 100644 --- a/src/plugins/WebOfTrust/WebOfTrust.java +++ b/src/plugins/WebOfTrust/WebOfTrust.java @@ -1,3565 +1,3566 @@ /* This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. */ package plugins.WebOfTrust; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Random; import plugins.WebOfTrust.Identity.FetchState; import plugins.WebOfTrust.Identity.IdentityID; import plugins.WebOfTrust.Score.ScoreID; import plugins.WebOfTrust.Trust.TrustID; import plugins.WebOfTrust.exceptions.DuplicateIdentityException; import plugins.WebOfTrust.exceptions.DuplicateScoreException; import plugins.WebOfTrust.exceptions.DuplicateTrustException; import plugins.WebOfTrust.exceptions.InvalidParameterException; import plugins.WebOfTrust.exceptions.NotInTrustTreeException; import plugins.WebOfTrust.exceptions.NotTrustedException; import plugins.WebOfTrust.exceptions.UnknownIdentityException; import plugins.WebOfTrust.introduction.IntroductionClient; import plugins.WebOfTrust.introduction.IntroductionPuzzle; import plugins.WebOfTrust.introduction.IntroductionPuzzleStore; import plugins.WebOfTrust.introduction.IntroductionServer; import plugins.WebOfTrust.introduction.OwnIntroductionPuzzle; import plugins.WebOfTrust.ui.fcp.FCPInterface; import plugins.WebOfTrust.ui.web.WebInterface; import com.db4o.Db4o; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.defragment.Defragment; import com.db4o.defragment.DefragmentConfig; import com.db4o.ext.ExtObjectContainer; import com.db4o.query.Query; import com.db4o.reflect.jdk.JdkReflector; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.l10n.BaseL10n; import freenet.l10n.BaseL10n.LANGUAGE; import freenet.l10n.PluginL10n; import freenet.node.RequestClient; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.FredPluginBaseL10n; import freenet.pluginmanager.FredPluginFCP; import freenet.pluginmanager.FredPluginL10n; import freenet.pluginmanager.FredPluginRealVersioned; import freenet.pluginmanager.FredPluginThreadless; import freenet.pluginmanager.FredPluginVersioned; import freenet.pluginmanager.PluginReplySender; import freenet.pluginmanager.PluginRespirator; import freenet.support.CurrentTimeUTC; import freenet.support.Logger; import freenet.support.Logger.LogLevel; import freenet.support.SimpleFieldSet; import freenet.support.SizeUtil; import freenet.support.api.Bucket; import freenet.support.io.FileUtil; /** * A web of trust plugin based on Freenet. * * @author xor ([email protected]), Julien Cornuwel ([email protected]) */ public class WebOfTrust implements FredPlugin, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginRealVersioned, FredPluginL10n, FredPluginBaseL10n { /* Constants */ public static final boolean FAST_DEBUG_MODE = false; /** The relative path of the plugin on Freenet's web interface */ public static final String SELF_URI = "/WebOfTrust"; /** Package-private method to allow unit tests to bypass some assert()s */ /** * The "name" of this web of trust. It is included in the document name of identity URIs. For an example, see the SEED_IDENTITIES * constant below. The purpose of this constant is to allow anyone to create his own custom web of trust which is completely disconnected * from the "official" web of trust of the Freenet project. It is also used as the session cookie namespace. */ public static final String WOT_NAME = "WebOfTrust"; public static final String DATABASE_FILENAME = WOT_NAME + ".db4o"; public static final int DATABASE_FORMAT_VERSION = 2; /** * The official seed identities of the WoT plugin: If a newbie wants to download the whole offficial web of trust, he needs at least one * trust list from an identity which is well-connected to the web of trust. To prevent newbies from having to add this identity manually, * the Freenet development team provides a list of seed identities - each of them is one of the developers. */ private static final String[] SEED_IDENTITIES = new String[] { "USK@QeTBVWTwBldfI-lrF~xf0nqFVDdQoSUghT~PvhyJ1NE,OjEywGD063La2H-IihD7iYtZm3rC0BP6UTvvwyF5Zh4,AQACAAE/WebOfTrust/1344", // xor "USK@z9dv7wqsxIBCiFLW7VijMGXD9Gl-EXAqBAwzQ4aq26s,4Uvc~Fjw3i9toGeQuBkDARUV5mF7OTKoAhqOA9LpNdo,AQACAAE/WebOfTrust/1270", // Toad "USK@o2~q8EMoBkCNEgzLUL97hLPdddco9ix1oAnEa~VzZtg,X~vTpL2LSyKvwQoYBx~eleI2RF6QzYJpzuenfcKDKBM,AQACAAE/WebOfTrust/9379", // Bombe // "USK@cI~w2hrvvyUa1E6PhJ9j5cCoG1xmxSooi7Nez4V2Gd4,A3ArC3rrJBHgAJV~LlwY9kgxM8kUR2pVYXbhGFtid78,AQACAAE/WebOfTrust/19", // TheSeeker. Disabled because he is using LCWoT and it does not support identity introduction ATM. "USK@D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc,xgddjFHx2S~5U6PeFkwqO5V~1gZngFLoM-xaoMKSBI8,AQACAAE/WebOfTrust/4959", // zidel }; /* References from the node */ /** The node's interface to connect the plugin with the node, needed for retrieval of all other interfaces */ private PluginRespirator mPR; private static PluginL10n l10n; /* References from the plugin itself */ /* Database & configuration of the plugin */ private ExtObjectContainer mDB; private Configuration mConfig; private IntroductionPuzzleStore mPuzzleStore; /** Used for exporting identities, identity introductions and introduction puzzles to XML and importing them from XML. */ private XMLTransformer mXMLTransformer; private RequestClient mRequestClient; /* Worker objects which actually run the plugin */ /** * Clients can subscribe to certain events such as identity creation, trust changes, etc. with the {@link SubscriptionManager} */ private SubscriptionManager mSubscriptionManager; /** * Periodically wakes up and inserts any OwnIdentity which needs to be inserted. */ private IdentityInserter mInserter; /** * Fetches identities when it is told to do so by the plugin: * - At startup, all known identities are fetched * - When a new identity is received from a trust list it is fetched * - When a new identity is received by the IntrouductionServer it is fetched * - When an identity is manually added it is also fetched. * - ... */ private IdentityFetcher mFetcher; /** * Uploads captchas belonging to our own identities which others can solve to get on the trust list of them. Checks whether someone * uploaded solutions for them periodically and adds the new identities if a solution is received. */ private IntroductionServer mIntroductionServer; /** * Downloads captchas which the user can solve to announce his identities on other people's trust lists, provides the interface for * the UI to obtain the captchas and enter solutions. Uploads the solutions if the UI enters them. */ private IntroductionClient mIntroductionClient; /* Actual data of the WoT */ private boolean mFullScoreComputationNeeded = false; private boolean mTrustListImportInProgress = false; /* User interfaces */ private WebInterface mWebInterface; private FCPInterface mFCPInterface; /* Statistics */ private int mFullScoreRecomputationCount = 0; private long mFullScoreRecomputationMilliseconds = 0; private int mIncrementalScoreRecomputationCount = 0; private long mIncrementalScoreRecomputationMilliseconds = 0; /* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */ private static transient volatile boolean logDEBUG = false; private static transient volatile boolean logMINOR = false; static { Logger.registerClass(WebOfTrust.class); } public void runPlugin(PluginRespirator myPR) { try { Logger.normal(this, "Web Of Trust plugin version " + Version.getMarketingVersion() + " starting up..."); /* Catpcha generation needs headless mode on linux */ System.setProperty("java.awt.headless", "true"); mPR = myPR; /* TODO: This can be used for clean copies of the database to get rid of corrupted internal db4o structures. /* We should provide an option on the web interface to run this once during next startup and switch to the cloned database */ // cloneDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME), new File(getUserDataDirectory(), DATABASE_FILENAME + ".clone")); mDB = openDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() > WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("The WoT plugin's database format is newer than the WoT plugin which is being used."); mSubscriptionManager = new SubscriptionManager(this); mPuzzleStore = new IntroductionPuzzleStore(this); // Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager while this is executing. upgradeDB(); mXMLTransformer = new XMLTransformer(this); mRequestClient = new RequestClient() { public boolean persistent() { return false; } public void removeFrom(ObjectContainer container) { throw new UnsupportedOperationException(); } public boolean realTimeFlag() { return false; } }; mInserter = new IdentityInserter(this); mFetcher = new IdentityFetcher(this, getPluginRespirator()); // We only do this if debug logging is enabled since the integrity verification cannot repair anything anyway, // if the user does not read his logs there is no need to check the integrity. // TODO: Do this once every few startups and notify the user in the web ui if errors are found. if(logDEBUG) verifyDatabaseIntegrity(); // TODO: Only do this once every few startups once we are certain that score computation does not have any serious bugs. verifyAndCorrectStoredScores(); // Database is up now, integrity is checked. We can start to actually do stuff // TODO: This can be used for doing backups. Implement auto backup, maybe once a week or month //backupDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME + ".backup")); mSubscriptionManager.start(); createSeedIdentities(); Logger.normal(this, "Starting fetches of all identities..."); synchronized(this) { synchronized(mFetcher) { for(Identity identity : getAllIdentities()) { if(shouldFetchIdentity(identity)) { try { mFetcher.fetch(identity.getID()); } catch(Exception e) { Logger.error(this, "Fetching identity failed!", e); } } } } } mInserter.start(); mIntroductionServer = new IntroductionServer(this, mFetcher); mIntroductionServer.start(); mIntroductionClient = new IntroductionClient(this); mIntroductionClient.start(); mWebInterface = new WebInterface(this, SELF_URI); mFCPInterface = new FCPInterface(this); Logger.normal(this, "Web Of Trust plugin starting up completed."); } catch(RuntimeException e){ Logger.error(this, "Error during startup", e); /* We call it so the database is properly closed */ terminate(); throw e; } } /** * Constructor for being used by the node and unit tests. Does not do anything. */ public WebOfTrust() { } /** * Constructor which does not generate an IdentityFetcher, IdentityInster, IntroductionPuzzleStore, user interface, etc. * For use by the unit tests to be able to run WoT without a node. * @param databaseFilename The filename of the database. */ public WebOfTrust(String databaseFilename) { mDB = openDatabase(new File(databaseFilename)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Database format version mismatch. Found: " + mConfig.getDatabaseFormatVersion() + "; expected: " + WebOfTrust.DATABASE_FORMAT_VERSION); mPuzzleStore = new IntroductionPuzzleStore(this); mSubscriptionManager = new SubscriptionManager(this); mFetcher = new IdentityFetcher(this, null); } private File getUserDataDirectory() { final File wotDirectory = new File(mPR.getNode().getUserDir(), WOT_NAME); if(!wotDirectory.exists() && !wotDirectory.mkdir()) throw new RuntimeException("Unable to create directory " + wotDirectory); return wotDirectory; } private com.db4o.config.Configuration getNewDatabaseConfiguration() { com.db4o.config.Configuration cfg = Db4o.newConfiguration(); // Required config options: cfg.reflectWith(new JdkReflector(getPluginClassLoader())); // TODO: Optimization: We do explicit activation everywhere. We could change this to 0 and test whether everything still works. // Ideally, we would benchmark both 0 and 1 and make it configurable. cfg.activationDepth(1); cfg.updateDepth(1); // This must not be changed: We only activate(this, 1) before store(this). Logger.normal(this, "Default activation depth: " + cfg.activationDepth()); cfg.exceptionsOnNotStorable(true); // The shutdown hook does auto-commit. We do NOT want auto-commit: if a transaction hasn't commit()ed, it's not safe to commit it. cfg.automaticShutDown(false); // Performance config options: cfg.callbacks(false); // We don't use callbacks yet. TODO: Investigate whether we might want to use them cfg.classActivationDepthConfigurable(false); // Registration of indices (also performance) // ATTENTION: Also update cloneDatabase() when adding new classes! @SuppressWarnings("unchecked") final Class<? extends Persistent>[] persistentClasses = new Class[] { Configuration.class, Identity.class, OwnIdentity.class, Trust.class, Score.class, IdentityFetcher.IdentityFetcherCommand.class, IdentityFetcher.AbortFetchCommand.class, IdentityFetcher.StartFetchCommand.class, IdentityFetcher.UpdateEditionHintCommand.class, SubscriptionManager.Subscription.class, SubscriptionManager.IdentitiesSubscription.class, SubscriptionManager.ScoresSubscription.class, SubscriptionManager.TrustsSubscription.class, SubscriptionManager.Notification.class, SubscriptionManager.InitialSynchronizationNotification.class, SubscriptionManager.IdentityChangedNotification.class, SubscriptionManager.ScoreChangedNotification.class, SubscriptionManager.TrustChangedNotification.class, IntroductionPuzzle.class, OwnIntroductionPuzzle.class }; for(Class<? extends Persistent> clazz : persistentClasses) { boolean classHasIndex = clazz.getAnnotation(Persistent.IndexedClass.class) != null; // TODO: We enable class indexes for all classes to make sure nothing breaks because it is the db4o default, check whether enabling // them only for the classes where we need them does not cause any harm. classHasIndex = true; if(logDEBUG) Logger.debug(this, "Persistent class: " + clazz.getCanonicalName() + "; hasIndex==" + classHasIndex); // TODO: Make very sure that it has no negative side effects if we disable class indices for some classes // Maybe benchmark in comparison to a database which has class indices enabled for ALL classes. cfg.objectClass(clazz).indexed(classHasIndex); // Check the class' fields for @IndexedField annotations for(Field field : clazz.getDeclaredFields()) { if(field.getAnnotation(Persistent.IndexedField.class) != null) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + field.getName()); cfg.objectClass(clazz).objectField(field.getName()).indexed(true); } } // Check whether the class itself has an @IndexedField annotation final Persistent.IndexedField annotation = clazz.getAnnotation(Persistent.IndexedField.class); if(annotation != null) { for(String fieldName : annotation.names()) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + fieldName); cfg.objectClass(clazz).objectField(fieldName).indexed(true); } } } // TODO: We should check whether db4o inherits the indexed attribute to child classes, for example for this one: // Unforunately, db4o does not provide any way to query the indexed() property of fields, you can only set it // We might figure out whether inheritance works by writing a benchmark. return cfg; } private synchronized void restoreDatabaseBackup(File databaseFile, File backupFile) throws IOException { Logger.warning(this, "Trying to restore database backup: " + backupFile.getAbsolutePath()); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(backupFile.exists()) { try { FileUtil.secureDelete(databaseFile, mPR.getNode().fastWeakRandom); } catch(IOException e) { Logger.warning(this, "Deleting of the database failed: " + databaseFile.getAbsolutePath()); } if(backupFile.renameTo(databaseFile)) { Logger.warning(this, "Backup restored!"); } else { throw new IOException("Unable to rename backup file back to database file: " + databaseFile.getAbsolutePath()); } } else { throw new IOException("Cannot restore backup, it does not exist!"); } } private synchronized void defragmentDatabase(File databaseFile) throws IOException { Logger.normal(this, "Defragmenting database ..."); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(mPR == null) { Logger.normal(this, "No PluginRespirator found, probably running as unit test, not defragmenting."); return; } final Random random = mPR.getNode().fastWeakRandom; // Open it first, because defrag will throw if it needs to upgrade the file. { final ObjectContainer database = Db4o.openFile(getNewDatabaseConfiguration(), databaseFile.getAbsolutePath()); // Db4o will throw during defragmentation if new fields were added to classes and we didn't initialize their values on existing // objects before defragmenting. So we just don't defragment if the database format version has changed. final boolean canDefragment = peekDatabaseFormatVersion(this, database.ext()) == WebOfTrust.DATABASE_FORMAT_VERSION; while(!database.close()); if(!canDefragment) { Logger.normal(this, "Not defragmenting, database format version changed!"); return; } if(!databaseFile.exists()) { Logger.error(this, "Database file does not exist after openFile: " + databaseFile.getAbsolutePath()); return; } } final File backupFile = new File(databaseFile.getAbsolutePath() + ".backup"); if(backupFile.exists()) { Logger.error(this, "Not defragmenting database: Backup file exists, maybe the node was shot during defrag: " + backupFile.getAbsolutePath()); return; } final File tmpFile = new File(databaseFile.getAbsolutePath() + ".temp"); FileUtil.secureDelete(tmpFile, random); /* As opposed to the default, BTreeIDMapping uses an on-disk file instead of in-memory for mapping IDs. /* Reduces memory usage during defragmentation while being slower. /* However as of db4o 7.4.63.11890, it is bugged and prevents defragmentation from succeeding for my database, so we don't use it for now. */ final DefragmentConfig config = new DefragmentConfig(databaseFile.getAbsolutePath(), backupFile.getAbsolutePath() // ,new BTreeIDMapping(tmpFile.getAbsolutePath()) ); /* Delete classes which are not known to the classloader anymore - We do NOT do this because: /* - It is buggy and causes exceptions often as of db4o 7.4.63.11890 /* - WOT has always had proper database upgrade code (function upgradeDB()) and does not rely on automatic schema evolution. /* If we need to get rid of certain objects we should do it in the database upgrade code, */ // config.storedClassFilter(new AvailableClassFilter()); config.db4oConfig(getNewDatabaseConfiguration()); try { Defragment.defrag(config); } catch (Exception e) { Logger.error(this, "Defragment failed", e); try { restoreDatabaseBackup(databaseFile, backupFile); return; } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e); } } final long oldSize = backupFile.length(); final long newSize = databaseFile.length(); if(newSize <= 0) { Logger.error(this, "Defrag produced an empty file! Trying to restore old database file..."); databaseFile.delete(); try { restoreDatabaseBackup(databaseFile, backupFile); } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e2); } } else { final double change = 100.0 * (((double)(oldSize - newSize)) / ((double)oldSize)); FileUtil.secureDelete(tmpFile, random); FileUtil.secureDelete(backupFile, random); Logger.normal(this, "Defragment completed. "+SizeUtil.formatSize(oldSize)+" ("+oldSize+") -> " +SizeUtil.formatSize(newSize)+" ("+newSize+") ("+(int)change+"% shrink)"); } } /** * ATTENTION: This function is duplicated in the Freetalk plugin, please backport any changes. * * Initializes the plugin's db4o database. */ private synchronized ExtObjectContainer openDatabase(File file) { Logger.normal(this, "Opening database using db4o " + Db4o.version()); if(mDB != null) throw new RuntimeException("Database is opened already!"); try { defragmentDatabase(file); } catch (IOException e) { throw new RuntimeException(e); } return Db4o.openFile(getNewDatabaseConfiguration(), file.getAbsolutePath()).ext(); } /** * ATTENTION: Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager while this is executing. * It doesn't synchronize on the IntroductionPuzzleStore / IdentityFetcher / SubscriptionManager because it assumes that they are not being used yet. * (I didn't upgrade this function to do the locking because it would be much work to test the changes for little benefit) */ @SuppressWarnings("deprecation") private synchronized void upgradeDB() { int databaseVersion = mConfig.getDatabaseFormatVersion(); if(databaseVersion == WebOfTrust.DATABASE_FORMAT_VERSION) return; // Insert upgrade code here. See Freetalk.java for a skeleton. if(databaseVersion == 1) { Logger.normal(this, "Upgrading database version " + databaseVersion); //synchronized(this) { // Already done at function level //synchronized(mPuzzleStore) { // Normally would be needed for deleteWithoutCommit(Identity) but IntroductionClient/Server are not running yet //synchronized(mFetcher) { // Normally would be needed for deleteWithoutCommit(Identity) but the IdentityFetcher is not running yet //synchronized(mSubscriptionManager) { // Normally would be needed for deleteWithoutCommit(Identity) but the SubscriptionManager is not running yet synchronized(Persistent.transactionLock(mDB)) { try { Logger.normal(this, "Generating Score IDs..."); for(Score score : getAllScores()) { score.generateID(); score.storeWithoutCommit(); } Logger.normal(this, "Generating Trust IDs..."); for(Trust trust : getAllTrusts()) { trust.generateID(); trust.storeWithoutCommit(); } Logger.normal(this, "Searching for identities with mixed up insert/request URIs..."); for(Identity identity : getAllIdentities()) { try { USK.create(identity.getRequestURI()); } catch (MalformedURLException e) { if(identity instanceof OwnIdentity) { Logger.error(this, "Insert URI specified as request URI for OwnIdentity, not correcting the URIs as the insert URI" + "might have been published by solving captchas - the identity could be compromised: " + identity); } else { Logger.error(this, "Insert URI specified as request URI for non-own Identity, deleting: " + identity); deleteWithoutCommit(identity); } } } mConfig.setDatabaseFormatVersion(++databaseVersion); mConfig.storeAndCommit(); Logger.normal(this, "Upgraded database to version " + databaseVersion); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } //} } if(databaseVersion != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Your database is too outdated to be upgraded automatically, please create a new one by deleting " + DATABASE_FILENAME + ". Contact the developers if you really need your old data."); } /** * DO NOT USE THIS FUNCTION ON A DATABASE WHICH YOU WANT TO CONTINUE TO USE! * * Debug function for finding object leaks in the database. * * - Deletes all identities in the database - This should delete ALL objects in the database. * - Then it checks for whether any objects still exist - those are leaks. */ private synchronized void checkForDatabaseLeaks() { Logger.normal(this, "Checking for database leaks... This will delete all identities!"); { Logger.debug(this, "Checking FetchState leakage..."); final Query query = mDB.query(); query.constrain(FetchState.class); @SuppressWarnings("unchecked") ObjectSet<FetchState> result = (ObjectSet<FetchState>)query.execute(); for(FetchState state : result) { Logger.debug(this, "Checking " + state); final Query query2 = mDB.query(); query2.constrain(Identity.class); query.descend("mCurrentEditionFetchState").constrain(state).identity(); @SuppressWarnings("unchecked") ObjectSet<FetchState> result2 = (ObjectSet<FetchState>)query.execute(); switch(result2.size()) { case 0: Logger.error(this, "Found leaked FetchState!"); break; case 1: break; default: Logger.error(this, "Found re-used FetchState, count: " + result2.size()); break; } } Logger.debug(this, "Finished checking FetchState leakage, amount:" + result.size()); } Logger.normal(this, "Deleting ALL identities..."); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { beginTrustListImport(); for(Identity identity : getAllIdentities()) { deleteWithoutCommit(identity); } finishTrustListImport(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); // abortTrustListImport() does rollback already // Persistent.checkedRollbackAndThrow(mDB, this, e); throw e; } } } } } Logger.normal(this, "Deleting ALL identities finished."); Query query = mDB.query(); query.constrain(Object.class); @SuppressWarnings("unchecked") ObjectSet<Object> result = query.execute(); for(Object leak : result) { Logger.error(this, "Found leaked object: " + leak); } Logger.warning(this, "Finished checking for database leaks. This database is empty now, delete it."); } private synchronized boolean verifyDatabaseIntegrity() { // Take locks of all objects which deal with persistent stuff because we act upon ALL persistent objects. synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { deleteDuplicateObjects(); deleteOrphanObjects(); Logger.debug(this, "Testing database integrity..."); final Query q = mDB.query(); q.constrain(Persistent.class); boolean result = true; for(final Persistent p : new Persistent.InitializingObjectSet<Persistent>(this, q)) { try { p.startupDatabaseIntegrityTest(); } catch(Exception e) { result = false; try { Logger.error(this, "Integrity test failed for " + p, e); } catch(Exception e2) { Logger.error(this, "Integrity test failed for Persistent of class " + p.getClass(), e); Logger.error(this, "Exception thrown by toString() was:", e2); } } } Logger.debug(this, "Database integrity test finished."); return result; } } } } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Does a backup of the database using db4o's backup mechanism. * * This will NOT fix corrupted internal structures of databases - use cloneDatabase if you need to fix your database. */ private synchronized void backupDatabase(File newDatabase) { Logger.normal(this, "Backing up database to " + newDatabase.getAbsolutePath()); if(newDatabase.exists()) throw new RuntimeException("Target exists already: " + newDatabase.getAbsolutePath()); WebOfTrust backup = null; boolean success = false; try { mDB.backup(newDatabase.getAbsolutePath()); if(logDEBUG) { backup = new WebOfTrust(newDatabase.getAbsolutePath()); // We do not throw to make the clone mechanism more robust in case it is being used for creating backups Logger.debug(this, "Checking database integrity of clone..."); if(backup.verifyDatabaseIntegrity()) Logger.debug(this, "Checking database integrity of clone finished."); else Logger.error(this, "Database integrity check of clone failed!"); Logger.debug(this, "Checking this.equals(clone)..."); if(equals(backup)) Logger.normal(this, "Clone is equal!"); else Logger.error(this, "Clone is not equal!"); } success = true; } finally { if(backup != null) backup.terminate(); if(!success) newDatabase.delete(); } Logger.normal(this, "Backing up database finished."); } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Creates a clone of the source database by reading all objects of it into memory and then writing them out to the target database. * Does NOT copy the Configuration, the IntroductionPuzzles or the IdentityFetcher command queue. * * The difference to backupDatabase is that it does NOT use db4o's backup mechanism, instead it creates the whole database from scratch. * This is useful because the backup mechanism of db4o does nothing but copying the raw file: * It wouldn't fix databases which cannot be defragmented anymore due to internal corruption. * - Databases which were cloned by this function CAN be defragmented even if the original database couldn't. * * HOWEVER this function uses lots of memory as the whole database is copied into memory. */ private synchronized void cloneDatabase(File sourceDatabase, File targetDatabase) { Logger.normal(this, "Cloning " + sourceDatabase.getAbsolutePath() + " to " + targetDatabase.getAbsolutePath()); if(targetDatabase.exists()) throw new RuntimeException("Target exists already: " + targetDatabase.getAbsolutePath()); WebOfTrust original = null; WebOfTrust clone = null; boolean success = false; try { original = new WebOfTrust(sourceDatabase.getAbsolutePath()); // We need to copy all objects into memory and then close & unload the source database before writing the objects to the target one. // - I tried implementing this function in a way where it directly takes the objects from the source database and stores them // in the target database while the source is still open. This did not work: Identity objects disappeared magically, resulting // in Trust objects .storeWithoutCommit throwing "Mandatory object not found" on their associated identities. // FIXME: Clone the Configuration object final HashSet<Identity> allIdentities = new HashSet<Identity>(original.getAllIdentities()); final HashSet<Trust> allTrusts = new HashSet<Trust>(original.getAllTrusts()); final HashSet<Score> allScores = new HashSet<Score>(original.getAllScores()); for(Identity identity : allIdentities) { identity.checkedActivate(16); identity.mWebOfTrust = null; identity.mDB = null; } for(Trust trust : allTrusts) { trust.checkedActivate(16); trust.mWebOfTrust = null; trust.mDB = null; } for(Score score : allScores) { score.checkedActivate(16); score.mWebOfTrust = null; score.mDB = null; } // We don't clone: // - Introduction puzzles because we can just download new ones // - IdentityFetcher commands because they aren't persistent across startups anyway // - Subscription and Notification objects because subscriptions are also not persistent across startups. original.terminate(); original = null; System.gc(); // Now we write out the in-memory copies ... clone = new WebOfTrust(targetDatabase.getAbsolutePath()); for(Identity identity : allIdentities) { identity.initializeTransient(clone); identity.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Trust trust : allTrusts) { trust.initializeTransient(clone); trust.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Score score : allScores) { score.initializeTransient(clone); score.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); // And because cloning is a complex operation we do a mandatory database integrity check Logger.normal(this, "Checking database integrity of clone..."); if(clone.verifyDatabaseIntegrity()) Logger.normal(this, "Checking database integrity of clone finished."); else throw new RuntimeException("Database integrity check of clone failed!"); // ... and also test whether the Web Of Trust is equals() to the clone. This does a deep check of all identities, scores & trusts! original = new WebOfTrust(sourceDatabase.getAbsolutePath()); Logger.normal(this, "Checking original.equals(clone)..."); if(original.equals(clone)) Logger.normal(this, "Clone is equal!"); else throw new RuntimeException("Clone is not equal!"); success = true; } finally { if(original != null) original.terminate(); if(clone != null) clone.terminate(); if(!success) targetDatabase.delete(); } Logger.normal(this, "Cloning database finished."); } /** * Recomputes the {@link Score} of all identities and checks whether the score which is stored in the database is correct. * Incorrect scores are corrected & stored. * * The function is synchronized and does a transaction, no outer synchronization is needed. */ protected synchronized void verifyAndCorrectStoredScores() { Logger.normal(this, "Veriying all stored scores ..."); synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "Veriying all stored scores finished."); } /** * Debug function for deleting duplicate identities etc. which might have been created due to bugs :) */ private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { + * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } - * }}} + * }}}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
false
true
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteWithoutCommit(Identity) synchronized(mFetcher) { // Needed for deleteWithoutCommit(Identity) synchronized(mSubscriptionManager) { // Needed for deleteWithoutCommit(Identity) synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { } // synchronized(mPuzzleStore) { // synchronized(this) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() / removeTrustWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mSubscriptionManager) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); // No need to update subscriptions as the trust is broken anyway. } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For computeAllScoresWithoutCommit(). Done at function level already. synchronized(mFetcher) { // For computeAllScoresWithoutCommit() synchronized(mSubscriptionManager) { // For computeAllScoresWithoutCommit() synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); // No need to update subscriptions as the score is broken anyway. } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ private int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { // FIXME: The comment "Security check, if rank computation breaks this will hit." below sounds like we don't actually // need to execute this because the callers probably do it implicitly. Check if this is true and if yes, convert it to an assert. if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(mSubscriptionManager) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}}} * </code> * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(currentStoredScore, null); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); final Score oldScore = currentStoredScore.clone(); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, currentStoredScore); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, newScore); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(target); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { synchronized(mSubscriptionManager) { for(String seedURI : SEED_IDENTITIES) { synchronized(Persistent.transactionLock(mDB)) { try { final Identity existingSeed = getIdentityByURI(seedURI); final Identity oldExistingSeed = existingSeed.clone(); // For the SubscriptionManager if(existingSeed instanceof OwnIdentity) { final OwnIdentity ownExistingSeed = (OwnIdentity)existingSeed; ownExistingSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownExistingSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, ownExistingSeed); ownExistingSeed.storeAndCommit(); } else { try { existingSeed.setEdition(new FreenetURI(seedURI).getEdition()); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldExistingSeed, existingSeed); existingSeed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { final Identity newSeed = new Identity(this, seedURI, null, true); // We have to explicitly set the edition number because the constructor only considers the given edition as a hint. newSeed.setEdition(new FreenetURI(seedURI).getEdition()); newSeed.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, newSeed); Persistent.checkedCommit(mDB, this); } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mSubscriptionManager != null) mSubscriptionManager.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore, the IdentityFetcher and the SubscriptionManager before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) { score.deleteWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(score, null); } } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); } if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(givenTrust, null); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(identity, null); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(oldTrust, trust); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(null, trust); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); // TODO: Mabye notify clients about this. IMHO it would create too much notifications on trust list import so we don't. // As soon as we have notification-coalescing we might do it. // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(truster); } /** * Only for being used by WoT internally and by unit tests! * * You have to synchronize on this WebOfTrust while querying the parameter identities and calling this function. */ void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); mSubscriptionManager.storeTrustChangedNotificationWithoutCommit(trust, null); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(null, score); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when {@link #finishTrustListImport()} is called. * * ATTENTION: Always take care to call one of {@link #finishTrustListImport()} / {@link #abortTrustListImport(Exception)} / {@link #abortTrustListImport(Exception, LogLevel)} * for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e, Logger.LogLevel.ERROR); // Does checkedRollback() for you already } * }}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Aborts the import of a trust list import and undoes all changes by it. * * ATTENTION: In opposite to finishTrustListImport(), which does not commit the transaction, this rolls back the transaction. * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * Finishes the import of the current trust list and performs score computation. * * ATTENTION: In opposite to abortTrustListImport(), which rolls back the transaction, this does NOT commit the transaction. You have to do it! * ATTENTION: Always take care to call {@link #beginTrustListImport()} for each call to this function. * * Synchronization: * This function does neither lock the database nor commit the transaction. You have to surround it with: * <code> * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { beginTrustListImport(); ... finishTrustListImport(); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { abortTrustListImport(e); // Does checkedRollback() for you already } * }}} * </code> */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link #computeAllScoresWithoutCommit()} * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; boolean scoreExistedBefore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); scoreExistedBefore = true; } catch(NotInTrustTreeException e) { scoreExistedBefore = false; currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) { currentStoredTrusteeScore.storeWithoutCommit(); mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(scoreExistedBefore ? oldScore : null, currentStoredTrusteeScore); } // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); // We don't notify clients about this because the WOT fetch state is of little interest to them, they determine theirs from the Score // mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(trustee); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); synchronized(Persistent.transactionLock(mDB)) { try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e2) { Persistent.checkedRollbackAndThrow(mDB, this, e2); } } // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. Logger.normal(this, "addIdentity(): " + identity); return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(mFetcher) { // For beginTrustListImport()/setTrustWithoutCommit() synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); // Nothing has changed about the actual score so we do not notify. // mSubscriptionManager.storeScoreChangedNotificationWithoutCommit(oldScore, newScore); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(null, identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { if(mTrustListImportInProgress) { // We don't execute beginTrustListImport() in all code paths of this function abortTrustListImport(e); // Does rollback for us throw e; } else { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } /** * Enables or disables the publishing of the trust list of an {@link OwnIdentity}. * The trust list contains all trust values which the OwnIdentity has assigned to other identities. * * @see OwnIdentity#setPublishTrustList(boolean) * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishTrustList Whether to publish the trust list. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given {@link Identity.IdentityID}. */ public synchronized void setPublishTrustList(final String ownIdentityID, final boolean publishTrustList) throws UnknownIdentityException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setPublishTrustList(publishTrustList); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "setPublishTrustList to " + publishTrustList + " for " + identity); } /** * Enables or disables the publishing of {@link IntroductionPuzzle}s for an {@link OwnIdentity}. * * If publishIntroductionPuzzles==true adds, if false removes: * - the context {@link IntroductionPuzzle.INTRODUCTION_CONTEXT} * - the property {@link IntroductionServer.PUZZLE_COUNT_PROPERTY} with the value {@link IntroductionServer.DEFAULT_PUZZLE_COUNT} * * @param ownIdentityID The {@link Identity.IdentityID} of the {@link OwnIdentity} you want to modify. * @param publishIntroductionPuzzles Whether to publish introduction puzzles. * @throws UnknownIdentityException If there is no identity with the given ownIdentityID * @throws InvalidParameterException If {@link OwnIdentity#doesPublishTrustList()} returns false on the selected identity: It doesn't make sense for an identity to allow introduction if it doesn't publish a trust list - the purpose of introduction is to add other identities to your trust list. */ public synchronized void setPublishIntroductionPuzzles(final String ownIdentityID, final boolean publishIntroductionPuzzles) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager if(!identity.doesPublishTrustList()) throw new InvalidParameterException("An identity must publish its trust list if it wants to publish introduction puzzles!"); synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { if(publishIntroductionPuzzles) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } else { identity.removeContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); identity.removeProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY); } mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } Logger.normal(this, "Set publishIntroductionPuzzles to " + true + " for " + identity); } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.addContext(newContext); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeContext(context); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.setProperty(property, value); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final OwnIdentity identity = getOwnIdentityByID(ownIdentityID); final OwnIdentity oldIdentity = identity.clone(); // For the SubscriptionManager synchronized(mSubscriptionManager) { synchronized(Persistent.transactionLock(mDB)) { try { identity.removeProperty(property); mSubscriptionManager.storeIdentityChangedNotificationWithoutCommit(oldIdentity, identity); identity.storeAndCommit(); } catch(RuntimeException e){ Persistent.checkedRollbackAndThrow(mDB, this, e); } } } if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public SubscriptionManager getSubscriptionManager() { return mSubscriptionManager; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } protected FCPInterface getFCPInterface() { return mFCPInterface; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
diff --git a/lipreading-android/src/edu/lipreading/android/SettingsFragment.java b/lipreading-android/src/edu/lipreading/android/SettingsFragment.java index c44f23f..50ed87e 100644 --- a/lipreading-android/src/edu/lipreading/android/SettingsFragment.java +++ b/lipreading-android/src/edu/lipreading/android/SettingsFragment.java @@ -1,99 +1,99 @@ package edu.lipreading.android; import java.util.List; import java.util.Locale; import java.util.Vector; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.preference.ListPreference; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import edu.lipreading.Constants; /* * Created with IntelliJ IDEA. * User: Sagi * Date: 23/03/13 * Time: 14:32 */ public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{ private LipReadingActivity context; public SettingsFragment(){ super(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); setPreferenceScreen((PreferenceScreen) findPreference("screen")); ListPreference vocabularyPref = (ListPreference) findPreference("vocabularyPref"); List<String> words = new Vector<String>(Constants.VOCABULARY); for (int i = 0; i < words.size(); i++) { words.set(i, context.makePretty(words.get(i))); } String[] entries = words.toArray(new String[words.size()]); vocabularyPref.setEntries(entries); vocabularyPref.setEntryValues(entries); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); view.setBackgroundColor(Color.BLACK); return view; } @Override public void onResume() { super.onResume(); getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); super.onPause(); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { SharedPreferences preferences = context.getPreferences(Context.MODE_PRIVATE); if(key.equals(getString(R.string.trainingModePref))){ boolean trainingModePref = sharedPreferences.getBoolean(getString(R.string.trainingModePref), false); context.setTrainingMode(trainingModePref); preferences.edit().putBoolean(key, trainingModePref).apply(); } else if(key.equals(getString(R.string.voiceTypePref))){ String defaultVoice = getResources().getString(R.string.male); - String voiceTypePref = sharedPreferences.getString(getString(R.string.trainingModePref), defaultVoice); + String voiceTypePref = sharedPreferences.getString(getString(R.string.voiceTypePref), defaultVoice); if(defaultVoice.equals(voiceTypePref)){ this.context.getTts().setLanguage(Locale.UK); } else { this.context.getTts().setLanguage(Locale.US); } preferences.edit().putString(key, voiceTypePref).apply(); } else if(key.equals(getString(R.string.serverPref))){ String currentUrl = sharedPreferences.getString(getString(R.string.serverPref), getString(R.string.serverDef)); this.context.setUri(currentUrl); preferences.edit().putString(key, currentUrl).apply(); } } public SettingsFragment setContext(LipReadingActivity context){ this.context = context; return this; } }
true
true
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { SharedPreferences preferences = context.getPreferences(Context.MODE_PRIVATE); if(key.equals(getString(R.string.trainingModePref))){ boolean trainingModePref = sharedPreferences.getBoolean(getString(R.string.trainingModePref), false); context.setTrainingMode(trainingModePref); preferences.edit().putBoolean(key, trainingModePref).apply(); } else if(key.equals(getString(R.string.voiceTypePref))){ String defaultVoice = getResources().getString(R.string.male); String voiceTypePref = sharedPreferences.getString(getString(R.string.trainingModePref), defaultVoice); if(defaultVoice.equals(voiceTypePref)){ this.context.getTts().setLanguage(Locale.UK); } else { this.context.getTts().setLanguage(Locale.US); } preferences.edit().putString(key, voiceTypePref).apply(); } else if(key.equals(getString(R.string.serverPref))){ String currentUrl = sharedPreferences.getString(getString(R.string.serverPref), getString(R.string.serverDef)); this.context.setUri(currentUrl); preferences.edit().putString(key, currentUrl).apply(); } }
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { SharedPreferences preferences = context.getPreferences(Context.MODE_PRIVATE); if(key.equals(getString(R.string.trainingModePref))){ boolean trainingModePref = sharedPreferences.getBoolean(getString(R.string.trainingModePref), false); context.setTrainingMode(trainingModePref); preferences.edit().putBoolean(key, trainingModePref).apply(); } else if(key.equals(getString(R.string.voiceTypePref))){ String defaultVoice = getResources().getString(R.string.male); String voiceTypePref = sharedPreferences.getString(getString(R.string.voiceTypePref), defaultVoice); if(defaultVoice.equals(voiceTypePref)){ this.context.getTts().setLanguage(Locale.UK); } else { this.context.getTts().setLanguage(Locale.US); } preferences.edit().putString(key, voiceTypePref).apply(); } else if(key.equals(getString(R.string.serverPref))){ String currentUrl = sharedPreferences.getString(getString(R.string.serverPref), getString(R.string.serverDef)); this.context.setUri(currentUrl); preferences.edit().putString(key, currentUrl).apply(); } }
diff --git a/loci/formats/in/OIFReader.java b/loci/formats/in/OIFReader.java index bcdc39c41..4e06aa769 100644 --- a/loci/formats/in/OIFReader.java +++ b/loci/formats/in/OIFReader.java @@ -1,300 +1,300 @@ // // OIFReader.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-2006 Melissa Linkert, Curtis Rueden, Chris Allan and Eric Kjellman. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.awt.image.BufferedImage; import java.io.*; import java.util.Hashtable; import java.util.Vector; import loci.formats.*; /** * OIFReader is the file format reader for Fluoview FV 1000 OIF files. * * @author Melissa Linkert linkert at cs.wisc.edu */ public class OIFReader extends FormatReader { // -- Fields -- /** Current file. */ protected BufferedReader reader; /** Number of image planes in the file. */ protected int numImages = 0; /** Names of every TIFF file to open. */ protected Vector tiffs; /** Helper reader to open TIFF files. */ protected TiffReader tiffReader; // -- Constructor -- /** Constructs a new OIF reader. */ public OIFReader() { super("Fluoview FV1000 OIF", new String[] {"oif", "roi", "pty", "lut", "bmp"}); } // -- FormatReader API methods -- /** Checks if the given block is a valid header for an OIF file. */ public boolean isThisType(byte[] block) { return false; } /** Determines the number of images in the given OIF file. */ public int getImageCount(String id) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } return isRGB(id) ? 3*numImages : numImages; } /** * Obtains the specified metadata field's value for the given file. * * @param field the name associated with the metadata field * @return the value, or null if the field doesn't exist */ public Object getMetadataValue(String id, String field) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } return metadata.get(field); } /** Checks if the images in the file are RGB. */ public boolean isRGB(String id) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } return tiffReader.isRGB((String) tiffs.get(0)); } /** Get the size of the X dimension. */ public int getSizeX(String id) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } return Integer.parseInt((String) metadata.get("ImageWidth")); } /** Get the size of the Y dimension. */ public int getSizeY(String id) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } return Integer.parseInt((String) metadata.get("ImageHeight")); } /** Get the size of the Z dimension. */ public int getSizeZ(String id) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } return numImages; } /** Get the size of the C dimension. */ public int getSizeC(String id) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } return isRGB(id) ? 3 : 1; } /** Get the size of the T dimension. */ public int getSizeT(String id) throws FormatException, IOException { return 1; } /** Return true if the data is in little-endian format. */ public boolean isLittleEndian(String id) throws FormatException, IOException { return true; } /** * Return a five-character string representing the dimension order * within the file. */ public String getDimensionOrder(String id) throws FormatException, IOException { return "XYZTC"; } /** Obtains the specified image from the given OIF file as a byte array. */ public byte[] openBytes(String id, int no) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } return tiffReader.openBytes((String) tiffs.get(no), 0); } /** Obtains the specified image from the given OIF file. */ public BufferedImage openImage(String id, int no) throws FormatException, IOException { if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) { initFile(id); } if (no < 0 || no >= getImageCount(id)) { throw new FormatException("Invalid image number: " + no); } return tiffReader.openImage((String) tiffs.get(no), 0); } /** Closes any open files. */ public void close() throws FormatException, IOException { if (reader != null) reader.close(); reader = null; currentId = null; } /** Initializes the given OIF file. */ protected void initFile(String id) throws FormatException, IOException { // check to make sure that we have the OIF file // if not, we need to look for it in the parent directory String oifFile = id; if (!id.toLowerCase().endsWith("oif")) { File current = new File(id); current = current.getAbsoluteFile(); String parent = current.getParent(); File tmp = new File(parent); parent = tmp.getParent(); // strip off the filename id = current.getPath(); oifFile = id.substring(id.lastIndexOf(File.separator)); oifFile = parent + oifFile.substring(0, oifFile.indexOf("_")) + ".oif"; tmp = new File(oifFile); if (!tmp.exists()) { oifFile = oifFile.substring(0, oifFile.lastIndexOf(".")) + ".OIF"; tmp = new File(oifFile); if (!tmp.exists()) throw new FormatException("OIF file not found"); currentId = oifFile; } else { currentId = oifFile; } } super.initFile(oifFile); reader = new BufferedReader(new FileReader(oifFile)); tiffReader = new TiffReader(); int slash = oifFile.lastIndexOf(File.separator); String path = slash < 0 ? "." : oifFile.substring(0, slash); // parse each key/value pair (one per line) Hashtable filenames = new Hashtable(); String line = reader.readLine(); while (line != null) { if (!line.startsWith("[") && (line.indexOf("=") > 0)) { String key = line.substring(0, line.indexOf("=") - 1).trim(); String value = line.substring(line.indexOf("=") + 1).trim(); key = DataTools.stripString(key); value = DataTools.stripString(value); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1) { int pos = Integer.parseInt(key.substring(11)); filenames.put(new Integer(pos), value); } metadata.put(key, value); } line = reader.readLine(); } numImages = filenames.size(); tiffs = new Vector(numImages); // open each INI file (.pty extension) String tiffPath; BufferedReader ptyReader; for (int i=0; i<numImages; i++) { String file = (String) filenames.get(new Integer(i)); file = file.substring(1, file.length() - 1); file = file.replace('\\', File.separatorChar); file = file.replace('/', File.separatorChar); file = path + File.separator + file; tiffPath = file.substring(0, file.lastIndexOf(File.separator)); ptyReader = new BufferedReader(new FileReader(file)); line = ptyReader.readLine(); while (line != null) { if (!line.startsWith("[") && (line.indexOf("=") > 0)) { String key = line.substring(0, line.indexOf("=") - 1).trim(); String value = line.substring(line.indexOf("=") + 1).trim(); key = DataTools.stripString(key); value = DataTools.stripString(value); if (key.equals("DataName")) { value = value.substring(1, value.length() - 1); tiffs.add(i, tiffPath + File.separator + value); } metadata.put("Image " + i + " : " + key, value); } line = ptyReader.readLine(); } ptyReader.close(); } // The metadata store we're working with. - MetadataStore store = getMetadataStore(id); + MetadataStore store = getMetadataStore(oifFile); store.setPixels( new Integer(Integer.parseInt((String) metadata.get("ImageWidth"))), new Integer(Integer.parseInt((String) metadata.get("ImageHeight"))), new Integer(numImages), new Integer(getSizeC(id)), new Integer(1), "int" + (8*Integer.parseInt((String) metadata.get("ImageDepth"))), new Boolean(false), "XYZTC", null); } // -- Main method -- public static void main(String[] args) throws FormatException, IOException { new OIFReader().testRead(args); } }
true
true
protected void initFile(String id) throws FormatException, IOException { // check to make sure that we have the OIF file // if not, we need to look for it in the parent directory String oifFile = id; if (!id.toLowerCase().endsWith("oif")) { File current = new File(id); current = current.getAbsoluteFile(); String parent = current.getParent(); File tmp = new File(parent); parent = tmp.getParent(); // strip off the filename id = current.getPath(); oifFile = id.substring(id.lastIndexOf(File.separator)); oifFile = parent + oifFile.substring(0, oifFile.indexOf("_")) + ".oif"; tmp = new File(oifFile); if (!tmp.exists()) { oifFile = oifFile.substring(0, oifFile.lastIndexOf(".")) + ".OIF"; tmp = new File(oifFile); if (!tmp.exists()) throw new FormatException("OIF file not found"); currentId = oifFile; } else { currentId = oifFile; } } super.initFile(oifFile); reader = new BufferedReader(new FileReader(oifFile)); tiffReader = new TiffReader(); int slash = oifFile.lastIndexOf(File.separator); String path = slash < 0 ? "." : oifFile.substring(0, slash); // parse each key/value pair (one per line) Hashtable filenames = new Hashtable(); String line = reader.readLine(); while (line != null) { if (!line.startsWith("[") && (line.indexOf("=") > 0)) { String key = line.substring(0, line.indexOf("=") - 1).trim(); String value = line.substring(line.indexOf("=") + 1).trim(); key = DataTools.stripString(key); value = DataTools.stripString(value); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1) { int pos = Integer.parseInt(key.substring(11)); filenames.put(new Integer(pos), value); } metadata.put(key, value); } line = reader.readLine(); } numImages = filenames.size(); tiffs = new Vector(numImages); // open each INI file (.pty extension) String tiffPath; BufferedReader ptyReader; for (int i=0; i<numImages; i++) { String file = (String) filenames.get(new Integer(i)); file = file.substring(1, file.length() - 1); file = file.replace('\\', File.separatorChar); file = file.replace('/', File.separatorChar); file = path + File.separator + file; tiffPath = file.substring(0, file.lastIndexOf(File.separator)); ptyReader = new BufferedReader(new FileReader(file)); line = ptyReader.readLine(); while (line != null) { if (!line.startsWith("[") && (line.indexOf("=") > 0)) { String key = line.substring(0, line.indexOf("=") - 1).trim(); String value = line.substring(line.indexOf("=") + 1).trim(); key = DataTools.stripString(key); value = DataTools.stripString(value); if (key.equals("DataName")) { value = value.substring(1, value.length() - 1); tiffs.add(i, tiffPath + File.separator + value); } metadata.put("Image " + i + " : " + key, value); } line = ptyReader.readLine(); } ptyReader.close(); } // The metadata store we're working with. MetadataStore store = getMetadataStore(id); store.setPixels( new Integer(Integer.parseInt((String) metadata.get("ImageWidth"))), new Integer(Integer.parseInt((String) metadata.get("ImageHeight"))), new Integer(numImages), new Integer(getSizeC(id)), new Integer(1), "int" + (8*Integer.parseInt((String) metadata.get("ImageDepth"))), new Boolean(false), "XYZTC", null); }
protected void initFile(String id) throws FormatException, IOException { // check to make sure that we have the OIF file // if not, we need to look for it in the parent directory String oifFile = id; if (!id.toLowerCase().endsWith("oif")) { File current = new File(id); current = current.getAbsoluteFile(); String parent = current.getParent(); File tmp = new File(parent); parent = tmp.getParent(); // strip off the filename id = current.getPath(); oifFile = id.substring(id.lastIndexOf(File.separator)); oifFile = parent + oifFile.substring(0, oifFile.indexOf("_")) + ".oif"; tmp = new File(oifFile); if (!tmp.exists()) { oifFile = oifFile.substring(0, oifFile.lastIndexOf(".")) + ".OIF"; tmp = new File(oifFile); if (!tmp.exists()) throw new FormatException("OIF file not found"); currentId = oifFile; } else { currentId = oifFile; } } super.initFile(oifFile); reader = new BufferedReader(new FileReader(oifFile)); tiffReader = new TiffReader(); int slash = oifFile.lastIndexOf(File.separator); String path = slash < 0 ? "." : oifFile.substring(0, slash); // parse each key/value pair (one per line) Hashtable filenames = new Hashtable(); String line = reader.readLine(); while (line != null) { if (!line.startsWith("[") && (line.indexOf("=") > 0)) { String key = line.substring(0, line.indexOf("=") - 1).trim(); String value = line.substring(line.indexOf("=") + 1).trim(); key = DataTools.stripString(key); value = DataTools.stripString(value); if (key.startsWith("IniFileName") && key.indexOf("Thumb") == -1) { int pos = Integer.parseInt(key.substring(11)); filenames.put(new Integer(pos), value); } metadata.put(key, value); } line = reader.readLine(); } numImages = filenames.size(); tiffs = new Vector(numImages); // open each INI file (.pty extension) String tiffPath; BufferedReader ptyReader; for (int i=0; i<numImages; i++) { String file = (String) filenames.get(new Integer(i)); file = file.substring(1, file.length() - 1); file = file.replace('\\', File.separatorChar); file = file.replace('/', File.separatorChar); file = path + File.separator + file; tiffPath = file.substring(0, file.lastIndexOf(File.separator)); ptyReader = new BufferedReader(new FileReader(file)); line = ptyReader.readLine(); while (line != null) { if (!line.startsWith("[") && (line.indexOf("=") > 0)) { String key = line.substring(0, line.indexOf("=") - 1).trim(); String value = line.substring(line.indexOf("=") + 1).trim(); key = DataTools.stripString(key); value = DataTools.stripString(value); if (key.equals("DataName")) { value = value.substring(1, value.length() - 1); tiffs.add(i, tiffPath + File.separator + value); } metadata.put("Image " + i + " : " + key, value); } line = ptyReader.readLine(); } ptyReader.close(); } // The metadata store we're working with. MetadataStore store = getMetadataStore(oifFile); store.setPixels( new Integer(Integer.parseInt((String) metadata.get("ImageWidth"))), new Integer(Integer.parseInt((String) metadata.get("ImageHeight"))), new Integer(numImages), new Integer(getSizeC(id)), new Integer(1), "int" + (8*Integer.parseInt((String) metadata.get("ImageDepth"))), new Boolean(false), "XYZTC", null); }
diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java index f7a4a4aac..fddcd4cc3 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java @@ -1,554 +1,556 @@ /** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * http://www.collectionspace.org * http://wiki.collectionspace.org * Copyright 2009 University of California at Berkeley * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.collectionspace.services.nuxeo.client.java; import java.util.Collection; import java.util.List; import javax.ws.rs.core.MultivaluedMap; import org.collectionspace.services.client.Profiler; import org.collectionspace.services.client.CollectionSpaceClient; import org.collectionspace.services.client.IQueryManager; import org.collectionspace.services.client.IRelationsManager; import org.collectionspace.services.client.PoxPayloadIn; import org.collectionspace.services.client.PoxPayloadOut; import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; import org.collectionspace.services.common.api.RefName; import org.collectionspace.services.common.api.RefName.RefNameInterface; import org.collectionspace.services.common.api.Tools; import org.collectionspace.services.common.authorityref.AuthorityRefList; import org.collectionspace.services.common.context.ServiceContext; import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl; import org.collectionspace.services.common.document.DocumentFilter; import org.collectionspace.services.common.document.DocumentWrapper; import org.collectionspace.services.common.document.DocumentWrapperImpl; import org.collectionspace.services.nuxeo.util.NuxeoUtils; import org.collectionspace.services.common.query.QueryContext; import org.collectionspace.services.common.repository.RepositoryClient; import org.collectionspace.services.common.repository.RepositoryClientFactory; import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo; import org.collectionspace.services.lifecycle.Lifecycle; import org.collectionspace.services.lifecycle.State; import org.collectionspace.services.lifecycle.StateList; import org.collectionspace.services.lifecycle.TransitionDef; import org.collectionspace.services.lifecycle.TransitionDefList; import org.collectionspace.services.lifecycle.TransitionList; import org.nuxeo.ecm.core.NXCore; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.nuxeo.ecm.core.api.model.PropertyException; import org.nuxeo.ecm.core.api.repository.RepositoryInstance; import org.nuxeo.ecm.core.lifecycle.LifeCycleService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DocumentModelHandler is a base abstract Nuxeo document handler * using Nuxeo Java Remote APIs for CollectionSpace services * * $LastChangedRevision: $ * $LastChangedDate: $ */ public abstract class DocumentModelHandler<T, TL> extends AbstractMultipartDocumentHandlerImpl<T, TL, DocumentModel, DocumentModelList> { private final Logger logger = LoggerFactory.getLogger(DocumentModelHandler.class); private RepositoryInstance repositorySession; protected String oldRefNameOnUpdate = null; // FIXME: REM - We should have setters and getters for these protected String newRefNameOnUpdate = null; // FIXME: two fields. /* * Map Nuxeo's life cycle object to our JAX-B based life cycle object */ private Lifecycle createCollectionSpaceLifecycle(org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle) { Lifecycle result = null; if (nuxeoLifecyle != null) { // // Copy the life cycle's name result = new Lifecycle(); result.setName(nuxeoLifecyle.getName()); // We currently support only one initial state, so take the first one from Nuxeo Collection<String> initialStateNames = nuxeoLifecyle.getInitialStateNames(); result.setDefaultInitial(initialStateNames.iterator().next()); // Next, we copy the state and corresponding transition lists StateList stateList = new StateList(); List<State> states = stateList.getState(); Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleState> nuxeoStates = nuxeoLifecyle.getStates(); for (org.nuxeo.ecm.core.lifecycle.LifeCycleState nuxeoState : nuxeoStates) { State tempState = new State(); tempState.setDescription(nuxeoState.getDescription()); tempState.setInitial(nuxeoState.isInitial()); tempState.setName(nuxeoState.getName()); // Now get the list of transitions TransitionList transitionList = new TransitionList(); List<String> transitions = transitionList.getTransition(); Collection<String> nuxeoTransitions = nuxeoState.getAllowedStateTransitions(); for (String nuxeoTransition : nuxeoTransitions) { transitions.add(nuxeoTransition); } tempState.setTransitionList(transitionList); states.add(tempState); } result.setStateList(stateList); // Finally, we create the transition definitions TransitionDefList transitionDefList = new TransitionDefList(); List<TransitionDef> transitionDefs = transitionDefList.getTransitionDef(); Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleTransition> nuxeoTransitionDefs = nuxeoLifecyle.getTransitions(); for (org.nuxeo.ecm.core.lifecycle.LifeCycleTransition nuxeoTransitionDef : nuxeoTransitionDefs) { TransitionDef tempTransitionDef = new TransitionDef(); tempTransitionDef.setDescription(nuxeoTransitionDef.getDescription()); tempTransitionDef.setDestinationState(nuxeoTransitionDef.getDestinationStateName()); tempTransitionDef.setName(nuxeoTransitionDef.getName()); transitionDefs.add(tempTransitionDef); } result.setTransitionDefList(transitionDefList); } return result; } /* * Returns the the life cycle definition of the related Nuxeo document type for this handler. * (non-Javadoc) * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle() */ @Override public Lifecycle getLifecycle() { Lifecycle result = null; String docTypeName = null; try { docTypeName = this.getServiceContext().getDocumentType(); result = getLifecycle(docTypeName); } catch (Exception e) { if (logger.isTraceEnabled() == true) { logger.trace("Could not retrieve lifecycle definition for Nuxeo doctype: " + docTypeName); } } return result; } /* * Returns the the life cycle definition of the related Nuxeo document type for this handler. * (non-Javadoc) * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle(java.lang.String) */ @Override public Lifecycle getLifecycle(String docTypeName) { org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle; Lifecycle result = null; try { LifeCycleService lifeCycleService = null; try { lifeCycleService = NXCore.getLifeCycleService(); } catch (Exception e) { e.printStackTrace(); } String lifeCycleName; lifeCycleName = lifeCycleService.getLifeCycleNameFor(docTypeName); nuxeoLifecyle = lifeCycleService.getLifeCycleByName(lifeCycleName); result = createCollectionSpaceLifecycle(nuxeoLifecyle); // result = (Lifecycle)FileTools.getJaxbObjectFromFile(Lifecycle.class, "default-lifecycle.xml"); } catch (Exception e) { // TODO Auto-generated catch block logger.error("Could not retreive life cycle information for Nuxeo doctype: " + docTypeName, e); } return result; } /* * We're using the "name" field of Nuxeo's DocumentModel to store * the CSID. */ public String getCsid(DocumentModel docModel) { return NuxeoUtils.getCsid(docModel); } public String getUri(DocumentModel docModel) { return getServiceContextPath()+getCsid(docModel); } public RepositoryClient<PoxPayloadIn, PoxPayloadOut> getRepositoryClient(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) { RepositoryClient<PoxPayloadIn, PoxPayloadOut> repositoryClient = RepositoryClientFactory.getInstance().getClient(ctx.getRepositoryClientName()); return repositoryClient; } /** * getRepositorySession returns Nuxeo Repository Session * @return */ public RepositoryInstance getRepositorySession() { return repositorySession; } /** * setRepositorySession sets repository session * @param repoSession */ public void setRepositorySession(RepositoryInstance repoSession) { this.repositorySession = repoSession; } @Override public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception { // TODO for sub-docs - check to see if the current service context is a multipart input, // OR a docfragment, and call a variant to fill the DocModel. fillAllParts(wrapDoc, Action.CREATE); handleCoreValues(wrapDoc, Action.CREATE); } // TODO for sub-docs - Add completeCreate in which we look for set-aside doc fragments // and create the subitems. We will create service contexts with the doc fragments // and then call @Override public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception { // TODO for sub-docs - check to see if the current service context is a multipart input, // OR a docfragment, and call a variant to fill the DocModel. fillAllParts(wrapDoc, Action.UPDATE); handleCoreValues(wrapDoc, Action.UPDATE); } @Override public void handleGet(DocumentWrapper<DocumentModel> wrapDoc) throws Exception { extractAllParts(wrapDoc); } @Override public void handleGetAll(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception { Profiler profiler = new Profiler(this, 2); profiler.start(); setCommonPartList(extractCommonPartList(wrapDoc)); profiler.stop(); } @Override public abstract void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception; @Override public abstract void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception; @Override public abstract T extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc) throws Exception; @Override public abstract void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception; @Override public abstract void fillCommonPart(T obj, DocumentWrapper<DocumentModel> wrapDoc) throws Exception; @Override public abstract TL extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception; @Override public abstract T getCommonPart(); @Override public abstract void setCommonPart(T obj); @Override public abstract TL getCommonPartList(); @Override public abstract void setCommonPartList(TL obj); @Override public DocumentFilter createDocumentFilter() { DocumentFilter filter = new NuxeoDocumentFilter(this.getServiceContext()); return filter; } /** * Gets the authority refs. * * @param docWrapper the doc wrapper * @param authRefFields the auth ref fields * @return the authority refs * @throws PropertyException the property exception */ abstract public AuthorityRefList getAuthorityRefs(String csid, List<AuthRefConfigInfo> authRefsInfo) throws PropertyException, Exception; /* * Subclasses should override this method if they need to customize their refname generation */ protected RefName.RefNameInterface getRefName(ServiceContext ctx, DocumentModel docModel) { return getRefName(new DocumentWrapperImpl<DocumentModel>(docModel), ctx.getTenantName(), ctx.getServiceName()); } /* * By default, we'll use the CSID as the short ID. Sub-classes can override this method if they want to use * something else for a short ID. * * (non-Javadoc) * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getRefName(org.collectionspace.services.common.document.DocumentWrapper, java.lang.String, java.lang.String) */ @Override protected RefName.RefNameInterface getRefName(DocumentWrapper<DocumentModel> docWrapper, String tenantName, String serviceName) { String csid = docWrapper.getWrappedObject().getName(); String refnameDisplayName = getRefnameDisplayName(docWrapper); RefName.RefNameInterface refname = RefName.Authority.buildAuthority(tenantName, serviceName, csid, null, refnameDisplayName); return refname; } private void handleCoreValues(DocumentWrapper<DocumentModel> docWrapper, Action action) throws ClientException { DocumentModel documentModel = docWrapper.getWrappedObject(); String now = GregorianCalendarDateTimeUtils.timestampUTC(); ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext(); String userId = ctx.getUserId(); if (action == Action.CREATE) { // // Add the tenant ID value to the new entity // String tenantId = ctx.getTenantId(); documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, CollectionSpaceClient.COLLECTIONSPACE_CORE_TENANTID, tenantId); // // Add the uri value to the new entity // documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, CollectionSpaceClient.COLLECTIONSPACE_CORE_URI, getUri(documentModel)); // // Add the CSID to the DublinCore title so we can see the CSID in the default // Nuxeo webapp. // try { documentModel.setProperty("dublincore", "title", documentModel.getName()); } catch (Exception x) { if (logger.isWarnEnabled() == true) { logger.warn("Could not set the Dublin Core 'title' field on document CSID:" + documentModel.getName()); } } // // Add createdAt timestamp and createdBy user // documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_AT, now); documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_BY, userId); } if (action == Action.CREATE || action == Action.UPDATE) { // // Add/update the resource's refname // handleRefNameChanges(ctx, documentModel); // // Add updatedAt timestamp and updateBy user // documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT, now); documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_BY, userId); } } protected boolean hasRefNameUpdate() { boolean result = false; if (Tools.notBlank(newRefNameOnUpdate) && Tools.notBlank(oldRefNameOnUpdate)) { if (newRefNameOnUpdate.equalsIgnoreCase(oldRefNameOnUpdate) == false) { result = true; // refNames are different so updates are needed } } return result; } protected void handleRefNameChanges(ServiceContext ctx, DocumentModel docModel) throws ClientException { // First get the old refName this.oldRefNameOnUpdate = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME); // Next, get the new refName RefNameInterface refName = getRefName(ctx, docModel); // Sub-classes may override the getRefName() method called here. if (refName != null) { this.newRefNameOnUpdate = refName.toString(); } else { logger.error(String.format("The refName for document is missing. Document CSID=%s", docModel.getName())); // FIXME: REM - We should probably be throwing an exception here? } // // Set the refName if it is an update or if the old refName was empty or null // if (hasRefNameUpdate() == true || this.oldRefNameOnUpdate == null) { docModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, this.newRefNameOnUpdate); } } /* * If we see the "rtSbj" query param then we need to perform a CMIS query. Currently, we have only one * CMIS query, but we could add more. If we do, this method should look at the incoming request and corresponding * query params to determine if we need to do a CMIS query * (non-Javadoc) * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#isCMISQuery() */ public boolean isCMISQuery() { boolean result = false; MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams(); // // Look the query params to see if we need to make a CMSIS query. // String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT); String asOjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT); String asEither = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER); if (asSubjectCsid != null || asOjectCsid != null || asEither != null) { result = true; } return result; } /** * Creates the CMIS query from the service context. Each document handler is * responsible for returning (can override) a valid CMIS query using the information in the * current service context -which includes things like the query parameters, * etc. * * This method implementation supports three mutually exclusive cases. We will build a query * that can find a document(s) 'A' in a relationship with another document * 'B' where document 'B' has a CSID equal to the query param passed in and: * 1. Document 'B' is the subject of the relationship * 2. Document 'B' is the object of the relationship * 3. Document 'B' is either the object or the subject of the relationship */ @Override public String getCMISQuery(QueryContext queryContext) { String result = null; if (isCMISQuery() == true) { // // Build up the query arguments // String theOnClause = ""; String theWhereClause = ""; MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams(); String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT); String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT); String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER); String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES); String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD); - String docType = this.getServiceContext().getDocumentType(); + //String docType = this.getServiceContext().getDocumentType(); + // If this type in this tenant has been extended, be sure to use that so extension schema is visible. + String docType = NuxeoUtils.getTenantQualifiedDocType(this.getServiceContext()); if (selectDocType != null && !selectDocType.isEmpty()) { docType = selectDocType; } String selectFields = IQueryManager.CMIS_TARGET_CSID + ", " + IQueryManager.CMIS_TARGET_TITLE + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID; String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX; String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX; String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID; String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID; String targetCsidCol = IQueryManager.CMIS_TARGET_CSID; // // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request. // // First come, first serve -the first match determines the "ON" and "WHERE" query clauses. // if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) { // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship. theOnClause = relObjectCsidCol + " = " + targetCsidCol; theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'"; } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) { // Since our query param is the "object" value, join the tables where the CSID of the document is the other side (the "subject") of the relationship. theOnClause = relSubjectCsidCol + " = " + targetCsidCol; theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'"; } else if (asEitherCsid != null && !asEitherCsid.isEmpty()) { theOnClause = relObjectCsidCol + " = " + targetCsidCol + " OR " + relSubjectCsidCol + " = " + targetCsidCol; theWhereClause = relSubjectCsidCol + " = " + "'" + asEitherCsid + "'" + " OR " + relObjectCsidCol + " = " + "'" + asEitherCsid + "'"; } else { //Since the call to isCMISQuery() return true, we should never get here. logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters."); } // Now consider a constraint on the object doc types (for search by service group) if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) { // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship. theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE + " IN " + matchObjDocTypes + ")"; } // This could later be in control of a queryParam, to omit if we want to see versions, or to // only see old versions. theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_NUXEO_IS_VERSION_FILTER; StringBuilder query = new StringBuilder(); // assemble the query from the string arguments query.append("SELECT "); query.append(selectFields); query.append(" FROM " + targetTable + " JOIN " + relTable); query.append(" ON " + theOnClause); query.append(" WHERE " + theWhereClause); try { NuxeoUtils.appendCMISOrderBy(query, queryContext); } catch (Exception e) { logger.error("Could not append ORDER BY clause to CMIS query", e); } // An example: // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid // FROM Dimension D JOIN Relation R // ON R.relations_common:objectCsid = D.cmis:name // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de' // ORDER BY D.collectionspace_core:updatedAt DESC result = query.toString(); if (logger.isDebugEnabled() == true && result != null) { logger.debug("The CMIS query is: " + result); } } return result; } }
true
true
public String getCMISQuery(QueryContext queryContext) { String result = null; if (isCMISQuery() == true) { // // Build up the query arguments // String theOnClause = ""; String theWhereClause = ""; MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams(); String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT); String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT); String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER); String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES); String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD); String docType = this.getServiceContext().getDocumentType(); if (selectDocType != null && !selectDocType.isEmpty()) { docType = selectDocType; } String selectFields = IQueryManager.CMIS_TARGET_CSID + ", " + IQueryManager.CMIS_TARGET_TITLE + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID; String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX; String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX; String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID; String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID; String targetCsidCol = IQueryManager.CMIS_TARGET_CSID; // // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request. // // First come, first serve -the first match determines the "ON" and "WHERE" query clauses. // if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) { // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship. theOnClause = relObjectCsidCol + " = " + targetCsidCol; theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'"; } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) { // Since our query param is the "object" value, join the tables where the CSID of the document is the other side (the "subject") of the relationship. theOnClause = relSubjectCsidCol + " = " + targetCsidCol; theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'"; } else if (asEitherCsid != null && !asEitherCsid.isEmpty()) { theOnClause = relObjectCsidCol + " = " + targetCsidCol + " OR " + relSubjectCsidCol + " = " + targetCsidCol; theWhereClause = relSubjectCsidCol + " = " + "'" + asEitherCsid + "'" + " OR " + relObjectCsidCol + " = " + "'" + asEitherCsid + "'"; } else { //Since the call to isCMISQuery() return true, we should never get here. logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters."); } // Now consider a constraint on the object doc types (for search by service group) if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) { // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship. theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE + " IN " + matchObjDocTypes + ")"; } // This could later be in control of a queryParam, to omit if we want to see versions, or to // only see old versions. theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_NUXEO_IS_VERSION_FILTER; StringBuilder query = new StringBuilder(); // assemble the query from the string arguments query.append("SELECT "); query.append(selectFields); query.append(" FROM " + targetTable + " JOIN " + relTable); query.append(" ON " + theOnClause); query.append(" WHERE " + theWhereClause); try { NuxeoUtils.appendCMISOrderBy(query, queryContext); } catch (Exception e) { logger.error("Could not append ORDER BY clause to CMIS query", e); } // An example: // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid // FROM Dimension D JOIN Relation R // ON R.relations_common:objectCsid = D.cmis:name // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de' // ORDER BY D.collectionspace_core:updatedAt DESC result = query.toString(); if (logger.isDebugEnabled() == true && result != null) { logger.debug("The CMIS query is: " + result); } } return result; }
public String getCMISQuery(QueryContext queryContext) { String result = null; if (isCMISQuery() == true) { // // Build up the query arguments // String theOnClause = ""; String theWhereClause = ""; MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams(); String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT); String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT); String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER); String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES); String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD); //String docType = this.getServiceContext().getDocumentType(); // If this type in this tenant has been extended, be sure to use that so extension schema is visible. String docType = NuxeoUtils.getTenantQualifiedDocType(this.getServiceContext()); if (selectDocType != null && !selectDocType.isEmpty()) { docType = selectDocType; } String selectFields = IQueryManager.CMIS_TARGET_CSID + ", " + IQueryManager.CMIS_TARGET_TITLE + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", " + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID; String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX; String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX; String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID; String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID; String targetCsidCol = IQueryManager.CMIS_TARGET_CSID; // // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request. // // First come, first serve -the first match determines the "ON" and "WHERE" query clauses. // if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) { // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship. theOnClause = relObjectCsidCol + " = " + targetCsidCol; theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'"; } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) { // Since our query param is the "object" value, join the tables where the CSID of the document is the other side (the "subject") of the relationship. theOnClause = relSubjectCsidCol + " = " + targetCsidCol; theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'"; } else if (asEitherCsid != null && !asEitherCsid.isEmpty()) { theOnClause = relObjectCsidCol + " = " + targetCsidCol + " OR " + relSubjectCsidCol + " = " + targetCsidCol; theWhereClause = relSubjectCsidCol + " = " + "'" + asEitherCsid + "'" + " OR " + relObjectCsidCol + " = " + "'" + asEitherCsid + "'"; } else { //Since the call to isCMISQuery() return true, we should never get here. logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters."); } // Now consider a constraint on the object doc types (for search by service group) if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) { // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship. theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE + " IN " + matchObjDocTypes + ")"; } // This could later be in control of a queryParam, to omit if we want to see versions, or to // only see old versions. theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_NUXEO_IS_VERSION_FILTER; StringBuilder query = new StringBuilder(); // assemble the query from the string arguments query.append("SELECT "); query.append(selectFields); query.append(" FROM " + targetTable + " JOIN " + relTable); query.append(" ON " + theOnClause); query.append(" WHERE " + theWhereClause); try { NuxeoUtils.appendCMISOrderBy(query, queryContext); } catch (Exception e) { logger.error("Could not append ORDER BY clause to CMIS query", e); } // An example: // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid // FROM Dimension D JOIN Relation R // ON R.relations_common:objectCsid = D.cmis:name // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de' // ORDER BY D.collectionspace_core:updatedAt DESC result = query.toString(); if (logger.isDebugEnabled() == true && result != null) { logger.debug("The CMIS query is: " + result); } } return result; }
diff --git a/src/main/java/com/greplin/interval/NumericInterval.java b/src/main/java/com/greplin/interval/NumericInterval.java index 307d8a0..03a8b44 100644 --- a/src/main/java/com/greplin/interval/NumericInterval.java +++ b/src/main/java/com/greplin/interval/NumericInterval.java @@ -1,77 +1,77 @@ package com.greplin.interval; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; /** * Base class for numeric intervals. Most functionality is implemented in * subclasses to avoid autoboxing and improve performance. * @param <T> value type */ public abstract class NumericInterval<T extends Number> { /** * @return the start of the interval, boxed. */ public abstract T getBoxedStart(); /** * @return the end of the interval, boxed. */ public abstract T getBoxedEnd(); @Override @SuppressWarnings("unchecked") // Safe because this class is abstract. public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NumericInterval<T> interval = (NumericInterval<T>) o; return this.getBoxedEnd().equals(interval.getBoxedEnd()) - && this.getBoxedStart().equals(interval.getBoxedEnd()); + && this.getBoxedStart().equals(interval.getBoxedStart()); } @Override public int hashCode() { return Objects.hashCode(this.getBoxedStart(), this.getBoxedEnd()); } @Override public String toString() { return this.getClass().getSimpleName() + "{" + this.getBoxedStart() + '-' + this.getBoxedEnd() + '}'; } /** * @return this interval formatted as a string. */ public String asString() { return this.getBoxedStart() + "-" + this.getBoxedEnd(); } /** * @return this interval formatted as a 2 element list. */ public ImmutableList<T> asList() { return ImmutableList.of(this.getBoxedStart(), this.getBoxedEnd()); } /** * @return this interval formatted as a 2 element list of strings. */ public ImmutableList<String> asStringList() { return ImmutableList.of( this.getBoxedStart().toString(), this.getBoxedEnd().toString()); } }
true
true
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NumericInterval<T> interval = (NumericInterval<T>) o; return this.getBoxedEnd().equals(interval.getBoxedEnd()) && this.getBoxedStart().equals(interval.getBoxedEnd()); }
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NumericInterval<T> interval = (NumericInterval<T>) o; return this.getBoxedEnd().equals(interval.getBoxedEnd()) && this.getBoxedStart().equals(interval.getBoxedStart()); }
diff --git a/RemoteControl/src/main/java/com/bignerdranch/android/remotecontrol/RemoteControlFragment.java b/RemoteControl/src/main/java/com/bignerdranch/android/remotecontrol/RemoteControlFragment.java index 2a3a1a4..cbf35e8 100644 --- a/RemoteControl/src/main/java/com/bignerdranch/android/remotecontrol/RemoteControlFragment.java +++ b/RemoteControl/src/main/java/com/bignerdranch/android/remotecontrol/RemoteControlFragment.java @@ -1,87 +1,87 @@ package com.bignerdranch.android.remotecontrol; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; /** * Created by panda on 7/8/13. */ public class RemoteControlFragment extends Fragment { private TextView mSelectedTextView; private TextView mWorkingTextView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { - final View v = inflater.inflate(R.layout.fragment_remote_control, parent, false); + View v = inflater.inflate(R.layout.fragment_remote_control, parent, false); mSelectedTextView = (TextView)v .findViewById(R.id.fragment_remote_control_selectedTextView); mWorkingTextView = (TextView)v .findViewById(R.id.fragment_remote_control_workingTextView); View.OnClickListener numberButtonListener = new View.OnClickListener() { @Override - public void onClick(View view) { + public void onClick(View v) { TextView textView = (TextView)v; String working = mWorkingTextView.getText().toString(); String text = textView.getText().toString(); if (working.equals("0")) { mWorkingTextView.setText(text); } else { mWorkingTextView.setText(working + text); } } }; TableLayout tableLayout = (TableLayout)v .findViewById(R.id.fragment_remote_control_tableLayout); int number = 1; for (int i = 2; i < tableLayout.getChildCount() - 1; i++) { TableRow row = (TableRow)tableLayout.getChildAt(i); for (int j = 0; j < row.getChildCount(); j++) { Button button = (Button)row.getChildAt(j); button.setText("" + number); button.setOnClickListener(numberButtonListener); number++; } } TableRow bottomRow = (TableRow)tableLayout .getChildAt(tableLayout.getChildCount() - 1); Button deleteButton = (Button)bottomRow.getChildAt(0); deleteButton.setText("Delete"); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mWorkingTextView.setText("0"); } }); Button zeroButton = (Button)bottomRow.getChildAt(1); zeroButton.setText("0"); zeroButton.setOnClickListener(numberButtonListener); Button enterButton = (Button)bottomRow.getChildAt(2); enterButton.setText("Enter"); enterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CharSequence working = mWorkingTextView.getText(); if (working.length() > 0) mSelectedTextView.setText(working); mWorkingTextView.setText("0"); } }); return v; } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.fragment_remote_control, parent, false); mSelectedTextView = (TextView)v .findViewById(R.id.fragment_remote_control_selectedTextView); mWorkingTextView = (TextView)v .findViewById(R.id.fragment_remote_control_workingTextView); View.OnClickListener numberButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { TextView textView = (TextView)v; String working = mWorkingTextView.getText().toString(); String text = textView.getText().toString(); if (working.equals("0")) { mWorkingTextView.setText(text); } else { mWorkingTextView.setText(working + text); } } }; TableLayout tableLayout = (TableLayout)v .findViewById(R.id.fragment_remote_control_tableLayout); int number = 1; for (int i = 2; i < tableLayout.getChildCount() - 1; i++) { TableRow row = (TableRow)tableLayout.getChildAt(i); for (int j = 0; j < row.getChildCount(); j++) { Button button = (Button)row.getChildAt(j); button.setText("" + number); button.setOnClickListener(numberButtonListener); number++; } } TableRow bottomRow = (TableRow)tableLayout .getChildAt(tableLayout.getChildCount() - 1); Button deleteButton = (Button)bottomRow.getChildAt(0); deleteButton.setText("Delete"); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mWorkingTextView.setText("0"); } }); Button zeroButton = (Button)bottomRow.getChildAt(1); zeroButton.setText("0"); zeroButton.setOnClickListener(numberButtonListener); Button enterButton = (Button)bottomRow.getChildAt(2); enterButton.setText("Enter"); enterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CharSequence working = mWorkingTextView.getText(); if (working.length() > 0) mSelectedTextView.setText(working); mWorkingTextView.setText("0"); } }); return v; }
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_remote_control, parent, false); mSelectedTextView = (TextView)v .findViewById(R.id.fragment_remote_control_selectedTextView); mWorkingTextView = (TextView)v .findViewById(R.id.fragment_remote_control_workingTextView); View.OnClickListener numberButtonListener = new View.OnClickListener() { @Override public void onClick(View v) { TextView textView = (TextView)v; String working = mWorkingTextView.getText().toString(); String text = textView.getText().toString(); if (working.equals("0")) { mWorkingTextView.setText(text); } else { mWorkingTextView.setText(working + text); } } }; TableLayout tableLayout = (TableLayout)v .findViewById(R.id.fragment_remote_control_tableLayout); int number = 1; for (int i = 2; i < tableLayout.getChildCount() - 1; i++) { TableRow row = (TableRow)tableLayout.getChildAt(i); for (int j = 0; j < row.getChildCount(); j++) { Button button = (Button)row.getChildAt(j); button.setText("" + number); button.setOnClickListener(numberButtonListener); number++; } } TableRow bottomRow = (TableRow)tableLayout .getChildAt(tableLayout.getChildCount() - 1); Button deleteButton = (Button)bottomRow.getChildAt(0); deleteButton.setText("Delete"); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mWorkingTextView.setText("0"); } }); Button zeroButton = (Button)bottomRow.getChildAt(1); zeroButton.setText("0"); zeroButton.setOnClickListener(numberButtonListener); Button enterButton = (Button)bottomRow.getChildAt(2); enterButton.setText("Enter"); enterButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CharSequence working = mWorkingTextView.getText(); if (working.length() > 0) mSelectedTextView.setText(working); mWorkingTextView.setText("0"); } }); return v; }
diff --git a/src/main/java/com/solidstategroup/radar/web/panels/DemographicsPanel.java b/src/main/java/com/solidstategroup/radar/web/panels/DemographicsPanel.java index 51ad013e..891005d5 100644 --- a/src/main/java/com/solidstategroup/radar/web/panels/DemographicsPanel.java +++ b/src/main/java/com/solidstategroup/radar/web/panels/DemographicsPanel.java @@ -1,248 +1,248 @@ package com.solidstategroup.radar.web.panels; import com.solidstategroup.radar.model.Centre; import com.solidstategroup.radar.model.Consultant; import com.solidstategroup.radar.model.Demographics; import com.solidstategroup.radar.model.Diagnosis; import com.solidstategroup.radar.model.DiagnosisCode; import com.solidstategroup.radar.model.Ethnicity; import com.solidstategroup.radar.model.Sex; import com.solidstategroup.radar.model.Status; import com.solidstategroup.radar.model.user.User; import com.solidstategroup.radar.service.*; import com.solidstategroup.radar.web.RadarApplication; import com.solidstategroup.radar.web.RadarSecuredSession; import com.solidstategroup.radar.web.components.CentreDropDown; import com.solidstategroup.radar.web.components.ConsultantDropDown; import com.solidstategroup.radar.web.components.RadarComponentFactory; import com.solidstategroup.radar.web.components.RadarRequiredDateTextField; import com.solidstategroup.radar.web.components.RadarRequiredDropdownChoice; import com.solidstategroup.radar.web.components.RadarRequiredTextField; import com.solidstategroup.radar.web.components.RadarTextFieldWithValidation; import com.solidstategroup.radar.web.models.RadarModelFactory; import com.solidstategroup.radar.web.pages.PatientPage; import com.solidstategroup.radar.web.pages.content.ConsentFormsPage; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.datetime.markup.html.form.DateTextField; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.validation.validator.PatternValidator; import java.util.ArrayList; import java.util.Date; import java.util.List; public class DemographicsPanel extends Panel { @SpringBean private DemographicsManager demographicsManager; @SpringBean private DiagnosisManager diagnosisManager; @SpringBean private ClinicalDataManager clinicalDataManager; @SpringBean private LabDataManager labDataManager; @SpringBean private TherapyManager therapyManager; @SpringBean private UtilityManager utilityManager; public DemographicsPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Set up model - if given radar number loadable detachable getting demographics by radar number final CompoundPropertyModel<Demographics> model = new CompoundPropertyModel<Demographics>(new LoadableDetachableModel<Demographics>() { @Override public Demographics load() { Demographics demographicsModelObject = null; if (radarNumberModel.getObject() != null) { Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } demographicsModelObject = demographicsManager.getDemographicsByRadarNumber(radarNumber); } if (demographicsModelObject == null) { demographicsModelObject = new Demographics(); } return demographicsModelObject; } }); // Set up form final Form<Demographics> form = new Form<Demographics>("form", model) { @Override protected void onSubmit() { Demographics demographics = getModelObject(); // shouldnt need to do this but for some reason the id comes back with null! if (radarNumberModel.getObject() != null) { demographics.setId(radarNumberModel.getObject()); } demographicsManager.saveDemographics(demographics); radarNumberModel.setObject(demographics.getId()); // create new diagnosis if it doesnt exist becuase diagnosis code is set in demographics tab Diagnosis diagnosis = diagnosisManager.getDiagnosisByRadarNumber(demographics.getId()); if (diagnosis == null) { Diagnosis diagnosis_new = new Diagnosis(); diagnosis_new.setRadarNumber(demographics.getId()); DiagnosisCode diagnosisCode = (DiagnosisCode) ((DropDownChoice) get("diagnosis")).getModelObject(); diagnosis_new.setDiagnosisCode(diagnosisCode); diagnosisManager.saveDiagnosis(diagnosis_new); } } }; add(form); final List<Component> componentsToUpdateList = new ArrayList<Component>(); form.add(new Label("addNewPatientLabel", "Add a New Patient") { @Override public boolean isVisible() { return radarNumberModel.getObject() == null; } }); - TextField<Long> radarNumberField = new TextField<Long>("id"); + TextField<Long> radarNumberField = new TextField<Long>("radarNumber", radarNumberModel); radarNumberField.setEnabled(false); form.add(radarNumberField); DateTextField dateRegistered = DateTextField.forDatePattern("dateRegistered", RadarApplication.DATE_PATTERN); if (radarNumberModel.getObject() == null) { model.getObject().setDateRegistered(new Date()); } form.add(dateRegistered); RadarRequiredDropdownChoice diagnosis = new RadarRequiredDropdownChoice("diagnosis", RadarModelFactory.getDiagnosisCodeModel(radarNumberModel, diagnosisManager), diagnosisManager.getDiagnosisCodes(), new ChoiceRenderer("abbreviation", "id"), form, componentsToUpdateList) { @Override public boolean isEnabled() { RadarSecuredSession securedSession = RadarSecuredSession.get(); if(securedSession.getRoles().hasRole(User.ROLE_PATIENT)) { return false; } return getModelObject() == null; } }; // Basic fields RadarRequiredTextField surname = new RadarRequiredTextField("surname", form, componentsToUpdateList); RadarRequiredTextField forename = new RadarRequiredTextField("forename", form, componentsToUpdateList); RadarRequiredDateTextField dateOfBirth = new RadarRequiredDateTextField("dateOfBirth", form, componentsToUpdateList); dateOfBirth.setRequired(true); form.add(diagnosis, surname, forename, dateOfBirth); // Sex RadarRequiredDropdownChoice sex = new RadarRequiredDropdownChoice("sex", demographicsManager.getSexes(), new ChoiceRenderer<Sex>("type", "id"), form, componentsToUpdateList); // Ethnicity DropDownChoice<Ethnicity> ethnicity = new DropDownChoice<Ethnicity>("ethnicity", utilityManager.getEthnicities(), new ChoiceRenderer<Ethnicity>("name", "id")); form.add(sex, ethnicity); // Address fields TextField address1 = new TextField("address1"); TextField address2 = new TextField("address2"); TextField address3 = new TextField("address3"); TextField address4 = new TextField("address4"); RadarTextFieldWithValidation postcode = new RadarTextFieldWithValidation("postcode", new PatternValidator("[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$"), form, componentsToUpdateList); form.add(address1, address2, address3, address4, postcode); // Archive fields TextField surnameAlias = new TextField("surnameAlias"); TextField previousPostcode = new TextField("previousPostcode"); form.add(surnameAlias, previousPostcode); // More info RadarRequiredTextField hospitalNumber = new RadarRequiredTextField("hospitalNumber", form, componentsToUpdateList); TextField nhsNumber = new TextField("nhsNumber"); TextField renalRegistryNumber = new TextField("renalRegistryNumber"); TextField ukTransplantNumber = new TextField("ukTransplantNumber"); TextField chiNumber = new TextField("chiNumber"); form.add(hospitalNumber, nhsNumber, renalRegistryNumber, ukTransplantNumber, chiNumber); // Status, consultants and centres drop down boxes DropDownChoice<Status> status = new DropDownChoice<Status>("status", demographicsManager.getStatuses(), new ChoiceRenderer<Status>("abbreviation", "id")); // Consultant and renal unit DropDownChoice<Consultant> consultant = new ConsultantDropDown("consultant"); DropDownChoice<Centre> renalUnit = new CentreDropDown("renalUnit"); form.add(status, consultant, renalUnit); CheckBox consent = new CheckBox("consent"); DropDownChoice<Centre> renalUnitAuthorised = new CentreDropDown("renalUnitAuthorised"); form.add(consent, renalUnitAuthorised); form.add(new BookmarkablePageLink("consentFormsLink", ConsentFormsPage.class)); final Label successMessage = RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdateList); Label errorMessage = RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdateList); - AjaxSubmitLink ajaxSubmitLink = new AjaxSubmitLink("submit") { + AjaxSubmitLink ajaxSubmitLink = new AjaxSubmitLink("save") { @Override protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) { ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()])); successMessage.setVisible(true); ajaxRequestTarget.add(successMessage); } @Override protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) { ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()])); successMessage.setVisible(false); ajaxRequestTarget.add(successMessage); } }; ajaxSubmitLink.add(new AttributeModifier("value", new AbstractReadOnlyModel() { @Override public Object getObject() { return radarNumberModel.getObject() == null ? "Add this patient" : "Update"; } })); form.add(ajaxSubmitLink); } @Override public boolean isVisible() { return ((PatientPage) getPage()).getCurrentTab().equals(PatientPage.CurrentTab.DEMOGRAPHICS); } }
false
true
public DemographicsPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Set up model - if given radar number loadable detachable getting demographics by radar number final CompoundPropertyModel<Demographics> model = new CompoundPropertyModel<Demographics>(new LoadableDetachableModel<Demographics>() { @Override public Demographics load() { Demographics demographicsModelObject = null; if (radarNumberModel.getObject() != null) { Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } demographicsModelObject = demographicsManager.getDemographicsByRadarNumber(radarNumber); } if (demographicsModelObject == null) { demographicsModelObject = new Demographics(); } return demographicsModelObject; } }); // Set up form final Form<Demographics> form = new Form<Demographics>("form", model) { @Override protected void onSubmit() { Demographics demographics = getModelObject(); // shouldnt need to do this but for some reason the id comes back with null! if (radarNumberModel.getObject() != null) { demographics.setId(radarNumberModel.getObject()); } demographicsManager.saveDemographics(demographics); radarNumberModel.setObject(demographics.getId()); // create new diagnosis if it doesnt exist becuase diagnosis code is set in demographics tab Diagnosis diagnosis = diagnosisManager.getDiagnosisByRadarNumber(demographics.getId()); if (diagnosis == null) { Diagnosis diagnosis_new = new Diagnosis(); diagnosis_new.setRadarNumber(demographics.getId()); DiagnosisCode diagnosisCode = (DiagnosisCode) ((DropDownChoice) get("diagnosis")).getModelObject(); diagnosis_new.setDiagnosisCode(diagnosisCode); diagnosisManager.saveDiagnosis(diagnosis_new); } } }; add(form); final List<Component> componentsToUpdateList = new ArrayList<Component>(); form.add(new Label("addNewPatientLabel", "Add a New Patient") { @Override public boolean isVisible() { return radarNumberModel.getObject() == null; } }); TextField<Long> radarNumberField = new TextField<Long>("id"); radarNumberField.setEnabled(false); form.add(radarNumberField); DateTextField dateRegistered = DateTextField.forDatePattern("dateRegistered", RadarApplication.DATE_PATTERN); if (radarNumberModel.getObject() == null) { model.getObject().setDateRegistered(new Date()); } form.add(dateRegistered); RadarRequiredDropdownChoice diagnosis = new RadarRequiredDropdownChoice("diagnosis", RadarModelFactory.getDiagnosisCodeModel(radarNumberModel, diagnosisManager), diagnosisManager.getDiagnosisCodes(), new ChoiceRenderer("abbreviation", "id"), form, componentsToUpdateList) { @Override public boolean isEnabled() { RadarSecuredSession securedSession = RadarSecuredSession.get(); if(securedSession.getRoles().hasRole(User.ROLE_PATIENT)) { return false; } return getModelObject() == null; } }; // Basic fields RadarRequiredTextField surname = new RadarRequiredTextField("surname", form, componentsToUpdateList); RadarRequiredTextField forename = new RadarRequiredTextField("forename", form, componentsToUpdateList); RadarRequiredDateTextField dateOfBirth = new RadarRequiredDateTextField("dateOfBirth", form, componentsToUpdateList); dateOfBirth.setRequired(true); form.add(diagnosis, surname, forename, dateOfBirth); // Sex RadarRequiredDropdownChoice sex = new RadarRequiredDropdownChoice("sex", demographicsManager.getSexes(), new ChoiceRenderer<Sex>("type", "id"), form, componentsToUpdateList); // Ethnicity DropDownChoice<Ethnicity> ethnicity = new DropDownChoice<Ethnicity>("ethnicity", utilityManager.getEthnicities(), new ChoiceRenderer<Ethnicity>("name", "id")); form.add(sex, ethnicity); // Address fields TextField address1 = new TextField("address1"); TextField address2 = new TextField("address2"); TextField address3 = new TextField("address3"); TextField address4 = new TextField("address4"); RadarTextFieldWithValidation postcode = new RadarTextFieldWithValidation("postcode", new PatternValidator("[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$"), form, componentsToUpdateList); form.add(address1, address2, address3, address4, postcode); // Archive fields TextField surnameAlias = new TextField("surnameAlias"); TextField previousPostcode = new TextField("previousPostcode"); form.add(surnameAlias, previousPostcode); // More info RadarRequiredTextField hospitalNumber = new RadarRequiredTextField("hospitalNumber", form, componentsToUpdateList); TextField nhsNumber = new TextField("nhsNumber"); TextField renalRegistryNumber = new TextField("renalRegistryNumber"); TextField ukTransplantNumber = new TextField("ukTransplantNumber"); TextField chiNumber = new TextField("chiNumber"); form.add(hospitalNumber, nhsNumber, renalRegistryNumber, ukTransplantNumber, chiNumber); // Status, consultants and centres drop down boxes DropDownChoice<Status> status = new DropDownChoice<Status>("status", demographicsManager.getStatuses(), new ChoiceRenderer<Status>("abbreviation", "id")); // Consultant and renal unit DropDownChoice<Consultant> consultant = new ConsultantDropDown("consultant"); DropDownChoice<Centre> renalUnit = new CentreDropDown("renalUnit"); form.add(status, consultant, renalUnit); CheckBox consent = new CheckBox("consent"); DropDownChoice<Centre> renalUnitAuthorised = new CentreDropDown("renalUnitAuthorised"); form.add(consent, renalUnitAuthorised); form.add(new BookmarkablePageLink("consentFormsLink", ConsentFormsPage.class)); final Label successMessage = RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdateList); Label errorMessage = RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdateList); AjaxSubmitLink ajaxSubmitLink = new AjaxSubmitLink("submit") { @Override protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) { ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()])); successMessage.setVisible(true); ajaxRequestTarget.add(successMessage); } @Override protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) { ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()])); successMessage.setVisible(false); ajaxRequestTarget.add(successMessage); } }; ajaxSubmitLink.add(new AttributeModifier("value", new AbstractReadOnlyModel() { @Override public Object getObject() { return radarNumberModel.getObject() == null ? "Add this patient" : "Update"; } })); form.add(ajaxSubmitLink); }
public DemographicsPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Set up model - if given radar number loadable detachable getting demographics by radar number final CompoundPropertyModel<Demographics> model = new CompoundPropertyModel<Demographics>(new LoadableDetachableModel<Demographics>() { @Override public Demographics load() { Demographics demographicsModelObject = null; if (radarNumberModel.getObject() != null) { Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } demographicsModelObject = demographicsManager.getDemographicsByRadarNumber(radarNumber); } if (demographicsModelObject == null) { demographicsModelObject = new Demographics(); } return demographicsModelObject; } }); // Set up form final Form<Demographics> form = new Form<Demographics>("form", model) { @Override protected void onSubmit() { Demographics demographics = getModelObject(); // shouldnt need to do this but for some reason the id comes back with null! if (radarNumberModel.getObject() != null) { demographics.setId(radarNumberModel.getObject()); } demographicsManager.saveDemographics(demographics); radarNumberModel.setObject(demographics.getId()); // create new diagnosis if it doesnt exist becuase diagnosis code is set in demographics tab Diagnosis diagnosis = diagnosisManager.getDiagnosisByRadarNumber(demographics.getId()); if (diagnosis == null) { Diagnosis diagnosis_new = new Diagnosis(); diagnosis_new.setRadarNumber(demographics.getId()); DiagnosisCode diagnosisCode = (DiagnosisCode) ((DropDownChoice) get("diagnosis")).getModelObject(); diagnosis_new.setDiagnosisCode(diagnosisCode); diagnosisManager.saveDiagnosis(diagnosis_new); } } }; add(form); final List<Component> componentsToUpdateList = new ArrayList<Component>(); form.add(new Label("addNewPatientLabel", "Add a New Patient") { @Override public boolean isVisible() { return radarNumberModel.getObject() == null; } }); TextField<Long> radarNumberField = new TextField<Long>("radarNumber", radarNumberModel); radarNumberField.setEnabled(false); form.add(radarNumberField); DateTextField dateRegistered = DateTextField.forDatePattern("dateRegistered", RadarApplication.DATE_PATTERN); if (radarNumberModel.getObject() == null) { model.getObject().setDateRegistered(new Date()); } form.add(dateRegistered); RadarRequiredDropdownChoice diagnosis = new RadarRequiredDropdownChoice("diagnosis", RadarModelFactory.getDiagnosisCodeModel(radarNumberModel, diagnosisManager), diagnosisManager.getDiagnosisCodes(), new ChoiceRenderer("abbreviation", "id"), form, componentsToUpdateList) { @Override public boolean isEnabled() { RadarSecuredSession securedSession = RadarSecuredSession.get(); if(securedSession.getRoles().hasRole(User.ROLE_PATIENT)) { return false; } return getModelObject() == null; } }; // Basic fields RadarRequiredTextField surname = new RadarRequiredTextField("surname", form, componentsToUpdateList); RadarRequiredTextField forename = new RadarRequiredTextField("forename", form, componentsToUpdateList); RadarRequiredDateTextField dateOfBirth = new RadarRequiredDateTextField("dateOfBirth", form, componentsToUpdateList); dateOfBirth.setRequired(true); form.add(diagnosis, surname, forename, dateOfBirth); // Sex RadarRequiredDropdownChoice sex = new RadarRequiredDropdownChoice("sex", demographicsManager.getSexes(), new ChoiceRenderer<Sex>("type", "id"), form, componentsToUpdateList); // Ethnicity DropDownChoice<Ethnicity> ethnicity = new DropDownChoice<Ethnicity>("ethnicity", utilityManager.getEthnicities(), new ChoiceRenderer<Ethnicity>("name", "id")); form.add(sex, ethnicity); // Address fields TextField address1 = new TextField("address1"); TextField address2 = new TextField("address2"); TextField address3 = new TextField("address3"); TextField address4 = new TextField("address4"); RadarTextFieldWithValidation postcode = new RadarTextFieldWithValidation("postcode", new PatternValidator("[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$"), form, componentsToUpdateList); form.add(address1, address2, address3, address4, postcode); // Archive fields TextField surnameAlias = new TextField("surnameAlias"); TextField previousPostcode = new TextField("previousPostcode"); form.add(surnameAlias, previousPostcode); // More info RadarRequiredTextField hospitalNumber = new RadarRequiredTextField("hospitalNumber", form, componentsToUpdateList); TextField nhsNumber = new TextField("nhsNumber"); TextField renalRegistryNumber = new TextField("renalRegistryNumber"); TextField ukTransplantNumber = new TextField("ukTransplantNumber"); TextField chiNumber = new TextField("chiNumber"); form.add(hospitalNumber, nhsNumber, renalRegistryNumber, ukTransplantNumber, chiNumber); // Status, consultants and centres drop down boxes DropDownChoice<Status> status = new DropDownChoice<Status>("status", demographicsManager.getStatuses(), new ChoiceRenderer<Status>("abbreviation", "id")); // Consultant and renal unit DropDownChoice<Consultant> consultant = new ConsultantDropDown("consultant"); DropDownChoice<Centre> renalUnit = new CentreDropDown("renalUnit"); form.add(status, consultant, renalUnit); CheckBox consent = new CheckBox("consent"); DropDownChoice<Centre> renalUnitAuthorised = new CentreDropDown("renalUnitAuthorised"); form.add(consent, renalUnitAuthorised); form.add(new BookmarkablePageLink("consentFormsLink", ConsentFormsPage.class)); final Label successMessage = RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdateList); Label errorMessage = RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdateList); AjaxSubmitLink ajaxSubmitLink = new AjaxSubmitLink("save") { @Override protected void onSubmit(AjaxRequestTarget ajaxRequestTarget, Form<?> form) { ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()])); successMessage.setVisible(true); ajaxRequestTarget.add(successMessage); } @Override protected void onError(AjaxRequestTarget ajaxRequestTarget, Form<?> form) { ajaxRequestTarget.add(componentsToUpdateList.toArray(new Component[componentsToUpdateList.size()])); successMessage.setVisible(false); ajaxRequestTarget.add(successMessage); } }; ajaxSubmitLink.add(new AttributeModifier("value", new AbstractReadOnlyModel() { @Override public Object getObject() { return radarNumberModel.getObject() == null ? "Add this patient" : "Update"; } })); form.add(ajaxSubmitLink); }
diff --git a/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/importer/SequenceFileSplitter.java b/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/importer/SequenceFileSplitter.java index 37ad8c98..64ebf7bb 100644 --- a/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/importer/SequenceFileSplitter.java +++ b/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/importer/SequenceFileSplitter.java @@ -1,117 +1,118 @@ package pl.edu.icm.cermine.pubmed.importer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Formatter; import java.util.Locale; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader; import org.apache.jute.RecordReader; import pl.edu.icm.cermine.pubmed.importer.model.DocumentProtos; import pl.edu.icm.cermine.pubmed.pig.PubmedCollectionIterator; import pl.edu.icm.cermine.pubmed.pig.PubmedEntry; import com.google.protobuf.ByteString; public class SequenceFileSplitter { public static void main(String[] args) throws IOException { if (args.length != 2 && args.length != 3) { System.out.println("Usage: <in_file> <out_dir> X"); System.exit(1); } String inputSequenceFile = args[0]; String outputSequenceFileDirectory = args[1]; Integer maximumPairs = Integer.valueOf(args[2]); checkPaths(inputSequenceFile, outputSequenceFileDirectory); splitSequenceFile(inputSequenceFile, outputSequenceFileDirectory, maximumPairs); } private static void checkPaths(String inputSequenceFile, String outputSequenceFileDirectory) throws IOException { File input = new File(inputSequenceFile); if (!input.exists()) { System.err.println("<Input file> does not exist: " + inputSequenceFile); System.exit(1); } File outf = new File(outputSequenceFileDirectory); if (!outf.getParentFile().exists()) { outf.getParentFile().mkdirs(); } if (!outf.exists()) { outf.mkdir(); } else if (!outf.isDirectory()) { System.err.println("<Output dir> is not a directory:" + outputSequenceFileDirectory); System.exit(1); } } private static void splitSequenceFile(String inputSequenceFile, String outputSequenceFileDirectory, Integer maximumPairs) throws IOException { System.out.println("MAX " + maximumPairs); SequenceFile.Writer sequenceFileWriter = null; Integer allRecordCounter = 0; Integer currentRecordCounter = 0; Integer outputFileCounter = 0; String inputFileName = new File(inputSequenceFile).getName(); String outputFileName = inputFileName+"_%04d"; StringBuilder stringBuilder = new StringBuilder(); Formatter formatter = new Formatter(stringBuilder, Locale.US); formatter.format(outputFileName, outputFileCounter); File outputFile = new File(outputSequenceFileDirectory, stringBuilder.toString()); sequenceFileWriter = createSequenceFileWriter(outputFile.getPath(), BytesWritable.class, BytesWritable.class); ++outputFileCounter; BytesWritable key = new BytesWritable(); BytesWritable value = new BytesWritable(); try { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); + @SuppressWarnings("deprecation") SequenceFile.Reader reader = new SequenceFile.Reader(fs, new Path(inputSequenceFile), conf); while(reader.next(key, value)) { if(currentRecordCounter.equals(maximumPairs)) { if(sequenceFileWriter != null) { sequenceFileWriter.close(); } stringBuilder.delete(0, stringBuilder.length()); outputFileName = inputFileName+"_%04d"; formatter.format(outputFileName, outputFileCounter); outputFile = new File(outputSequenceFileDirectory, stringBuilder.toString()); System.out.println("NEW FILE " + stringBuilder.toString()); sequenceFileWriter = createSequenceFileWriter(outputFile.getPath(), BytesWritable.class, BytesWritable.class); currentRecordCounter = 0; ++outputFileCounter; } System.out.println("FILE " + outputFileCounter + " RECORD " + currentRecordCounter + " (" +allRecordCounter+" TOTAL)"); sequenceFileWriter.append(key, value); ++currentRecordCounter; ++allRecordCounter; } } finally { sequenceFileWriter.close(); } } private static <T1, T2> SequenceFile.Writer createSequenceFileWriter(String uri, Class<T1> keyClass, Class<T2> valueClass) throws IOException { Configuration conf = new Configuration(); Path path = new Path(uri); SequenceFile.Writer writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(path), SequenceFile.Writer.keyClass(keyClass), SequenceFile.Writer.valueClass(valueClass), SequenceFile.Writer.bufferSize(1<<25)); // FileSystem fs = FileSystem.get(URI.create(uri), conf); // SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, path, keyClass, valueClass); return writer; } }
true
true
private static void splitSequenceFile(String inputSequenceFile, String outputSequenceFileDirectory, Integer maximumPairs) throws IOException { System.out.println("MAX " + maximumPairs); SequenceFile.Writer sequenceFileWriter = null; Integer allRecordCounter = 0; Integer currentRecordCounter = 0; Integer outputFileCounter = 0; String inputFileName = new File(inputSequenceFile).getName(); String outputFileName = inputFileName+"_%04d"; StringBuilder stringBuilder = new StringBuilder(); Formatter formatter = new Formatter(stringBuilder, Locale.US); formatter.format(outputFileName, outputFileCounter); File outputFile = new File(outputSequenceFileDirectory, stringBuilder.toString()); sequenceFileWriter = createSequenceFileWriter(outputFile.getPath(), BytesWritable.class, BytesWritable.class); ++outputFileCounter; BytesWritable key = new BytesWritable(); BytesWritable value = new BytesWritable(); try { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); SequenceFile.Reader reader = new SequenceFile.Reader(fs, new Path(inputSequenceFile), conf); while(reader.next(key, value)) { if(currentRecordCounter.equals(maximumPairs)) { if(sequenceFileWriter != null) { sequenceFileWriter.close(); } stringBuilder.delete(0, stringBuilder.length()); outputFileName = inputFileName+"_%04d"; formatter.format(outputFileName, outputFileCounter); outputFile = new File(outputSequenceFileDirectory, stringBuilder.toString()); System.out.println("NEW FILE " + stringBuilder.toString()); sequenceFileWriter = createSequenceFileWriter(outputFile.getPath(), BytesWritable.class, BytesWritable.class); currentRecordCounter = 0; ++outputFileCounter; } System.out.println("FILE " + outputFileCounter + " RECORD " + currentRecordCounter + " (" +allRecordCounter+" TOTAL)"); sequenceFileWriter.append(key, value); ++currentRecordCounter; ++allRecordCounter; } } finally { sequenceFileWriter.close(); } }
private static void splitSequenceFile(String inputSequenceFile, String outputSequenceFileDirectory, Integer maximumPairs) throws IOException { System.out.println("MAX " + maximumPairs); SequenceFile.Writer sequenceFileWriter = null; Integer allRecordCounter = 0; Integer currentRecordCounter = 0; Integer outputFileCounter = 0; String inputFileName = new File(inputSequenceFile).getName(); String outputFileName = inputFileName+"_%04d"; StringBuilder stringBuilder = new StringBuilder(); Formatter formatter = new Formatter(stringBuilder, Locale.US); formatter.format(outputFileName, outputFileCounter); File outputFile = new File(outputSequenceFileDirectory, stringBuilder.toString()); sequenceFileWriter = createSequenceFileWriter(outputFile.getPath(), BytesWritable.class, BytesWritable.class); ++outputFileCounter; BytesWritable key = new BytesWritable(); BytesWritable value = new BytesWritable(); try { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); @SuppressWarnings("deprecation") SequenceFile.Reader reader = new SequenceFile.Reader(fs, new Path(inputSequenceFile), conf); while(reader.next(key, value)) { if(currentRecordCounter.equals(maximumPairs)) { if(sequenceFileWriter != null) { sequenceFileWriter.close(); } stringBuilder.delete(0, stringBuilder.length()); outputFileName = inputFileName+"_%04d"; formatter.format(outputFileName, outputFileCounter); outputFile = new File(outputSequenceFileDirectory, stringBuilder.toString()); System.out.println("NEW FILE " + stringBuilder.toString()); sequenceFileWriter = createSequenceFileWriter(outputFile.getPath(), BytesWritable.class, BytesWritable.class); currentRecordCounter = 0; ++outputFileCounter; } System.out.println("FILE " + outputFileCounter + " RECORD " + currentRecordCounter + " (" +allRecordCounter+" TOTAL)"); sequenceFileWriter.append(key, value); ++currentRecordCounter; ++allRecordCounter; } } finally { sequenceFileWriter.close(); } }