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/branches/4.0.0/CruxGWTWidgets/src/br/com/sysmap/crux/gwt/client/DisclosurePanelFactory.java b/branches/4.0.0/CruxGWTWidgets/src/br/com/sysmap/crux/gwt/client/DisclosurePanelFactory.java
index fd1491d9d..98df11094 100644
--- a/branches/4.0.0/CruxGWTWidgets/src/br/com/sysmap/crux/gwt/client/DisclosurePanelFactory.java
+++ b/branches/4.0.0/CruxGWTWidgets/src/br/com/sysmap/crux/gwt/client/DisclosurePanelFactory.java
@@ -1,132 +1,137 @@
/*
* Copyright 2009 Sysmap Solutions Software e Consultoria Ltda.
*
* 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 br.com.sysmap.crux.gwt.client;
import br.com.sysmap.crux.core.client.declarative.DeclarativeFactory;
import br.com.sysmap.crux.core.client.declarative.TagAttribute;
import br.com.sysmap.crux.core.client.declarative.TagAttributeDeclaration;
import br.com.sysmap.crux.core.client.declarative.TagAttributes;
import br.com.sysmap.crux.core.client.declarative.TagAttributesDeclaration;
import br.com.sysmap.crux.core.client.declarative.TagChild;
import br.com.sysmap.crux.core.client.declarative.TagChildAttributes;
import br.com.sysmap.crux.core.client.declarative.TagChildLazyCondition;
import br.com.sysmap.crux.core.client.declarative.TagChildLazyConditions;
import br.com.sysmap.crux.core.client.declarative.TagChildren;
import br.com.sysmap.crux.core.client.screen.InterfaceConfigException;
import br.com.sysmap.crux.core.client.screen.LazyPanel;
import br.com.sysmap.crux.core.client.screen.WidgetFactoryContext;
import br.com.sysmap.crux.core.client.screen.children.AnyWidgetChildProcessor;
import br.com.sysmap.crux.core.client.screen.children.WidgetChildProcessor;
import br.com.sysmap.crux.core.client.screen.factory.HasAnimationFactory;
import br.com.sysmap.crux.core.client.screen.factory.HasCloseHandlersFactory;
import br.com.sysmap.crux.core.client.screen.factory.HasOpenHandlersFactory;
import br.com.sysmap.crux.core.client.screen.parser.CruxMetaDataElement;
import br.com.sysmap.crux.core.client.utils.StringUtils;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.user.client.ui.DisclosurePanel;
/**
* Factory for DisclosurePanel widgets
* @author Gesse S. F. Dafe
*/
@DeclarativeFactory(id="disclosurePanel", library="gwt")
public class DisclosurePanelFactory extends CompositeFactory<DisclosurePanel, WidgetFactoryContext>
implements HasAnimationFactory<DisclosurePanel, WidgetFactoryContext>,
HasOpenHandlersFactory<DisclosurePanel, WidgetFactoryContext>,
HasCloseHandlersFactory<DisclosurePanel, WidgetFactoryContext>
{
protected GWTMessages messages = GWT.create(GWTMessages.class);
@Override
public DisclosurePanel instantiateWidget(CruxMetaDataElement element, String widgetId)
{
String headerText = element.getProperty("headerText");
final DisclosurePanel ret;
if (!StringUtils.isEmpty(headerText))
{
ret = new DisclosurePanel(headerText);
}
else
{
ret = new DisclosurePanel();
}
String open = element.getProperty("open");
if (open == null || !StringUtils.unsafeEquals(open, "true"))
{
ret.addOpenHandler(new OpenHandler<DisclosurePanel>() {
+ private boolean loaded = false;
public void onOpen(OpenEvent<DisclosurePanel> event)
{
- LazyPanel widget = (LazyPanel)ret.getContent();
- widget.ensureWidget();
+ if (!loaded)
+ {
+ LazyPanel widget = (LazyPanel)ret.getContent();
+ widget.ensureWidget();
+ loaded = true;
+ }
}
});
}
return ret;
}
@Override
@TagAttributes({
@TagAttribute(value="open", type=Boolean.class)
})
@TagAttributesDeclaration({
@TagAttributeDeclaration("headerText")
})
public void processAttributes(WidgetFactoryContext context) throws InterfaceConfigException
{
super.processAttributes(context);
}
@Override
@TagChildren({
@TagChild(HeaderProcessor.class),
@TagChild(ContentProcessor.class)
})
public void processChildren(WidgetFactoryContext context) throws InterfaceConfigException {}
@TagChildAttributes(minOccurs="0", tagName="widgetHeader")
public static class HeaderProcessor extends WidgetChildProcessor<DisclosurePanel, WidgetFactoryContext>
{
@Override
@TagChildren({
@TagChild(WidgetHeaderProcessor.class)
})
public void processChildren(WidgetFactoryContext context) throws InterfaceConfigException {}
}
@TagChildAttributes(minOccurs="0", tagName="widgetContent")
public static class ContentProcessor extends WidgetChildProcessor<DisclosurePanel, WidgetFactoryContext>
{
@Override
@TagChildren({
@TagChild(WidgetProcessor.class)
})
public void processChildren(WidgetFactoryContext context) throws InterfaceConfigException {}
}
@TagChildAttributes(widgetProperty="content")
@TagChildLazyConditions(all={
@TagChildLazyCondition(property="open", notEquals="true")
})
public static class WidgetProcessor extends AnyWidgetChildProcessor<DisclosurePanel, WidgetFactoryContext> {}
@TagChildAttributes(widgetProperty="header")
public static class WidgetHeaderProcessor extends AnyWidgetChildProcessor<DisclosurePanel, WidgetFactoryContext> {}
}
| false | true | public DisclosurePanel instantiateWidget(CruxMetaDataElement element, String widgetId)
{
String headerText = element.getProperty("headerText");
final DisclosurePanel ret;
if (!StringUtils.isEmpty(headerText))
{
ret = new DisclosurePanel(headerText);
}
else
{
ret = new DisclosurePanel();
}
String open = element.getProperty("open");
if (open == null || !StringUtils.unsafeEquals(open, "true"))
{
ret.addOpenHandler(new OpenHandler<DisclosurePanel>() {
public void onOpen(OpenEvent<DisclosurePanel> event)
{
LazyPanel widget = (LazyPanel)ret.getContent();
widget.ensureWidget();
}
});
}
return ret;
}
| public DisclosurePanel instantiateWidget(CruxMetaDataElement element, String widgetId)
{
String headerText = element.getProperty("headerText");
final DisclosurePanel ret;
if (!StringUtils.isEmpty(headerText))
{
ret = new DisclosurePanel(headerText);
}
else
{
ret = new DisclosurePanel();
}
String open = element.getProperty("open");
if (open == null || !StringUtils.unsafeEquals(open, "true"))
{
ret.addOpenHandler(new OpenHandler<DisclosurePanel>() {
private boolean loaded = false;
public void onOpen(OpenEvent<DisclosurePanel> event)
{
if (!loaded)
{
LazyPanel widget = (LazyPanel)ret.getContent();
widget.ensureWidget();
loaded = true;
}
}
});
}
return ret;
}
|
diff --git a/postgresql/Field.java b/postgresql/Field.java
index 2beb1d2..a4cc3c7 100644
--- a/postgresql/Field.java
+++ b/postgresql/Field.java
@@ -1,103 +1,105 @@
package postgresql;
import java.lang.*;
import java.sql.*;
import java.util.*;
import postgresql.*;
/**
* postgresql.Field is a class used to describe fields in a PostgreSQL ResultSet
*
* @version 1.0 15-APR-1997
* @author <A HREF="mailto:[email protected]">Adrian Hall</A>
*/
public class Field
{
int length; // Internal Length of this field
int oid; // OID of the type
Connection conn; // Connection Instantation
String name; // Name of this field
int sql_type = -1; // The entry in java.sql.Types for this field
String type_name = null;// The sql type name
/**
* Construct a field based on the information fed to it.
*
* @param conn the connection this field came from
* @param name the name of the field
* @param oid the OID of the field
* @param len the length of the field
*/
public Field(Connection conn, String name, int oid, int length)
{
this.conn = conn;
this.name = name;
this.oid = oid;
this.length = length;
}
/**
* the ResultSet and ResultMetaData both need to handle the SQL
* type, which is gained from another query. Note that we cannot
* use getObject() in this, since getObject uses getSQLType().
*
* @return the entry in Types that refers to this field
* @exception SQLException if a database access error occurs
*/
public int getSQLType() throws SQLException
{
if (sql_type == -1)
{
ResultSet result = (postgresql.ResultSet)conn.ExecSQL("select typname from pg_type where oid = " + oid);
if (result.getColumnCount() != 1 || result.getTupleCount() != 1)
throw new SQLException("Unexpected return from query for type");
result.next();
type_name = result.getString(1);
if (type_name.equals("int2"))
sql_type = Types.SMALLINT;
else if (type_name.equals("int4"))
sql_type = Types.INTEGER;
else if (type_name.equals("int8"))
sql_type = Types.BIGINT;
else if (type_name.equals("cash"))
sql_type = Types.DECIMAL;
else if (type_name.equals("money"))
sql_type = Types.DECIMAL;
else if (type_name.equals("float4"))
sql_type = Types.REAL;
else if (type_name.equals("float8"))
sql_type = Types.DOUBLE;
else if (type_name.equals("bpchar"))
sql_type = Types.CHAR;
else if (type_name.equals("varchar"))
sql_type = Types.VARCHAR;
else if (type_name.equals("bool"))
sql_type = Types.BIT;
else if (type_name.equals("date"))
sql_type = Types.DATE;
else if (type_name.equals("time"))
sql_type = Types.TIME;
else if (type_name.equals("abstime"))
sql_type = Types.TIMESTAMP;
+ else if (type_name.equals("timestamp"))
+ sql_type = Types.TIMESTAMP;
else
sql_type = Types.OTHER;
}
return sql_type;
}
/**
* We also need to get the type name as returned by the back end.
* This is held in type_name AFTER a call to getSQLType. Since
* we get this information within getSQLType (if it isn't already
* done), we can just call getSQLType and throw away the result.
*
* @return the String representation of the type of this field
* @exception SQLException if a database access error occurs
*/
public String getTypeName() throws SQLException
{
int sql = getSQLType();
return type_name;
}
}
| true | true | public int getSQLType() throws SQLException
{
if (sql_type == -1)
{
ResultSet result = (postgresql.ResultSet)conn.ExecSQL("select typname from pg_type where oid = " + oid);
if (result.getColumnCount() != 1 || result.getTupleCount() != 1)
throw new SQLException("Unexpected return from query for type");
result.next();
type_name = result.getString(1);
if (type_name.equals("int2"))
sql_type = Types.SMALLINT;
else if (type_name.equals("int4"))
sql_type = Types.INTEGER;
else if (type_name.equals("int8"))
sql_type = Types.BIGINT;
else if (type_name.equals("cash"))
sql_type = Types.DECIMAL;
else if (type_name.equals("money"))
sql_type = Types.DECIMAL;
else if (type_name.equals("float4"))
sql_type = Types.REAL;
else if (type_name.equals("float8"))
sql_type = Types.DOUBLE;
else if (type_name.equals("bpchar"))
sql_type = Types.CHAR;
else if (type_name.equals("varchar"))
sql_type = Types.VARCHAR;
else if (type_name.equals("bool"))
sql_type = Types.BIT;
else if (type_name.equals("date"))
sql_type = Types.DATE;
else if (type_name.equals("time"))
sql_type = Types.TIME;
else if (type_name.equals("abstime"))
sql_type = Types.TIMESTAMP;
else
sql_type = Types.OTHER;
}
return sql_type;
}
| public int getSQLType() throws SQLException
{
if (sql_type == -1)
{
ResultSet result = (postgresql.ResultSet)conn.ExecSQL("select typname from pg_type where oid = " + oid);
if (result.getColumnCount() != 1 || result.getTupleCount() != 1)
throw new SQLException("Unexpected return from query for type");
result.next();
type_name = result.getString(1);
if (type_name.equals("int2"))
sql_type = Types.SMALLINT;
else if (type_name.equals("int4"))
sql_type = Types.INTEGER;
else if (type_name.equals("int8"))
sql_type = Types.BIGINT;
else if (type_name.equals("cash"))
sql_type = Types.DECIMAL;
else if (type_name.equals("money"))
sql_type = Types.DECIMAL;
else if (type_name.equals("float4"))
sql_type = Types.REAL;
else if (type_name.equals("float8"))
sql_type = Types.DOUBLE;
else if (type_name.equals("bpchar"))
sql_type = Types.CHAR;
else if (type_name.equals("varchar"))
sql_type = Types.VARCHAR;
else if (type_name.equals("bool"))
sql_type = Types.BIT;
else if (type_name.equals("date"))
sql_type = Types.DATE;
else if (type_name.equals("time"))
sql_type = Types.TIME;
else if (type_name.equals("abstime"))
sql_type = Types.TIMESTAMP;
else if (type_name.equals("timestamp"))
sql_type = Types.TIMESTAMP;
else
sql_type = Types.OTHER;
}
return sql_type;
}
|
diff --git a/view/GamePanel.java b/view/GamePanel.java
index 249cb73..4e1c640 100644
--- a/view/GamePanel.java
+++ b/view/GamePanel.java
@@ -1,520 +1,522 @@
package view;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import model.Card;
import model.FriendCards;
import model.Game;
import model.GameProperties;
import model.Play;
import model.Player;
import model.Trick;
public class GamePanel extends JPanel
{
private static final long serialVersionUID = 7889326310244251698L;
private BufferedImage[][] CARD_IMAGES;
private BufferedImage BIG_JOKER_IMAGE, SMALL_JOKER_IMAGE;
private BufferedImage CARD_BACK_IMAGE;
private HumanView view;
private Game game;
private Map<Card, CardPosition> cardPositions;
private boolean showPreviousTrick;
public GamePanel(HumanView view)
{
setBackground(Color.GREEN);
this.view = view;
}
public void loadImages() throws IOException
{
CARD_IMAGES = new BufferedImage[13][4];
for (int i = 0; i < CARD_IMAGES.length; i++)
for (int j = 0; j < CARD_IMAGES[i].length; j++)
{
String resource = String.format("/images/%c%s.gif",
"shdc".charAt(j),
"2 3 4 5 6 7 8 9 10 j q k 1".split(" ")[i]);
CARD_IMAGES[i][j] = ImageIO.read(getClass().getResource(resource));
}
BIG_JOKER_IMAGE = ImageIO.read(getClass().getResource("/images/jr.gif"));
SMALL_JOKER_IMAGE = ImageIO.read(getClass().getResource("/images/jb.gif"));
CARD_BACK_IMAGE = ImageIO.read(getClass().getResource("/images/b1fv.gif"));
}
public void setGame(Game game)
{
this.game = game;
this.cardPositions = new HashMap<Card, CardPosition>();
for (MouseListener listener : getMouseListeners())
removeMouseListener(listener);
addMouseListener(new CardSelectListener());
addMouseListener(new ShowPreviousTrickListener());
new Timer().schedule(new TimerTask()
{
public void run()
{
synchronized (cardPositions)
{
for (CardPosition position : cardPositions.values())
position.snap();
}
repaint();
}
}, 50, 50);
}
public List<Card> getSelected()
{
List<Card> selectedCards = new ArrayList<Card>();
synchronized (cardPositions)
{
for (Card card : cardPositions.keySet())
if (cardPositions.get(card).selected())
selectedCards.add(card);
}
return selectedCards;
}
public void resetSelected()
{
synchronized (cardPositions)
{
for (Card card : cardPositions.keySet())
cardPositions.get(card).setSelected(false);
}
repaint();
}
public void moveCardsToDeck()
{
cardPositions.clear();
}
public void moveCardToHand(Card card, int playerID)
{
moveCard(card, handLocation(playerID, card), !view.joinedGame()
|| playerID == view.getPlayerID(), 0.5);
}
public void moveCardToTable(Card card, int playerID)
{
moveCard(card, tableLocation(playerID, card), true, 0.3);
}
public void moveCardAway(Card card, int playerID)
{
moveCard(card, awayLocation(playerID), true, 0.2);
}
public void showPreviousTrick(boolean flag)
{
showPreviousTrick = flag;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
synchronized (view)
{
if (game == null)
return;
drawGameInformation(g);
drawGameScores(g);
drawSpecialInformation(g);
if (!game.started())
return;
drawRoundScores(g);
/* Draw deck */
if (game.deckHasCards())
drawDeck(g);
else if (game.getState() == Game.State.AWAITING_PLAY)
drawShowPreviousTrickButton(g);
drawCards(g);
}
}
private void moveCard(Card card, Point point, boolean faceUp,
double snapRatio)
{
synchronized (cardPositions)
{
if (!cardPositions.containsKey(card))
cardPositions
.put(card, new CardPosition(deckLocation(), false));
cardPositions.get(card).setDest(point, faceUp, snapRatio);
}
}
private void drawGameInformation(Graphics g)
{
Font font = new Font("Times New Roman", 0, 14);
g.setFont(font);
g.setColor(Color.BLACK);
FontMetrics fm = g.getFontMetrics();
int lineDiff = fm.getHeight() + 4;
/* Draw game information */
int y = 0;
g.drawString("Trump value: " + game.getTrumpValue(), 10, y += lineDiff);
g.drawString("Trump suit: "
+ (game.getTrumpSuit() == Card.SUIT.TRUMP ? '\u2668'
: (char) (game.getTrumpSuit().ordinal() + '\u2660')),
10, y += lineDiff);
g.drawString("Starter: " + game.getMaster().name, 10, y += lineDiff);
/* Draw player names */
List<Player> players = game.getPlayers();
for (Player player : players)
{
double angle = getAngle(player.ID);
int startX = (int) (450 * (1 + 0.9 * Math.sin(angle)));
int startY = (int) (350 * (1 + 0.9 * Math.cos(angle)));
String s = player.name;
AffineTransform at = new AffineTransform();
double transformAngle = (Math.cos(angle) < 1e-10 ? Math.PI - angle
: -angle);
at.rotate(transformAngle);
g.setFont(font.deriveFont(at));
int width = fm.stringWidth(s);
if (game.getTeam(player.ID) == game.getTeam(game.getMaster().ID))
g.setColor(Color.BLACK);
else
g.setColor(Color.BLUE);
g.drawString(s, (int) (startX - Math.cos(transformAngle) * width
/ 2), (int) (startY - Math.sin(transformAngle) * width / 2));
}
}
private void drawGameScores(Graphics g)
{
g.setFont(new Font("Times New Roman", 0, 14));
g.setColor(Color.BLACK);
FontMetrics fm = g.getFontMetrics();
int lineDiff = fm.getHeight() + 4;
int y = 0;
String s = "Scores";
g.drawString(s, 890 - fm.stringWidth(s), y += lineDiff);
Map<Integer, Integer> playerScores = game.getPlayerScores();
for (int playerID : playerScores.keySet())
{
s = game.getPlayerWithID(playerID).name + ": "
+ Card.VALUE.values()[playerScores.get(playerID)];
g.drawString(s, 890 - fm.stringWidth(s), y += lineDiff);
}
}
private void drawRoundScores(Graphics g)
{
g.setFont(new Font("Times New Roman", 0, 14));
g.setColor(Color.BLUE);
FontMetrics fm = g.getFontMetrics();
int lineDiff = fm.getHeight() + 4;
Map<String, Integer> teamScores = game.getTeamScores();
int y = 640 - lineDiff * teamScores.size();
for (String teamName : teamScores.keySet())
{
String s = teamName + ": " + teamScores.get(teamName);
g.drawString(s, 10, y += lineDiff);
}
}
private void drawSpecialInformation(Graphics g)
{
g.setFont(new Font("Times New Roman", 0, 14));
g.setColor(Color.BLACK);
FontMetrics fm = g.getFontMetrics();
int lineDiff = fm.getHeight() + 4;
GameProperties properties = game.getProperties();
FriendCards friendCards = game.getFriendCards();
int y = 640 - lineDiff
* (1 + (properties.find_a_friend ? 1 : 0) + friendCards.size());
String s = properties.numDecks + " decks";
g.drawString(s, 890 - fm.stringWidth(s), y += lineDiff);
if (properties.find_a_friend)
{
s = "Find a friend!"
+ (friendCards.isEmpty() ? "" : " Looking for:");
g.drawString(s, 890 - fm.stringWidth(s), y += lineDiff);
}
Map<Card, Integer> friendCardsMap = friendCards.getFriendCards();
for (Card card : friendCardsMap.keySet())
{
int index = friendCardsMap.get(card);
String indexStr;
if (index == 1)
indexStr = "next";
else if (index == 2)
indexStr = "second";
else if (index == 3)
indexStr = "third";
else
indexStr = index + "th";
s = "the "
+ indexStr
+ " "
+ card.value.toString().toLowerCase().replace("_", " ")
+ (card.value == Card.VALUE.SMALL_JOKER
|| card.value == Card.VALUE.BIG_JOKER ? "" : " of "
+ card.suit.toString().toLowerCase() + "s");
g.drawString(s, 890 - fm.stringWidth(s), y += lineDiff);
}
}
private void drawDeck(Graphics g)
{
g.drawImage(CARD_BACK_IMAGE, 415, 300, null);
}
private void drawShowPreviousTrickButton(Graphics g)
{
// TODO make fancier button.
g.setFont(new Font("Times New Roman", 0, 14));
g.setColor(Color.BLACK);
FontMetrics fm = g.getFontMetrics();
String s = "Show prev";
g.drawString(s, 450 - fm.stringWidth(s) / 2, 350 - fm.getHeight());
}
private void drawCards(Graphics g)
{
synchronized (cardPositions)
{
Set<Card> denotedCards = new HashSet<Card>();
for (Player player : game.getPlayers())
{
for (Card card : memoizeSortedHandCards(player.ID))
{
moveCardToHand(card, player.ID);
denotedCards.add(card);
}
for (Card card : memoizeTableCards(player.ID))
{
moveCardToTable(card, player.ID);
denotedCards.add(card);
}
}
Trick[] tricks =
{ game.getCurrentTrick(), game.getPreviousTrick() };
for (Trick trick : tricks)
if (trick.getWinningPlay() != null)
for (Play play : trick.getPlays())
for (Card card : play.getCards())
if (!denotedCards.contains(card))
{
moveCardAway(card, trick.getWinningPlay()
.getPlayerID());
denotedCards.add(card);
}
List<Card> cardsToDraw = new ArrayList<Card>(denotedCards);
Collections.sort(cardsToDraw, new Comparator<Card>()
{
public int compare(Card card1, Card card2)
{
CardPosition position1 = cardPositions.get(card1);
CardPosition position2 = cardPositions.get(card2);
+ if (position1.faceUp() != position2.faceUp())
+ return position1.faceUp() ? 1 : -1;
int score1 = position1.currX() + 5 * position1.currY();
int score2 = position2.currX() + 5 * position2.currY();
return score1 - score2;
}
});
for (Card card : cardsToDraw)
drawCard(card, g);
}
}
private Point deckLocation()
{
return new Point(415, 300);
}
private Point handLocation(int playerID, Card card)
{
double angle = getAngle(playerID);
int startX = (int) (450 * (1 + 0.7 * Math.sin(angle)));
int startY = (int) (350 * (1 + 0.7 * Math.cos(angle)));
List<Card> cards = memoizeSortedHandCards(playerID);
int cardIndex = cards.indexOf(card);
int cardDiff = (!view.joinedGame() || playerID == view.getPlayerID()) ? 14
: 9;
return new Point((int) (startX + cardDiff * Math.cos(angle)
* (cardIndex - cards.size() / 2.0) - 35),
(int) (startY - cardDiff * Math.sin(angle)
* (cardIndex - cards.size() / 2.0) - 48));
}
private Point tableLocation(int playerID, Card card)
{
double angle = getAngle(playerID);
int startX = (int) (450 * (1 + 0.4 * Math.sin(angle)));
int startY = (int) (350 * (1 + 0.4 * Math.cos(angle)));
List<Card> cards = memoizeTableCards(playerID);
int cardIndex = cards.indexOf(card);
return new Point((int) (startX + 24 * Math.cos(angle)
* (cardIndex - cards.size() / 2.0) - 35), (int) (startY - 24
* Math.sin(angle) * (cardIndex - cards.size() / 2.0) - 48));
}
private Point awayLocation(int playerID)
{
double angle = getAngle(playerID);
int startX = (int) (450 * (1 + 2 * Math.sin(angle)));
int startY = (int) (350 * (1 + 2 * Math.cos(angle)));
return new Point(startX, startY);
}
private double getAngle(int playerID)
{
List<Player> players = game.getPlayers();
int index = players.indexOf(game.getPlayerWithID(playerID));
if (view.joinedGame())
index -= players.indexOf(game.getPlayerWithID(view.getPlayerID()));
return 2 * Math.PI / players.size() * index;
}
private void drawCard(Card card, Graphics g)
{
CardPosition position = cardPositions.get(card);
BufferedImage image;
if (!position.faceUp())
image = CARD_BACK_IMAGE;
else if (card.value == Card.VALUE.BIG_JOKER)
image = BIG_JOKER_IMAGE;
else if (card.value == Card.VALUE.SMALL_JOKER)
image = SMALL_JOKER_IMAGE;
else
image = CARD_IMAGES[card.value.ordinal()][card.suit.ordinal()];
int y = position.selected() ? position.currY() - 20 : position.currY();
g.drawImage(image, position.currX(), y, null);
}
private Map<Integer, List<Card>> sortedHandCards = new HashMap<Integer, List<Card>>();
private Map<Integer, List<Card>> prevHandCards = new HashMap<Integer, List<Card>>();
private List<Card> memoizeSortedHandCards(int playerID)
{
List<Card> cards = game.getHand(playerID).getCards();
if (!cards.equals(prevHandCards.get(playerID)))
{
List<Card> sortedCards = new ArrayList<Card>(cards);
game.sortCards(sortedCards);
sortedHandCards.put(playerID, sortedCards);
prevHandCards.put(playerID, cards);
}
return sortedHandCards.get(playerID);
}
private Map<Integer, List<Card>> tableCards = new HashMap<Integer, List<Card>>();
private Map<Integer, List<Card>> prevTableCards = new HashMap<Integer, List<Card>>();
private List<Card> memoizeTableCards(int playerID)
{
List<Card> cards = Collections.emptyList();
if (game.getState() == Game.State.AWAITING_PLAY)
{
Play play = (showPreviousTrick ? game.getPreviousTrick() : game
.getCurrentTrick()).getPlayByID(playerID);
if (play != null)
cards = play.getCards();
}
else if (game.getState() == Game.State.AWAITING_RESTART
&& game.getKitty().getPlayerID() == playerID)
cards = game.getKitty().getCards();
else if (game.getShownCards() != null
&& game.getShownCards().getPlayerID() == playerID)
cards = game.getShownCards().getCards();
if (!cards.equals(prevTableCards.get(playerID)))
{
List<Card> sortedCards = new ArrayList<Card>(cards);
game.sortCards(sortedCards);
tableCards.put(playerID, sortedCards);
prevTableCards.put(playerID, cards);
}
return tableCards.get(playerID);
}
private class CardSelectListener extends MouseAdapter
{
@Override
public void mouseClicked(MouseEvent e)
{
if (!view.joinedGame())
return;
List<Card> cards = new ArrayList<Card>(
memoizeSortedHandCards(view.getPlayerID()));
Collections.reverse(cards);
for (Card card : cards)
{
CardPosition position = cardPositions.get(card);
if (e.getX() >= position.currX()
&& e.getX() < position.currX() + 71
&& e.getY() >= position.currY()
&& e.getY() < position.currY() + 96)
{
position.setSelected(!position.selected());
break;
}
}
repaint();
}
}
private class ShowPreviousTrickListener extends MouseAdapter
{
@Override
public void mousePressed(MouseEvent e)
{
if (Math.hypot(450 - e.getX(), 350 - e.getY()) < 50)
showPreviousTrick = true;
repaint();
}
@Override
public void mouseReleased(MouseEvent e)
{
showPreviousTrick = false;
repaint();
}
}
}
| true | true | private void drawCards(Graphics g)
{
synchronized (cardPositions)
{
Set<Card> denotedCards = new HashSet<Card>();
for (Player player : game.getPlayers())
{
for (Card card : memoizeSortedHandCards(player.ID))
{
moveCardToHand(card, player.ID);
denotedCards.add(card);
}
for (Card card : memoizeTableCards(player.ID))
{
moveCardToTable(card, player.ID);
denotedCards.add(card);
}
}
Trick[] tricks =
{ game.getCurrentTrick(), game.getPreviousTrick() };
for (Trick trick : tricks)
if (trick.getWinningPlay() != null)
for (Play play : trick.getPlays())
for (Card card : play.getCards())
if (!denotedCards.contains(card))
{
moveCardAway(card, trick.getWinningPlay()
.getPlayerID());
denotedCards.add(card);
}
List<Card> cardsToDraw = new ArrayList<Card>(denotedCards);
Collections.sort(cardsToDraw, new Comparator<Card>()
{
public int compare(Card card1, Card card2)
{
CardPosition position1 = cardPositions.get(card1);
CardPosition position2 = cardPositions.get(card2);
int score1 = position1.currX() + 5 * position1.currY();
int score2 = position2.currX() + 5 * position2.currY();
return score1 - score2;
}
});
for (Card card : cardsToDraw)
drawCard(card, g);
}
}
| private void drawCards(Graphics g)
{
synchronized (cardPositions)
{
Set<Card> denotedCards = new HashSet<Card>();
for (Player player : game.getPlayers())
{
for (Card card : memoizeSortedHandCards(player.ID))
{
moveCardToHand(card, player.ID);
denotedCards.add(card);
}
for (Card card : memoizeTableCards(player.ID))
{
moveCardToTable(card, player.ID);
denotedCards.add(card);
}
}
Trick[] tricks =
{ game.getCurrentTrick(), game.getPreviousTrick() };
for (Trick trick : tricks)
if (trick.getWinningPlay() != null)
for (Play play : trick.getPlays())
for (Card card : play.getCards())
if (!denotedCards.contains(card))
{
moveCardAway(card, trick.getWinningPlay()
.getPlayerID());
denotedCards.add(card);
}
List<Card> cardsToDraw = new ArrayList<Card>(denotedCards);
Collections.sort(cardsToDraw, new Comparator<Card>()
{
public int compare(Card card1, Card card2)
{
CardPosition position1 = cardPositions.get(card1);
CardPosition position2 = cardPositions.get(card2);
if (position1.faceUp() != position2.faceUp())
return position1.faceUp() ? 1 : -1;
int score1 = position1.currX() + 5 * position1.currY();
int score2 = position2.currX() + 5 * position2.currY();
return score1 - score2;
}
});
for (Card card : cardsToDraw)
drawCard(card, g);
}
}
|
diff --git a/src/glossa/external/ExternalSubprograms.java b/src/glossa/external/ExternalSubprograms.java
index a4ba90b..65784e7 100644
--- a/src/glossa/external/ExternalSubprograms.java
+++ b/src/glossa/external/ExternalSubprograms.java
@@ -1,383 +1,383 @@
/*
* The MIT License
*
* Copyright 2012 Georgios Migdos <[email protected]>.
*
* 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 glossa.external;
import glossa.interpreter.symboltable.symbols.RuntimeArray;
import glossa.interpreter.symboltable.symbols.RuntimeArrayItemWrapper;
import glossa.interpreter.symboltable.symbols.RuntimeVariable;
import glossa.interpreter.symboltable.symbols.ValueContainer;
import glossa.messages.Messages;
import glossa.statictypeanalysis.ExpressionResultForm;
import glossa.statictypeanalysis.scopetable.parameters.ActualParameter;
import glossa.types.Type;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
*
* @author cyberpython
*/
public class ExternalSubprograms {
//TODO: Procedures
private HashMap<String, ExternalFunction> functionCache;
private HashMap<String, ExternalProcedure> procedureCache;
public static ExternalSubprograms getInstance() {
return ExternalSubprogramsHolder.INSTANCE;
}
private static class ExternalSubprogramsHolder {
private static final ExternalSubprograms INSTANCE = new ExternalSubprograms();
}
private ExternalSubprograms() {
functionCache = new HashMap<String, ExternalFunction>();
procedureCache = new HashMap<String, ExternalProcedure>();
loadExternalSubprograms();
}
private void loadExternalSubprograms() {
//FIXME: external lib lookup directory
//TODO: maybe instead of loading the classes
// we should load the pair <subprogramName,className>
// and then load the appropriate class on demand
- File lookupDir = new File("/home/cyberpython/ΒΙΒΛΙΟΘΗΚΗ_ΓΛΩΣΣΑΣ");
+ File lookupDir = new File(System.getProperty("user.home")+System.getProperty("file.separator")+"ΒΙΒΛΙΟΘΗΚΗ_ΓΛΩΣΣΑΣ");
if (lookupDir.isDirectory()) {
File[] jarFiles = lookupDir.listFiles(new FileFilter() {
public boolean accept(File file) {
if (file.getAbsolutePath().toLowerCase().endsWith(".jar")) {
return true;
}
return false;
}
});
URL[] jarURLs = new URL[jarFiles.length];
for (int i = 0; i < jarURLs.length; i++) {
try {
jarURLs[i] = jarFiles[i].toURI().toURL();
} catch (MalformedURLException mue) {
//ignore jarfile
}
}
ClassLoader loader = URLClassLoader.newInstance(jarURLs);
for (File file : jarFiles) {
try {
JarFile jf = new JarFile(file);
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.toLowerCase().endsWith(".class")) {
name = name.replaceAll("\\/", ".").substring(0, name.length() - 6);
try {
Class clazz = loader.loadClass(name);
Class[] ifaces = clazz.getInterfaces();
boolean foundExternalFunc = false;
boolean foundExternalProc = false;
for (int i = 0; i < ifaces.length; i++) {
Class iface = ifaces[i];
if (iface.equals(ExternalFunction.class)) {
foundExternalFunc = true;
break;
}
if (iface.equals(ExternalProcedure.class)) {
foundExternalProc = true;
break;
}
}
if (foundExternalFunc) {
Class<? extends ExternalFunction> externalFuncClass = clazz.asSubclass(ExternalFunction.class);
Constructor<? extends ExternalFunction> ctor = externalFuncClass.getConstructor();
ExternalFunction f = ctor.newInstance();
functionCache.put(toCanonicalName(f.getName()), f);
} else if (foundExternalProc) {
Class<? extends ExternalProcedure> externalProcClass = clazz.asSubclass(ExternalProcedure.class);
Constructor<? extends ExternalProcedure> ctor = externalProcClass.getConstructor();
ExternalProcedure p = ctor.newInstance();
procedureCache.put(toCanonicalName(p.getName()), p);
}
} catch (ClassNotFoundException cnfe) {
//ignore
} catch (NoSuchMethodException nsme) {
//ignore
} catch (InstantiationException ie) {
//ignore
} catch (IllegalAccessException iae) {
//ignore
} catch (InvocationTargetException ite) {
//ignore
}
}
}
} catch (IOException ioe) {
}
}
}
}
public Type checkExternalFunctionCall(String functionName, List<ActualParameter> actualParameters) throws ExternalFunctionNotFoundException,
WrongParametersNumberForExternalSubprogramException,
WrongParameterTypesForExternalSubprogramException {
String searchKey = toCanonicalName(functionName);
ExternalFunction f = functionCache.get(searchKey);
if (f == null) {
throw new ExternalFunctionNotFoundException(functionName);
} else {
List<Parameter> params = f.getParametersList();
if (params.size() == actualParameters.size()) {
List<ParameterTypeMismatchInstance> mismatchedParamTypes = checkParameters(f, actualParameters);
if (mismatchedParamTypes.isEmpty()) {
return f.getReturnType();
} else {
throw new WrongParameterTypesForExternalSubprogramException(functionName, mismatchedParamTypes);
}
} else {
throw new WrongParametersNumberForExternalSubprogramException(functionName, params, actualParameters);
}
}
}
public void checkExternalProcedureCall(String procedureName, List<ActualParameter> actualParameters) throws ExternalProcedureNotFoundException,
WrongParametersNumberForExternalSubprogramException,
WrongParameterTypesForExternalSubprogramException {
String searchKey = toCanonicalName(procedureName);
ExternalProcedure proc = procedureCache.get(searchKey);
if (proc == null) {
throw new ExternalProcedureNotFoundException(procedureName);
} else {
List<Parameter> params = proc.getParametersList();
if (params.size() == actualParameters.size()) {
List<ParameterTypeMismatchInstance> mismatchedParamTypes = checkParameters(proc, actualParameters);
if (!mismatchedParamTypes.isEmpty()) {
throw new WrongParameterTypesForExternalSubprogramException(procedureName, mismatchedParamTypes);
}
} else {
throw new WrongParametersNumberForExternalSubprogramException(procedureName, params, actualParameters);
}
}
}
public Object callFunction(String functionName, List<Object> parameters) throws ExternalFunctionNotFoundException {
List<Object> parameterValues = new ArrayList<Object>();
for (Object object : parameters) {
if (object instanceof ValueContainer) {
parameterValues.add(((ValueContainer) object).getValue());
} else {
parameterValues.add(object);
}
}
String searchKey = toCanonicalName(functionName);
ExternalFunction f = functionCache.get(searchKey);
if (f == null) {
throw new ExternalFunctionNotFoundException(functionName);
} else {
return f.execute(parameterValues);
}
}
public void callProcedure(String procedureName, List<Object> parameters) throws ExternalProcedureNotFoundException {
List<Object> procParameters = new ArrayList<Object>();
for (Object object : parameters) {
if (object instanceof ValueContainer) {
procParameters.add(new ParameterValueWrapper(((ValueContainer) object).getValue())); //wrap the value and pass it to the procedure
} else if (object instanceof RuntimeArray) {
procParameters.add(object);
} else { // Just a value - wrap it and pass it along
procParameters.add(new ParameterValueWrapper(object));
}
}
String searchKey = toCanonicalName(procedureName);
ExternalProcedure proc = procedureCache.get(searchKey);
if (proc == null) {
throw new ExternalProcedureNotFoundException(procedureName);
} else {
proc.execute(procParameters);
for (int i = 0; i < parameters.size(); i++) {
Object object = parameters.get(i);
if ((object instanceof RuntimeVariable) || (object instanceof RuntimeArrayItemWrapper)) {
((ValueContainer) object).setValue(((ParameterValueWrapper) procParameters.get(i)).getValue());
}
}
}
}
private List<ParameterTypeMismatchInstance> checkParameters(ExternalSubProgram sub, List<ActualParameter> actualParams) {
List<ParameterTypeMismatchInstance> result = new ArrayList<ParameterTypeMismatchInstance>();
List<Parameter> params = sub.getParametersList();
Parameter param;
ActualParameter actualParam;
if (params.size() == actualParams.size()) {
for (int i = 0; i < params.size(); i++) {
param = params.get(i);
actualParam = actualParams.get(i);
if ((!param.getType().equals(actualParam.getType()))) { // param types differ
if (!(Type.REAL.equals(param.getType()) && Type.INTEGER.equals(actualParam.getType()))) {
result.add(new ParameterTypeMismatchInstance(i, param, actualParam));
} else { // integer actual param -> real formal param
if ((param.isArray() && (!(ExpressionResultForm.ARRAY.equals(actualParam.getForm()))))
|| ((!param.isArray()) && (ExpressionResultForm.ARRAY.equals(actualParam.getForm())))) {
result.add(new ParameterTypeMismatchInstance(i, param, actualParam));
}
}
} else {
if (param.isArray() && (!(ExpressionResultForm.ARRAY.equals(actualParam.getForm())))) {
result.add(new ParameterTypeMismatchInstance(i, param, actualParam));
}
}
}
return result;
}
throw new RuntimeException("Το πλήθος των πραγματικών παραμέτρων διαφέρει από των αναμενόμενων!");
}
private String toCanonicalName(String name) {
CharSequence tmp = name.toLowerCase();
StringBuilder sb = new StringBuilder();
char c;
for (int i = 0; i < tmp.length(); i++) {
c = tmp.charAt(i);
if (c == 'ά') {
sb.append('α');
} else if (c == 'έ') {
sb.append('ε');
} else if (c == 'ή') {
sb.append('η');
} else if ((c == 'ί') || (c == 'ϊ') || (c == 'ΐ')) {
sb.append('ι');
} else if ((c == 'ύ') || (c == 'ϋ') || (c == 'ΰ')) {
sb.append('υ');
} else if (c == 'ό') {
sb.append('ο');
} else if (c == 'ώ') {
sb.append('ω');
} else if (c == 'ς') {
sb.append('σ');
} else {
sb.append(c);
}
}
return sb.toString();
}
public final String getHTMLDocumentation(ExternalSubProgram sp) {
StringBuilder sb = new StringBuilder("<h1>");
ExternalFunction f = null;
if (sp instanceof ExternalFunction) {
f = (ExternalFunction) sp;
sb.append("Συνάρτηση ");
}
sb.append(sp.getName()).append("</h1>\n");
sb.append("<ul>\n");
if (f != null) {
sb.append(" <li> <strong>Τιμή επιστροφής:</strong> ").append(Messages.convertFirstLetterToUppercase(f.getReturnType().toString())).append("</li>\n");
}
List<Parameter> params = sp.getParametersList();
if (params.size() > 0) {
sb.append(" <li> <strong>Παράμετροι</strong> ").append("\n <ul>\n");
for (Parameter param : params) {
sb.append(" <li> <strong>").append(param.getName()).append(":</strong> ");
if (param.isArray()) {
sb.append("Πίνακας ").append(param.getType().toPluralPossesiveString());
} else {
sb.append(Messages.convertFirstLetterToUppercase(param.getType().toString()));
}
sb.append("</li>\n");
}
}
sb.append(" </ul>\n");
sb.append(" <li> <strong>Περιγραφή:</strong> ").append(sp.getDescription()).append("</li>\n");
sb.append("</ul>");
return sb.toString();
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
ExternalSubprograms xf = ExternalSubprograms.getInstance();
long instantiationTime = System.currentTimeMillis();
List params = new ArrayList();
long beforeLoopTime = System.currentTimeMillis();
int max = 10;
BigDecimal[] results = new BigDecimal[max];
BigDecimal[] randomValues = new BigDecimal[max];
for (int i = 0; i < max; i++) {
params.clear();
randomValues[i] = new BigDecimal(Math.random() * 100);
params.add(randomValues[i]);
try {
results[i] = (BigDecimal) xf.callFunction("κυβος", params);
} catch (ExternalFunctionNotFoundException e1) {
System.err.println(e1.getMessage());
}
}
long afterLoopTime = System.currentTimeMillis();
for (int i = 0; i < max; i++) {
System.out.println(String.format("%1$6.3f^3 = %2$6.3f", randomValues[i].doubleValue(), results[i].doubleValue()));
}
System.out.println();
System.out.println("--------------------------------");
System.out.println("Total time : " + (afterLoopTime - startTime) + " msec");
System.out.println("Instantiation time: " + (instantiationTime - startTime) + " msec");
System.out.println("Loop time : " + (afterLoopTime - beforeLoopTime) + " msec");
System.out.println("Average call time : " + ((afterLoopTime - beforeLoopTime) / ((double) max)) + " msec");
System.out.println("--------------------------------");
}
}
| true | true | private void loadExternalSubprograms() {
//FIXME: external lib lookup directory
//TODO: maybe instead of loading the classes
// we should load the pair <subprogramName,className>
// and then load the appropriate class on demand
File lookupDir = new File("/home/cyberpython/ΒΙΒΛΙΟΘΗΚΗ_ΓΛΩΣΣΑΣ");
if (lookupDir.isDirectory()) {
File[] jarFiles = lookupDir.listFiles(new FileFilter() {
public boolean accept(File file) {
if (file.getAbsolutePath().toLowerCase().endsWith(".jar")) {
return true;
}
return false;
}
});
URL[] jarURLs = new URL[jarFiles.length];
for (int i = 0; i < jarURLs.length; i++) {
try {
jarURLs[i] = jarFiles[i].toURI().toURL();
} catch (MalformedURLException mue) {
//ignore jarfile
}
}
ClassLoader loader = URLClassLoader.newInstance(jarURLs);
for (File file : jarFiles) {
try {
JarFile jf = new JarFile(file);
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.toLowerCase().endsWith(".class")) {
name = name.replaceAll("\\/", ".").substring(0, name.length() - 6);
try {
Class clazz = loader.loadClass(name);
Class[] ifaces = clazz.getInterfaces();
boolean foundExternalFunc = false;
boolean foundExternalProc = false;
for (int i = 0; i < ifaces.length; i++) {
Class iface = ifaces[i];
if (iface.equals(ExternalFunction.class)) {
foundExternalFunc = true;
break;
}
if (iface.equals(ExternalProcedure.class)) {
foundExternalProc = true;
break;
}
}
if (foundExternalFunc) {
Class<? extends ExternalFunction> externalFuncClass = clazz.asSubclass(ExternalFunction.class);
Constructor<? extends ExternalFunction> ctor = externalFuncClass.getConstructor();
ExternalFunction f = ctor.newInstance();
functionCache.put(toCanonicalName(f.getName()), f);
} else if (foundExternalProc) {
Class<? extends ExternalProcedure> externalProcClass = clazz.asSubclass(ExternalProcedure.class);
Constructor<? extends ExternalProcedure> ctor = externalProcClass.getConstructor();
ExternalProcedure p = ctor.newInstance();
procedureCache.put(toCanonicalName(p.getName()), p);
}
} catch (ClassNotFoundException cnfe) {
//ignore
} catch (NoSuchMethodException nsme) {
//ignore
} catch (InstantiationException ie) {
//ignore
} catch (IllegalAccessException iae) {
//ignore
} catch (InvocationTargetException ite) {
//ignore
}
}
}
} catch (IOException ioe) {
}
}
}
}
| private void loadExternalSubprograms() {
//FIXME: external lib lookup directory
//TODO: maybe instead of loading the classes
// we should load the pair <subprogramName,className>
// and then load the appropriate class on demand
File lookupDir = new File(System.getProperty("user.home")+System.getProperty("file.separator")+"ΒΙΒΛΙΟΘΗΚΗ_ΓΛΩΣΣΑΣ");
if (lookupDir.isDirectory()) {
File[] jarFiles = lookupDir.listFiles(new FileFilter() {
public boolean accept(File file) {
if (file.getAbsolutePath().toLowerCase().endsWith(".jar")) {
return true;
}
return false;
}
});
URL[] jarURLs = new URL[jarFiles.length];
for (int i = 0; i < jarURLs.length; i++) {
try {
jarURLs[i] = jarFiles[i].toURI().toURL();
} catch (MalformedURLException mue) {
//ignore jarfile
}
}
ClassLoader loader = URLClassLoader.newInstance(jarURLs);
for (File file : jarFiles) {
try {
JarFile jf = new JarFile(file);
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.toLowerCase().endsWith(".class")) {
name = name.replaceAll("\\/", ".").substring(0, name.length() - 6);
try {
Class clazz = loader.loadClass(name);
Class[] ifaces = clazz.getInterfaces();
boolean foundExternalFunc = false;
boolean foundExternalProc = false;
for (int i = 0; i < ifaces.length; i++) {
Class iface = ifaces[i];
if (iface.equals(ExternalFunction.class)) {
foundExternalFunc = true;
break;
}
if (iface.equals(ExternalProcedure.class)) {
foundExternalProc = true;
break;
}
}
if (foundExternalFunc) {
Class<? extends ExternalFunction> externalFuncClass = clazz.asSubclass(ExternalFunction.class);
Constructor<? extends ExternalFunction> ctor = externalFuncClass.getConstructor();
ExternalFunction f = ctor.newInstance();
functionCache.put(toCanonicalName(f.getName()), f);
} else if (foundExternalProc) {
Class<? extends ExternalProcedure> externalProcClass = clazz.asSubclass(ExternalProcedure.class);
Constructor<? extends ExternalProcedure> ctor = externalProcClass.getConstructor();
ExternalProcedure p = ctor.newInstance();
procedureCache.put(toCanonicalName(p.getName()), p);
}
} catch (ClassNotFoundException cnfe) {
//ignore
} catch (NoSuchMethodException nsme) {
//ignore
} catch (InstantiationException ie) {
//ignore
} catch (IllegalAccessException iae) {
//ignore
} catch (InvocationTargetException ite) {
//ignore
}
}
}
} catch (IOException ioe) {
}
}
}
}
|
diff --git a/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/Thrown.java b/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/Thrown.java
index 43ff76fced..63edd18a82 100644
--- a/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/Thrown.java
+++ b/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/Thrown.java
@@ -1,46 +1,46 @@
package org.rascalmpl.library.experiments.Compiler.RVM.Interpreter;
import java.io.PrintWriter;
import java.util.List;
import org.eclipse.imp.pdb.facts.ISourceLocation;
import org.eclipse.imp.pdb.facts.IValue;
public class Thrown extends RuntimeException {
private static final long serialVersionUID = 5789848344801944419L;
private static Thrown instance = new Thrown();
IValue value;
ISourceLocation loc;
List<Frame> stacktrace;
private Thrown() {
super();
this.value = null;
this.stacktrace = null;
}
public static Thrown getInstance(IValue value, ISourceLocation loc, List<Frame> stacktrace) {
instance.value = value;
instance.loc = loc;
instance.stacktrace = stacktrace;
return instance;
}
public String toString() {
return value.toString();
}
public void printStackTrace(PrintWriter stdout) {
stdout.println("Runtime exception: throw " + this.toString() + ((loc !=null) ? loc : "") );
for(Frame cf : stacktrace) {
- for(Frame f = cf; f != null; f = cf.previousCallFrame) {
+ for(Frame f = cf; f != null; f = f.previousCallFrame) {
stdout.println("at " + f.function.name);
}
}
}
}
| true | true | public void printStackTrace(PrintWriter stdout) {
stdout.println("Runtime exception: throw " + this.toString() + ((loc !=null) ? loc : "") );
for(Frame cf : stacktrace) {
for(Frame f = cf; f != null; f = cf.previousCallFrame) {
stdout.println("at " + f.function.name);
}
}
}
| public void printStackTrace(PrintWriter stdout) {
stdout.println("Runtime exception: throw " + this.toString() + ((loc !=null) ? loc : "") );
for(Frame cf : stacktrace) {
for(Frame f = cf; f != null; f = f.previousCallFrame) {
stdout.println("at " + f.function.name);
}
}
}
|
diff --git a/target_explorer/plugins/org.eclipse.tm.te.ui.views/src/org/eclipse/tm/te/ui/views/workingsets/pages/TargetWorkingSetPage.java b/target_explorer/plugins/org.eclipse.tm.te.ui.views/src/org/eclipse/tm/te/ui/views/workingsets/pages/TargetWorkingSetPage.java
index d47b43364..66ddc6e15 100644
--- a/target_explorer/plugins/org.eclipse.tm.te.ui.views/src/org/eclipse/tm/te/ui/views/workingsets/pages/TargetWorkingSetPage.java
+++ b/target_explorer/plugins/org.eclipse.tm.te.ui.views/src/org/eclipse/tm/te/ui/views/workingsets/pages/TargetWorkingSetPage.java
@@ -1,141 +1,141 @@
/*******************************************************************************
* Copyright (c) 2011 Wind River Systems, Inc. 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:
* William Chen (Wind River) [354578] Add support for working sets
*******************************************************************************/
package org.eclipse.tm.te.ui.views.workingsets.pages;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.tm.te.runtime.interfaces.workingsets.IWorkingSetElement;
import org.eclipse.tm.te.ui.trees.TreeArrayContentProvider;
import org.eclipse.tm.te.ui.views.ViewsUtil;
import org.eclipse.tm.te.ui.views.activator.UIPlugin;
import org.eclipse.tm.te.ui.views.interfaces.IUIConstants;
import org.eclipse.tm.te.ui.views.interfaces.ImageConsts;
import org.eclipse.tm.te.ui.views.internal.ViewRoot;
import org.eclipse.tm.te.ui.views.nls.Messages;
import org.eclipse.tm.te.ui.views.workingsets.WorkingSetElementHolder;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.navigator.CommonNavigator;
import org.eclipse.ui.navigator.INavigatorContentService;
/**
* A target working set page is a wizard page used to configure a custom defined
* working set. This wizard is used in the configure working set action to edit
* the working sets used in the working set viewer.
*/
public class TargetWorkingSetPage extends AbstractWorkingSetWizardPage {
// The target explorer view content service (Never dispose it in here!)
private INavigatorContentService contentService;
// The initial selection
private IStructuredSelection initialSelection;
/**
* Default constructor.
*/
public TargetWorkingSetPage() {
super("targetWorkingSetPage", Messages.TargetWorkingSetPage_title, UIPlugin.getImageDescriptor(ImageConsts.WORKING_SET)); //$NON-NLS-1$
setDescription(Messages.TargetWorkingSetPage_workingSet_description);
}
/**
* Set the initial selection.
* @param selection The initial selection
*/
public void setInitialSelection(IStructuredSelection selection) {
initialSelection = selection;
}
/* (non-Javadoc)
* @see org.eclipse.tm.te.tcf.ui.internal.workingsets.AbstractWorkingSetWizardPage#getPageId()
*/
@Override
protected String getPageId() {
return "org.eclipse.tm.te.tcf.ui.TargetWorkingSetPage"; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.tm.te.tcf.ui.internal.workingsets.AbstractWorkingSetWizardPage#configureTree(org.eclipse.jface.viewers.TreeViewer)
*/
@Override
protected void configureTree(TreeViewer tree) {
// Get the content service from the Target Explorer view.
IWorkbenchPart part = ViewsUtil.getPart(IUIConstants.ID_EXPLORER);
if (part instanceof CommonNavigator) {
contentService = ((CommonNavigator)part).getNavigatorContentService();
tree.setContentProvider(TreeArrayContentProvider.getInstance());
tree.setLabelProvider(contentService.createCommonLabelProvider());
// Filter out everything not implementing IWorkingSetElement
tree.addFilter(new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return element instanceof IWorkingSetElement;
}
});
// Initialize the tree input
tree.setInput(contentService.createCommonContentProvider().getElements(ViewRoot.getInstance()));
}
}
/* (non-Javadoc)
* @see org.eclipse.tm.te.tcf.ui.internal.workingsets.AbstractWorkingSetWizardPage#configureTable(org.eclipse.jface.viewers.TableViewer)
*/
@Override
protected void configureTable(TableViewer table) {
table.setLabelProvider(contentService.createCommonLabelProvider());
}
/* (non-Javadoc)
* @see org.eclipse.tm.te.tcf.ui.internal.workingsets.AbstractWorkingSetWizardPage#getInitialWorkingSetElements(org.eclipse.ui.IWorkingSet)
*/
@Override
protected Object[] getInitialWorkingSetElements(IWorkingSet workingSet) {
Object[] elements;
if (workingSet == null) {
if (initialSelection == null)
return new IAdaptable[0];
elements = initialSelection.toArray();
} else {
List<IWorkingSetElement> result = new ArrayList<IWorkingSetElement>();
for (IAdaptable adaptable : workingSet.getElements()) {
if (!(adaptable instanceof WorkingSetElementHolder)) continue;
WorkingSetElementHolder holder = (WorkingSetElementHolder) adaptable;
Assert.isNotNull(holder);
IWorkingSetElement element = holder.getElement();
// If the element is null, try to look up the element through the content provider
if (element == null) {
ITreeContentProvider contentProvider = (ITreeContentProvider)tree.getContentProvider();
- for (Object candidate : contentProvider.getElements(ViewRoot.getInstance())) {
+ for (Object candidate : contentProvider.getElements(tree.getInput())) {
if (candidate instanceof IWorkingSetElement && ((IWorkingSetElement)candidate).getElementId().equals(holder.getElementId())) {
holder.setElement((IWorkingSetElement)candidate);
element = holder.getElement();
break;
}
}
}
if (element != null) result.add(element);
}
elements = result.toArray();
}
return elements;
}
}
| true | true | protected Object[] getInitialWorkingSetElements(IWorkingSet workingSet) {
Object[] elements;
if (workingSet == null) {
if (initialSelection == null)
return new IAdaptable[0];
elements = initialSelection.toArray();
} else {
List<IWorkingSetElement> result = new ArrayList<IWorkingSetElement>();
for (IAdaptable adaptable : workingSet.getElements()) {
if (!(adaptable instanceof WorkingSetElementHolder)) continue;
WorkingSetElementHolder holder = (WorkingSetElementHolder) adaptable;
Assert.isNotNull(holder);
IWorkingSetElement element = holder.getElement();
// If the element is null, try to look up the element through the content provider
if (element == null) {
ITreeContentProvider contentProvider = (ITreeContentProvider)tree.getContentProvider();
for (Object candidate : contentProvider.getElements(ViewRoot.getInstance())) {
if (candidate instanceof IWorkingSetElement && ((IWorkingSetElement)candidate).getElementId().equals(holder.getElementId())) {
holder.setElement((IWorkingSetElement)candidate);
element = holder.getElement();
break;
}
}
}
if (element != null) result.add(element);
}
elements = result.toArray();
}
return elements;
}
| protected Object[] getInitialWorkingSetElements(IWorkingSet workingSet) {
Object[] elements;
if (workingSet == null) {
if (initialSelection == null)
return new IAdaptable[0];
elements = initialSelection.toArray();
} else {
List<IWorkingSetElement> result = new ArrayList<IWorkingSetElement>();
for (IAdaptable adaptable : workingSet.getElements()) {
if (!(adaptable instanceof WorkingSetElementHolder)) continue;
WorkingSetElementHolder holder = (WorkingSetElementHolder) adaptable;
Assert.isNotNull(holder);
IWorkingSetElement element = holder.getElement();
// If the element is null, try to look up the element through the content provider
if (element == null) {
ITreeContentProvider contentProvider = (ITreeContentProvider)tree.getContentProvider();
for (Object candidate : contentProvider.getElements(tree.getInput())) {
if (candidate instanceof IWorkingSetElement && ((IWorkingSetElement)candidate).getElementId().equals(holder.getElementId())) {
holder.setElement((IWorkingSetElement)candidate);
element = holder.getElement();
break;
}
}
}
if (element != null) result.add(element);
}
elements = result.toArray();
}
return elements;
}
|
diff --git a/src/de/sofd/draw2d/event/DrawingObjectRemoveEvent.java b/src/de/sofd/draw2d/event/DrawingObjectRemoveEvent.java
index c663d1a..b50872d 100644
--- a/src/de/sofd/draw2d/event/DrawingObjectRemoveEvent.java
+++ b/src/de/sofd/draw2d/event/DrawingObjectRemoveEvent.java
@@ -1,73 +1,73 @@
package de.sofd.draw2d.event;
import de.sofd.draw2d.Drawing;
import de.sofd.draw2d.DrawingObject;
/**
* Event indication that a {@link DrawingObject} is to be or has been removed
* from a {@link Drawing}.
*
* @author olaf
*/
public class DrawingObjectRemoveEvent extends DrawingEvent {
private static final long serialVersionUID = -436574494714032465L;
private final boolean isBeforeChange;
private final int index;
protected DrawingObjectRemoveEvent(Drawing source, boolean isBeforeChange, int index) {
super(source);
this.isBeforeChange = isBeforeChange;
this.index = index;
}
/**
*
* @return true iff the event indicates that the removal is imminent, but
* has not occured yet (so the object is still present in the
* drawing at position {@link #getIndex()})
*/
public boolean isBeforeChange() {
return isBeforeChange;
}
/**
*
* @return !{@link #isBeforeChange()}
*/
public boolean isAfterChange() {
return !isBeforeChange;
}
/**
*
* @return z-order index of the DrawingObject to be removed or having been
* removed
*/
public int getIndex() {
return index;
}
/**
*
* @return the DrawingObject this event refers to, if it can be retrieved
* from the Drawing (which is, if {@link #isBeforeChange()})
*/
public DrawingObject getObject() {
if (!isBeforeChange) {
- throw new IllegalStateException("can't determine to-be-removed DrawingObject for an after-DrawingObjectRemove event");
+ throw new IllegalStateException("can't determine removed DrawingObject for an after-DrawingObjectRemove event");
}
return getSource().get(getIndex());
}
// public "constructors"
public static DrawingObjectRemoveEvent newBeforeObjectRemoveEvent(Drawing source, int index) {
return new DrawingObjectRemoveEvent(source, true, index);
}
public static DrawingObjectRemoveEvent newAfterObjectRemoveEvent(Drawing source, int index) {
return new DrawingObjectRemoveEvent(source, false, index);
}
}
| true | true | public DrawingObject getObject() {
if (!isBeforeChange) {
throw new IllegalStateException("can't determine to-be-removed DrawingObject for an after-DrawingObjectRemove event");
}
return getSource().get(getIndex());
}
| public DrawingObject getObject() {
if (!isBeforeChange) {
throw new IllegalStateException("can't determine removed DrawingObject for an after-DrawingObjectRemove event");
}
return getSource().get(getIndex());
}
|
diff --git a/src/GedScanner.java b/src/GedScanner.java
index ce04672..b7444fe 100755
--- a/src/GedScanner.java
+++ b/src/GedScanner.java
@@ -1,382 +1,382 @@
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import uk.co.mmscomputing.device.scanner.Scanner;
import uk.co.mmscomputing.device.scanner.ScannerDevice;
import uk.co.mmscomputing.device.scanner.ScannerIOException;
import uk.co.mmscomputing.device.scanner.ScannerIOMetadata;
import uk.co.mmscomputing.device.scanner.ScannerIOMetadata.Type;
import uk.co.mmscomputing.device.scanner.ScannerListener;
public abstract class GedScanner extends Componente implements ScannerListener {
protected static final long serialVersionUID = -6485821906378910164L;
protected FileFilter EXTENCOES_SUPORTADAS = new ExtensionFilter("Imagens", new String[] {".jpg", ".jpeg"});
protected final String [] PREFIXOS_INTERFACES = new String[] {"WIA", "TWAIN", "SANE"};
protected Scanner scanner = null;
protected JComboBox scanners = null;
protected JCheckBox modoColorido = null;
protected JButton botaoDigitalizar = null;
protected boolean scannersDisponiveis = false;
protected List<String> nomesArquivos = new ArrayList<String>();
protected JButton botaoSelecionarArquivos = null;
protected JFileChooser chooserSelecionarVariosArquivos = null;
protected File[] arquivosSelecionados = null;
protected JButton botaoEnviarTudo = null;
protected abstract void inicializar();
public void init() {
try {
configurarLayout();
inicializar();
if(getParameter("id_documento") == null || getParameter("id_usuario") == null || getParameter("url_upload_pagina") == null){
throw new RuntimeException("Todos os parâmetros devem ser preenchidos.");
}
scannersDisponiveis = false;
if(isScannerValido()){
scanner.addListener(this);
modoColorido = new JCheckBox("Cor?", true);
botaoDigitalizar = new JButton("Digitalizar");
botaoDigitalizar.setMnemonic('D');
botaoDigitalizar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
digitalizar();
}
});
List<String> opcoes = new ArrayList<String>();
String [] listaScanners = scanner.getDeviceNames();
for(String nomeScanner : listaScanners){
boolean podeListar = true;
for(String prefixoInterface : PREFIXOS_INTERFACES){
if(nomeScanner.toLowerCase().contains(prefixoInterface.toLowerCase())){
podeListar = false;
break;
}
}
if(podeListar || listaScanners.length < 2){
opcoes.add(nomeScanner);
}
}
- if(opcoes.size() < 1 && nomesScanners.length > 0){
- for(String nomeScanner : nomesScanners){
+ if(opcoes.size() < 1 && listaScanners.length > 0){
+ for(String nomeScanner : listaScanners){
opcoes.add(nomeScanner);
}
}
scanners = new JComboBox(opcoes.toArray());
if(opcoes.size() > 0){
scanners.setSelectedIndex(0);
}
scannersDisponiveis = true;
}
chooserSelecionarVariosArquivos = new JFileChooser("Selecione os arquivos para serem enviados");
chooserSelecionarVariosArquivos.setMultiSelectionEnabled(true);
chooserSelecionarVariosArquivos.addChoosableFileFilter(EXTENCOES_SUPORTADAS);
botaoSelecionarArquivos = new JButton("Selecionar...");
botaoSelecionarArquivos.setMnemonic('S');
botaoSelecionarArquivos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean chooserFechado = (chooserSelecionarVariosArquivos.showOpenDialog(getContentPane()) == JFileChooser.APPROVE_OPTION);
File[] arquivosSelecionadosAgora = chooserSelecionarVariosArquivos.getSelectedFiles();
int tamanhoArquivosSelecionadosAgora = arquivosSelecionadosAgora.length;
if (chooserFechado == true && arquivosSelecionadosAgora != null && tamanhoArquivosSelecionadosAgora > 0) {
arquivosSelecionados = arquivosSelecionadosAgora;
botaoEnviarTudo.setEnabled(true);
botaoEnviarTudo.setText(getLabelBotaoEnviar(nomesArquivos.size() + arquivosSelecionados.length));
}
arquivosSelecionadosAgora = null;
}
});
botaoEnviarTudo = new JButton(getLabelBotaoEnviar(0));
botaoEnviarTudo.setMnemonic('O');
botaoEnviarTudo.setEnabled(false);
botaoEnviarTudo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enviarTudo();
}
});
configurarAlinhamento();
if(scannersDisponiveis == true){
getContentPane().add(scanners, getAlinhamento());
getContentPane().add(modoColorido, getAlinhamento());
getContentPane().add(botaoDigitalizar, getAlinhamento());
}
getContentPane().add(botaoSelecionarArquivos, getAlinhamento());
getContentPane().add(botaoEnviarTudo, getAlinhamento());
}
catch(Exception e){
e.printStackTrace();
}
}
public void update(Type type, ScannerIOMetadata metadata) {
try {
if (type.equals(ScannerIOMetadata.ACQUIRED)) {
BufferedImage imagemOriginal = metadata.getImage();
if(!modoColorido.isSelected()) {
BufferedImage imagemCinza = new BufferedImage(imagemOriginal.getWidth(), imagemOriginal.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics graphics = imagemCinza.getGraphics();
graphics.drawImage(imagemOriginal, 0, 0, null);
graphics.dispose();
graphics = null;
ImageIO.write(imagemCinza, "jpeg", new File(getNomeArquivo()));
imagemCinza = null;
}
else {
ImageIO.write(imagemOriginal, "jpeg", new File(getNomeArquivo()));
}
imagemOriginal = null;
}
else if (type.equals(ScannerIOMetadata.NEGOTIATE)) {
ScannerDevice device = metadata.getDevice();
device.setResolution(200);
device.setShowUserInterface(false);
}
else if (type.equals(ScannerIOMetadata.STATECHANGE)) {
System.err.println(metadata.getStateStr());
if (metadata.isFinished()) {
nomesArquivos.add(getNomeArquivo());
habilitarCampos();
if(arquivosSelecionados != null){
botaoEnviarTudo.setText(getLabelBotaoEnviar(nomesArquivos.size() + arquivosSelecionados.length));
}
else {
botaoEnviarTudo.setText(getLabelBotaoEnviar(nomesArquivos.size()));
}
}
}
else if (type.equals(ScannerIOMetadata.EXCEPTION)) {
metadata.getException().printStackTrace();
throw new RuntimeException(metadata.getException());
}
}
catch(Exception e){
try {
scanner.setCancel(true);
} catch (ScannerIOException e1) {
e1.printStackTrace();
}
habilitarCampos();
String mensagem = "Não foi possível realizar a operação!\nERRO: " + e.getMessage();
JOptionPane.showMessageDialog(this, mensagem, "Erro!", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
protected void digitalizar() {
try {
desabilitarCampos();
scanner.select(scanners.getSelectedItem().toString());
scanner.acquire();
}
catch(Exception e){
try {
scanner.setCancel(true);
} catch (ScannerIOException e1) {
e1.printStackTrace();
}
habilitarCampos();
String mensagem = "Não foi possível realizar a operação!\nERRO:" + e.getMessage();
JOptionPane.showMessageDialog(this, mensagem, "Erro!", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
protected void enviarTudo(){
enviarArquivosDigitalizados();
enviarArquivosUpload();
try {
String urlBase = getParameter("url_upload_pagina");
if(urlBase.contains("?")){
getAppletContext().showDocument(new URL(urlBase + "&id_documento=" + getParameter("id_documento") + "&ok=true"));
}
else {
getAppletContext().showDocument(new URL(urlBase + "?id_documento=" + getParameter("id_documento") + "&ok=true"));
}
}
catch(Exception e1){
habilitarCampos();
String mensagem = "Não foi possível realizar a operação!\n";
mensagem += "Ocorreu um erro ao enviar os dados.\n";
mensagem += "ERRO: "+ e1.getMessage() + ".";
JOptionPane.showMessageDialog(this, mensagem, "Erro!", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
protected void enviarArquivosDigitalizados() {
if(nomesArquivos == null || nomesArquivos.size() == 0){
return;
}
int contador = 1;
try {
desabilitarCampos();
URL url = new URL(getParameter("url_upload_pagina"));
for(String nomeArquivo : nomesArquivos){
File arquivo = new File(nomeArquivo);
arquivo.deleteOnExit();
String boundary = MultiPartFormOutputStream.createBoundary();
URLConnection requisicao = gerarRequisicao(boundary, url);
MultiPartFormOutputStream saida = new MultiPartFormOutputStream(requisicao.getOutputStream(), boundary);
saida.writeField("id_documento", getParameter("id_documento"));
saida.writeField("id_usuario", getParameter("id_usuario"));
anexarArquivo(arquivo, saida);
saida.close();
saida = null;
carregarResposta(requisicao);
contador += 1;
arquivo = null;
nomeArquivo = null;
}
}
catch(Exception e){
habilitarCampos();
String mensagem = "Não foi possível realizar a operação!\n";
mensagem += "Ocorreu um erro ao enviar a página #" + contador + ".\n";
mensagem += "ERRO: "+ e.getMessage() + ".";
JOptionPane.showMessageDialog(this, mensagem, "Erro!", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
protected void enviarArquivosUpload() {
if(arquivosSelecionados == null || arquivosSelecionados.length == 0){
return;
}
String arquivoAtual = null;
try {
desabilitarCampos();
URL url = new URL(getParameter("url_upload_pagina"));
for(File arquivo : arquivosSelecionados){
arquivoAtual = arquivo.getName();
String boundary = MultiPartFormOutputStream.createBoundary();
URLConnection requisicao = gerarRequisicao(boundary, url);
MultiPartFormOutputStream saida = new MultiPartFormOutputStream(requisicao.getOutputStream(), boundary);
saida.writeField("id_documento", getParameter("id_documento"));
saida.writeField("id_usuario", getParameter("id_usuario"));
anexarArquivo(arquivo, saida);
saida.close();
saida = null;
carregarResposta(requisicao);
arquivo = null;
arquivoAtual = null;
}
}
catch(Exception e){
tratarEExibirErro(e, arquivoAtual);
}
}
protected String getNomeArquivo(){
return System.getProperty("user.home") + File.separator + getParameter("id_documento") + "_" + nomesArquivos.size() + ".jpg";
}
protected boolean isScannerValido() throws Exception {
String erroPadrao = "Instale os aplicativos necessários para a digitalização.";
try {
if(!scanner.isAPIInstalled()){
throw new RuntimeException(erroPadrao);
}
if(scanner.getDeviceNames().length == 0){
throw new RuntimeException("Verifique se o scanner está instalado e conectado corretamente.");
}
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
@Override
protected void trocarCampos(boolean habilitar) {
if(scannersDisponiveis == true){
scanners.setEnabled(habilitar);
modoColorido.setEnabled(habilitar);
botaoDigitalizar.setEnabled(habilitar);
}
botaoSelecionarArquivos.setEnabled(habilitar);
if(habilitar == true){
boolean existemImagensDigitalizados = (nomesArquivos != null && nomesArquivos.size() > 0);
boolean existemArquivosSelecionados = (arquivosSelecionados != null && arquivosSelecionados.length > 0);
if(existemImagensDigitalizados || existemArquivosSelecionados){
botaoEnviarTudo.setEnabled(true);
}
}
else {
botaoEnviarTudo.setEnabled(false);
}
}
}
| true | true | public void init() {
try {
configurarLayout();
inicializar();
if(getParameter("id_documento") == null || getParameter("id_usuario") == null || getParameter("url_upload_pagina") == null){
throw new RuntimeException("Todos os parâmetros devem ser preenchidos.");
}
scannersDisponiveis = false;
if(isScannerValido()){
scanner.addListener(this);
modoColorido = new JCheckBox("Cor?", true);
botaoDigitalizar = new JButton("Digitalizar");
botaoDigitalizar.setMnemonic('D');
botaoDigitalizar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
digitalizar();
}
});
List<String> opcoes = new ArrayList<String>();
String [] listaScanners = scanner.getDeviceNames();
for(String nomeScanner : listaScanners){
boolean podeListar = true;
for(String prefixoInterface : PREFIXOS_INTERFACES){
if(nomeScanner.toLowerCase().contains(prefixoInterface.toLowerCase())){
podeListar = false;
break;
}
}
if(podeListar || listaScanners.length < 2){
opcoes.add(nomeScanner);
}
}
if(opcoes.size() < 1 && nomesScanners.length > 0){
for(String nomeScanner : nomesScanners){
opcoes.add(nomeScanner);
}
}
scanners = new JComboBox(opcoes.toArray());
if(opcoes.size() > 0){
scanners.setSelectedIndex(0);
}
scannersDisponiveis = true;
}
chooserSelecionarVariosArquivos = new JFileChooser("Selecione os arquivos para serem enviados");
chooserSelecionarVariosArquivos.setMultiSelectionEnabled(true);
chooserSelecionarVariosArquivos.addChoosableFileFilter(EXTENCOES_SUPORTADAS);
botaoSelecionarArquivos = new JButton("Selecionar...");
botaoSelecionarArquivos.setMnemonic('S');
botaoSelecionarArquivos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean chooserFechado = (chooserSelecionarVariosArquivos.showOpenDialog(getContentPane()) == JFileChooser.APPROVE_OPTION);
File[] arquivosSelecionadosAgora = chooserSelecionarVariosArquivos.getSelectedFiles();
int tamanhoArquivosSelecionadosAgora = arquivosSelecionadosAgora.length;
if (chooserFechado == true && arquivosSelecionadosAgora != null && tamanhoArquivosSelecionadosAgora > 0) {
arquivosSelecionados = arquivosSelecionadosAgora;
botaoEnviarTudo.setEnabled(true);
botaoEnviarTudo.setText(getLabelBotaoEnviar(nomesArquivos.size() + arquivosSelecionados.length));
}
arquivosSelecionadosAgora = null;
}
});
botaoEnviarTudo = new JButton(getLabelBotaoEnviar(0));
botaoEnviarTudo.setMnemonic('O');
botaoEnviarTudo.setEnabled(false);
botaoEnviarTudo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enviarTudo();
}
});
configurarAlinhamento();
if(scannersDisponiveis == true){
getContentPane().add(scanners, getAlinhamento());
getContentPane().add(modoColorido, getAlinhamento());
getContentPane().add(botaoDigitalizar, getAlinhamento());
}
getContentPane().add(botaoSelecionarArquivos, getAlinhamento());
getContentPane().add(botaoEnviarTudo, getAlinhamento());
}
catch(Exception e){
e.printStackTrace();
}
}
| public void init() {
try {
configurarLayout();
inicializar();
if(getParameter("id_documento") == null || getParameter("id_usuario") == null || getParameter("url_upload_pagina") == null){
throw new RuntimeException("Todos os parâmetros devem ser preenchidos.");
}
scannersDisponiveis = false;
if(isScannerValido()){
scanner.addListener(this);
modoColorido = new JCheckBox("Cor?", true);
botaoDigitalizar = new JButton("Digitalizar");
botaoDigitalizar.setMnemonic('D');
botaoDigitalizar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
digitalizar();
}
});
List<String> opcoes = new ArrayList<String>();
String [] listaScanners = scanner.getDeviceNames();
for(String nomeScanner : listaScanners){
boolean podeListar = true;
for(String prefixoInterface : PREFIXOS_INTERFACES){
if(nomeScanner.toLowerCase().contains(prefixoInterface.toLowerCase())){
podeListar = false;
break;
}
}
if(podeListar || listaScanners.length < 2){
opcoes.add(nomeScanner);
}
}
if(opcoes.size() < 1 && listaScanners.length > 0){
for(String nomeScanner : listaScanners){
opcoes.add(nomeScanner);
}
}
scanners = new JComboBox(opcoes.toArray());
if(opcoes.size() > 0){
scanners.setSelectedIndex(0);
}
scannersDisponiveis = true;
}
chooserSelecionarVariosArquivos = new JFileChooser("Selecione os arquivos para serem enviados");
chooserSelecionarVariosArquivos.setMultiSelectionEnabled(true);
chooserSelecionarVariosArquivos.addChoosableFileFilter(EXTENCOES_SUPORTADAS);
botaoSelecionarArquivos = new JButton("Selecionar...");
botaoSelecionarArquivos.setMnemonic('S');
botaoSelecionarArquivos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean chooserFechado = (chooserSelecionarVariosArquivos.showOpenDialog(getContentPane()) == JFileChooser.APPROVE_OPTION);
File[] arquivosSelecionadosAgora = chooserSelecionarVariosArquivos.getSelectedFiles();
int tamanhoArquivosSelecionadosAgora = arquivosSelecionadosAgora.length;
if (chooserFechado == true && arquivosSelecionadosAgora != null && tamanhoArquivosSelecionadosAgora > 0) {
arquivosSelecionados = arquivosSelecionadosAgora;
botaoEnviarTudo.setEnabled(true);
botaoEnviarTudo.setText(getLabelBotaoEnviar(nomesArquivos.size() + arquivosSelecionados.length));
}
arquivosSelecionadosAgora = null;
}
});
botaoEnviarTudo = new JButton(getLabelBotaoEnviar(0));
botaoEnviarTudo.setMnemonic('O');
botaoEnviarTudo.setEnabled(false);
botaoEnviarTudo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enviarTudo();
}
});
configurarAlinhamento();
if(scannersDisponiveis == true){
getContentPane().add(scanners, getAlinhamento());
getContentPane().add(modoColorido, getAlinhamento());
getContentPane().add(botaoDigitalizar, getAlinhamento());
}
getContentPane().add(botaoSelecionarArquivos, getAlinhamento());
getContentPane().add(botaoEnviarTudo, getAlinhamento());
}
catch(Exception e){
e.printStackTrace();
}
}
|
diff --git a/src/test/org/apache/nutch/fetcher/TestFetcher.java b/src/test/org/apache/nutch/fetcher/TestFetcher.java
index 0e0d57b2..3ea8c33f 100644
--- a/src/test/org/apache/nutch/fetcher/TestFetcher.java
+++ b/src/test/org/apache/nutch/fetcher/TestFetcher.java
@@ -1,133 +1,134 @@
/*
* Copyright 2006 The Apache Software Foundation
*
* 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.nutch.fetcher;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.UTF8;
import org.apache.nutch.crawl.CrawlDBTestUtil;
import org.apache.nutch.crawl.Generator;
import org.apache.nutch.crawl.Injector;
import org.apache.nutch.protocol.Content;
import org.mortbay.jetty.Server;
import junit.framework.TestCase;
/**
* Basic fetcher test
* 1. generate seedlist
* 2. inject
* 3. generate
* 3. fetch
* 4. Verify contents
* @author nutch-dev <nutch-dev at lucene.apache.org>
*
*/
public class TestFetcher extends TestCase {
final static Path testdir=new Path("build/test/fetch-test");
Configuration conf;
FileSystem fs;
Path crawldbPath;
Path segmentsPath;
Path urlPath;
Server server;
protected void setUp() throws Exception{
conf=CrawlDBTestUtil.createConfiguration();
fs=FileSystem.get(conf);
fs.delete(testdir);
urlPath=new Path(testdir,"urls");
crawldbPath=new Path(testdir,"crawldb");
segmentsPath=new Path(testdir,"segments");
server=CrawlDBTestUtil.getServer(conf.getInt("content.server.port",50000), "build/test/data/fetch-test-site");
server.start();
}
protected void tearDown() throws InterruptedException, IOException{
server.stop();
fs.delete(testdir);
}
public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
Fetcher fetcher=new Fetcher(conf);
fetcher.fetch(generatedSegment, 1, true);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
- assertTrue(1000*time > (urls.size() + 1 * conf.getInt("fetcher.server.delay",5)));
+ int minimumTime=(int) ((urls.size()+1)*1000*conf.getFloat("fetcher.server.delay",5));
+ assertTrue(time > minimumTime);
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
handledurls.add(key.toString());
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
private void addUrl(ArrayList<String> urls, String page) {
urls.add("http://127.0.0.1:" + server.getListeners()[0].getPort() + "/" + page);
}
}
| true | true | public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
Fetcher fetcher=new Fetcher(conf);
fetcher.fetch(generatedSegment, 1, true);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
assertTrue(1000*time > (urls.size() + 1 * conf.getInt("fetcher.server.delay",5)));
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
handledurls.add(key.toString());
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
| public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
Fetcher fetcher=new Fetcher(conf);
fetcher.fetch(generatedSegment, 1, true);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
int minimumTime=(int) ((urls.size()+1)*1000*conf.getFloat("fetcher.server.delay",5));
assertTrue(time > minimumTime);
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
handledurls.add(key.toString());
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
|
diff --git a/gdp-utility-wps/src/main/java/gov/usgs/cida/gdp/wps/algorithm/filemanagement/ReceiveFiles.java b/gdp-utility-wps/src/main/java/gov/usgs/cida/gdp/wps/algorithm/filemanagement/ReceiveFiles.java
index 9abffbcd..39a63ad8 100644
--- a/gdp-utility-wps/src/main/java/gov/usgs/cida/gdp/wps/algorithm/filemanagement/ReceiveFiles.java
+++ b/gdp-utility-wps/src/main/java/gov/usgs/cida/gdp/wps/algorithm/filemanagement/ReceiveFiles.java
@@ -1,230 +1,230 @@
package gov.usgs.cida.gdp.wps.algorithm.filemanagement;
import gov.usgs.cida.gdp.constants.AppConstant;
import gov.usgs.cida.gdp.dataaccess.helper.ShapeFileEPSGHelper;
import gov.usgs.cida.gdp.dataaccess.ManageGeoserverWorkspace;
import gov.usgs.cida.gdp.utilities.FileHelper;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.n52.wps.io.data.GenericFileData;
import org.n52.wps.io.data.IData;
import org.n52.wps.io.data.binding.complex.GenericFileDataBinding;
import org.n52.wps.io.data.binding.literal.LiteralStringBinding;
import org.n52.wps.server.AbstractSelfDescribingAlgorithm;
import org.opengis.referencing.FactoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This algorithm allows a client to upload a file to the server via WPS.
* More info: http://privusgs2.er.usgs.gov/display/GDP/Adding+a+Shapefile+as+a+GeoServer+WFS+EndPoint
*
* @author isuftin
*/
public class ReceiveFiles extends AbstractSelfDescribingAlgorithm {
Logger log = LoggerFactory.getLogger(ReceiveFiles.class);
private List<String> errors = new ArrayList<String>();
@Override
public Map<String, IData> run(Map<String, List<IData>> inputData) {
if (inputData == null) throw new RuntimeException("Error while allocating input parameters.");
if (!inputData.containsKey("file")) throw new RuntimeException("Error: Missing input parameter 'file'");
if (!inputData.containsKey("wfs-url")) throw new RuntimeException("Error: Missing input parameter 'wfs-url'");
if (!inputData.containsKey("filename")) throw new RuntimeException("Error: Missing input parameter 'filename'");
// "gdp.shapefile.temp.path" should be set in the tomcat startup script or setenv.sh as JAVA_OPTS="-Dgdp.shapefile.temp.path=/wherever/you/want/this/file/placed"
String fileDump = AppConstant.SHAPEFILE_LOCATION.getValue() + File.separator + UUID.randomUUID();
// Ensure that the temp directory exists
File temp = new File(fileDump);
temp.mkdirs();
List<IData> dataList = inputData.get("filename");
String desiredFilename = ((LiteralStringBinding) dataList.get(0)).getPayload();
List<IData> wfsEndpointList = inputData.get("wfs-url");
String wfsEndpoint = ((LiteralStringBinding) wfsEndpointList.get(0)).getPayload();
dataList = inputData.get("file");
IData data = dataList.get(0);
// Process each input one at a time
GenericFileData file = ((GenericFileDataBinding) data).getPayload();
if (file == null) {
errors.add("Error while processing file: Could not get file from server");
throw new RuntimeException("Error while processing file: Could not get file from server");
}
String shapefilePath = file.writeData(temp);
if (shapefilePath == null) { // Not sure if that is the only reason newFilename would be null
- errors.add("Error while processing file: Does the zip file contain the .shp file?");
- throw new RuntimeException("Error while processing file: Does the zip file contain the .shp file?");
+ errors.add("Error while processing file: Malformed zip file or incomplete shapefile");
+ throw new RuntimeException("Error while processing file: Malformed zip file or incomplete shapefile");
}
File shapefileFile = new File(shapefilePath);
File shapefileDir = shapefileFile.getParentFile();
String shapefileName = shapefileFile.getName();
String shapefileNamePrefix = shapefileName.substring(0, shapefileName.lastIndexOf("."));
// Find all files with filename with any extension
String pattern = shapefileNamePrefix + "\\..*";
FileFilter filter = new RegexFileFilter(pattern);
String[] filenames = shapefileDir.list((FilenameFilter) filter);
List<String> filenamesList = Arrays.asList(filenames);
// Make sure required files are present
String[] requiredFiles = { ".shp", ".shx", ".prj", ".dbf" };
for (String s : requiredFiles) {
if (!filenamesList.contains(shapefileNamePrefix + s)) {
throw new RuntimeException("Zip file missing " + s + " file.");
}
}
// Rename the files to the desired filenames
File[] files = shapefileDir.listFiles(filter);
for (File f : files) {
String name = f.getName();
String extension = name.substring(name.lastIndexOf("."));
f.renameTo(new File(shapefileDir.getPath() + File.separator + desiredFilename + extension));
}
String renamedShpPath = shapefileDir.getPath() + File.separator + desiredFilename + ".shp";
String renamedPrjPath = shapefileDir.getPath() + File.separator + desiredFilename + ".prj";
// Do EPSG processing
String declaredCRS = null;
String nativeCRS = null;
try {
nativeCRS = new String(FileHelper.getByteArrayFromFile(new File(renamedPrjPath)));
if (nativeCRS == null || nativeCRS.isEmpty()) {
throw new RuntimeException("Error while getting Prj/WKT information from PRJ file. Function halted.");
}
// The behavior of this method requires that the layer always force
// projection from native to declared...
declaredCRS = ShapeFileEPSGHelper.getDeclaredEPSGFromWKT(nativeCRS);
if (declaredCRS == null || declaredCRS.isEmpty()) {
throw new RuntimeException("Could not attain EPSG code from shapefile. Please ensure proper projection and a valid PRJ file.");
}
} catch (IOException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while getting EPSG information from PRJ file. Function halted.");
} catch (FactoryException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while getting EPSG information from PRJ file. Function halted.");
}
String workspace = "upload";
try {
ManageGeoserverWorkspace mws = new ManageGeoserverWorkspace(wfsEndpoint);
mws.createDataStore(renamedShpPath, desiredFilename, workspace, nativeCRS, declaredCRS);
} catch (IOException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while communicating with WFS server. Please try again or contact system administrator.");
}
Map<String, IData> result = new HashMap<String, IData>();
// GeoServer has accepted the shapefile. Send the success response to the client.
result.put("result", new LiteralStringBinding("OK: " + desiredFilename + " successfully uploaded to workspace '" + workspace + "'"));
result.put("wfs-url", new LiteralStringBinding(wfsEndpoint + "?Service=WFS&Version=1.0.0&"));
result.put("featuretype", new LiteralStringBinding(workspace + ":" + desiredFilename));
return result;
}
@Override
public BigInteger getMaxOccurs(String identifier) {
if ("wfs-url".equals(identifier)) {
return BigInteger.valueOf(1);
}
if ("filename".equals(identifier)) {
return BigInteger.valueOf(1);
}
if ("file".equals(identifier)) {
return BigInteger.valueOf(1);
}
return super.getMaxOccurs(identifier);
}
@Override
public BigInteger getMinOccurs(String identifier) {
if ("wfs-url".equals(identifier)) {
return BigInteger.valueOf(1);
}
if ("filename".equals(identifier)) {
return BigInteger.valueOf(1);
}
if ("file".equals(identifier)) {
return BigInteger.valueOf(1);
}
return super.getMinOccurs(identifier);
}
@Override
public List<String> getInputIdentifiers() {
List<String> result = new ArrayList<String>();
result.add("wfs-url");
result.add("filename");
result.add("file");
return result;
}
@Override
public List<String> getOutputIdentifiers() {
List<String> result = new ArrayList<String>();
result.add("result");
result.add("wfs-url");
result.add("featuretype");
return result;
}
@Override
public Class getInputDataType(String id) {
if ("wfs-url".equals(id)) {
return LiteralStringBinding.class;
}
if ("filename".equals(id)) {
return LiteralStringBinding.class;
}
if ("file".equals(id)) {
return GenericFileDataBinding.class;
}
return null;
}
@Override
public Class getOutputDataType(String id) {
if (id.equals("result")) {
return LiteralStringBinding.class;
}
if (id.equals("wfs-url")) {
return LiteralStringBinding.class;
}
if (id.equals("featuretype")) {
return LiteralStringBinding.class;
}
return null;
}
@Override
public List<String> getErrors() {
return errors;
}
}
| true | true | public Map<String, IData> run(Map<String, List<IData>> inputData) {
if (inputData == null) throw new RuntimeException("Error while allocating input parameters.");
if (!inputData.containsKey("file")) throw new RuntimeException("Error: Missing input parameter 'file'");
if (!inputData.containsKey("wfs-url")) throw new RuntimeException("Error: Missing input parameter 'wfs-url'");
if (!inputData.containsKey("filename")) throw new RuntimeException("Error: Missing input parameter 'filename'");
// "gdp.shapefile.temp.path" should be set in the tomcat startup script or setenv.sh as JAVA_OPTS="-Dgdp.shapefile.temp.path=/wherever/you/want/this/file/placed"
String fileDump = AppConstant.SHAPEFILE_LOCATION.getValue() + File.separator + UUID.randomUUID();
// Ensure that the temp directory exists
File temp = new File(fileDump);
temp.mkdirs();
List<IData> dataList = inputData.get("filename");
String desiredFilename = ((LiteralStringBinding) dataList.get(0)).getPayload();
List<IData> wfsEndpointList = inputData.get("wfs-url");
String wfsEndpoint = ((LiteralStringBinding) wfsEndpointList.get(0)).getPayload();
dataList = inputData.get("file");
IData data = dataList.get(0);
// Process each input one at a time
GenericFileData file = ((GenericFileDataBinding) data).getPayload();
if (file == null) {
errors.add("Error while processing file: Could not get file from server");
throw new RuntimeException("Error while processing file: Could not get file from server");
}
String shapefilePath = file.writeData(temp);
if (shapefilePath == null) { // Not sure if that is the only reason newFilename would be null
errors.add("Error while processing file: Does the zip file contain the .shp file?");
throw new RuntimeException("Error while processing file: Does the zip file contain the .shp file?");
}
File shapefileFile = new File(shapefilePath);
File shapefileDir = shapefileFile.getParentFile();
String shapefileName = shapefileFile.getName();
String shapefileNamePrefix = shapefileName.substring(0, shapefileName.lastIndexOf("."));
// Find all files with filename with any extension
String pattern = shapefileNamePrefix + "\\..*";
FileFilter filter = new RegexFileFilter(pattern);
String[] filenames = shapefileDir.list((FilenameFilter) filter);
List<String> filenamesList = Arrays.asList(filenames);
// Make sure required files are present
String[] requiredFiles = { ".shp", ".shx", ".prj", ".dbf" };
for (String s : requiredFiles) {
if (!filenamesList.contains(shapefileNamePrefix + s)) {
throw new RuntimeException("Zip file missing " + s + " file.");
}
}
// Rename the files to the desired filenames
File[] files = shapefileDir.listFiles(filter);
for (File f : files) {
String name = f.getName();
String extension = name.substring(name.lastIndexOf("."));
f.renameTo(new File(shapefileDir.getPath() + File.separator + desiredFilename + extension));
}
String renamedShpPath = shapefileDir.getPath() + File.separator + desiredFilename + ".shp";
String renamedPrjPath = shapefileDir.getPath() + File.separator + desiredFilename + ".prj";
// Do EPSG processing
String declaredCRS = null;
String nativeCRS = null;
try {
nativeCRS = new String(FileHelper.getByteArrayFromFile(new File(renamedPrjPath)));
if (nativeCRS == null || nativeCRS.isEmpty()) {
throw new RuntimeException("Error while getting Prj/WKT information from PRJ file. Function halted.");
}
// The behavior of this method requires that the layer always force
// projection from native to declared...
declaredCRS = ShapeFileEPSGHelper.getDeclaredEPSGFromWKT(nativeCRS);
if (declaredCRS == null || declaredCRS.isEmpty()) {
throw new RuntimeException("Could not attain EPSG code from shapefile. Please ensure proper projection and a valid PRJ file.");
}
} catch (IOException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while getting EPSG information from PRJ file. Function halted.");
} catch (FactoryException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while getting EPSG information from PRJ file. Function halted.");
}
String workspace = "upload";
try {
ManageGeoserverWorkspace mws = new ManageGeoserverWorkspace(wfsEndpoint);
mws.createDataStore(renamedShpPath, desiredFilename, workspace, nativeCRS, declaredCRS);
} catch (IOException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while communicating with WFS server. Please try again or contact system administrator.");
}
Map<String, IData> result = new HashMap<String, IData>();
// GeoServer has accepted the shapefile. Send the success response to the client.
result.put("result", new LiteralStringBinding("OK: " + desiredFilename + " successfully uploaded to workspace '" + workspace + "'"));
result.put("wfs-url", new LiteralStringBinding(wfsEndpoint + "?Service=WFS&Version=1.0.0&"));
result.put("featuretype", new LiteralStringBinding(workspace + ":" + desiredFilename));
return result;
}
| public Map<String, IData> run(Map<String, List<IData>> inputData) {
if (inputData == null) throw new RuntimeException("Error while allocating input parameters.");
if (!inputData.containsKey("file")) throw new RuntimeException("Error: Missing input parameter 'file'");
if (!inputData.containsKey("wfs-url")) throw new RuntimeException("Error: Missing input parameter 'wfs-url'");
if (!inputData.containsKey("filename")) throw new RuntimeException("Error: Missing input parameter 'filename'");
// "gdp.shapefile.temp.path" should be set in the tomcat startup script or setenv.sh as JAVA_OPTS="-Dgdp.shapefile.temp.path=/wherever/you/want/this/file/placed"
String fileDump = AppConstant.SHAPEFILE_LOCATION.getValue() + File.separator + UUID.randomUUID();
// Ensure that the temp directory exists
File temp = new File(fileDump);
temp.mkdirs();
List<IData> dataList = inputData.get("filename");
String desiredFilename = ((LiteralStringBinding) dataList.get(0)).getPayload();
List<IData> wfsEndpointList = inputData.get("wfs-url");
String wfsEndpoint = ((LiteralStringBinding) wfsEndpointList.get(0)).getPayload();
dataList = inputData.get("file");
IData data = dataList.get(0);
// Process each input one at a time
GenericFileData file = ((GenericFileDataBinding) data).getPayload();
if (file == null) {
errors.add("Error while processing file: Could not get file from server");
throw new RuntimeException("Error while processing file: Could not get file from server");
}
String shapefilePath = file.writeData(temp);
if (shapefilePath == null) { // Not sure if that is the only reason newFilename would be null
errors.add("Error while processing file: Malformed zip file or incomplete shapefile");
throw new RuntimeException("Error while processing file: Malformed zip file or incomplete shapefile");
}
File shapefileFile = new File(shapefilePath);
File shapefileDir = shapefileFile.getParentFile();
String shapefileName = shapefileFile.getName();
String shapefileNamePrefix = shapefileName.substring(0, shapefileName.lastIndexOf("."));
// Find all files with filename with any extension
String pattern = shapefileNamePrefix + "\\..*";
FileFilter filter = new RegexFileFilter(pattern);
String[] filenames = shapefileDir.list((FilenameFilter) filter);
List<String> filenamesList = Arrays.asList(filenames);
// Make sure required files are present
String[] requiredFiles = { ".shp", ".shx", ".prj", ".dbf" };
for (String s : requiredFiles) {
if (!filenamesList.contains(shapefileNamePrefix + s)) {
throw new RuntimeException("Zip file missing " + s + " file.");
}
}
// Rename the files to the desired filenames
File[] files = shapefileDir.listFiles(filter);
for (File f : files) {
String name = f.getName();
String extension = name.substring(name.lastIndexOf("."));
f.renameTo(new File(shapefileDir.getPath() + File.separator + desiredFilename + extension));
}
String renamedShpPath = shapefileDir.getPath() + File.separator + desiredFilename + ".shp";
String renamedPrjPath = shapefileDir.getPath() + File.separator + desiredFilename + ".prj";
// Do EPSG processing
String declaredCRS = null;
String nativeCRS = null;
try {
nativeCRS = new String(FileHelper.getByteArrayFromFile(new File(renamedPrjPath)));
if (nativeCRS == null || nativeCRS.isEmpty()) {
throw new RuntimeException("Error while getting Prj/WKT information from PRJ file. Function halted.");
}
// The behavior of this method requires that the layer always force
// projection from native to declared...
declaredCRS = ShapeFileEPSGHelper.getDeclaredEPSGFromWKT(nativeCRS);
if (declaredCRS == null || declaredCRS.isEmpty()) {
throw new RuntimeException("Could not attain EPSG code from shapefile. Please ensure proper projection and a valid PRJ file.");
}
} catch (IOException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while getting EPSG information from PRJ file. Function halted.");
} catch (FactoryException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while getting EPSG information from PRJ file. Function halted.");
}
String workspace = "upload";
try {
ManageGeoserverWorkspace mws = new ManageGeoserverWorkspace(wfsEndpoint);
mws.createDataStore(renamedShpPath, desiredFilename, workspace, nativeCRS, declaredCRS);
} catch (IOException ex) {
errors.add(ex.getMessage());
throw new RuntimeException("Error while communicating with WFS server. Please try again or contact system administrator.");
}
Map<String, IData> result = new HashMap<String, IData>();
// GeoServer has accepted the shapefile. Send the success response to the client.
result.put("result", new LiteralStringBinding("OK: " + desiredFilename + " successfully uploaded to workspace '" + workspace + "'"));
result.put("wfs-url", new LiteralStringBinding(wfsEndpoint + "?Service=WFS&Version=1.0.0&"));
result.put("featuretype", new LiteralStringBinding(workspace + ":" + desiredFilename));
return result;
}
|
diff --git a/src/org/ffmpeg/android/MediaUtils.java b/src/org/ffmpeg/android/MediaUtils.java
index 95cbccd..a9756e5 100644
--- a/src/org/ffmpeg/android/MediaUtils.java
+++ b/src/org/ffmpeg/android/MediaUtils.java
@@ -1,28 +1,28 @@
package org.ffmpeg.android;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.util.Log;
public class MediaUtils {
public static Bitmap getVideoFrame(String videoPath,long frameTime) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(videoPath);
return retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST);
} catch (IllegalArgumentException ex) {
- Log.e("MediaUtils", "error getting video frame", ex);
+ Log.w("FFMPEG.MediaUtils", "illegal argument exception");
} catch (RuntimeException ex) {
- Log.e("MediaUtils", "error getting video frame", ex);
+ Log.w("FFMPEG.MediaUtils", "error getting video frame");
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
}
}
return null;
}
}
| false | true | public static Bitmap getVideoFrame(String videoPath,long frameTime) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(videoPath);
return retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST);
} catch (IllegalArgumentException ex) {
Log.e("MediaUtils", "error getting video frame", ex);
} catch (RuntimeException ex) {
Log.e("MediaUtils", "error getting video frame", ex);
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
}
}
return null;
}
| public static Bitmap getVideoFrame(String videoPath,long frameTime) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(videoPath);
return retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST);
} catch (IllegalArgumentException ex) {
Log.w("FFMPEG.MediaUtils", "illegal argument exception");
} catch (RuntimeException ex) {
Log.w("FFMPEG.MediaUtils", "error getting video frame");
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
}
}
return null;
}
|
diff --git a/src/uk/me/parabola/imgfmt/app/labelenc/BaseEncoder.java b/src/uk/me/parabola/imgfmt/app/labelenc/BaseEncoder.java
index d495aed1..6f43e1b9 100644
--- a/src/uk/me/parabola/imgfmt/app/labelenc/BaseEncoder.java
+++ b/src/uk/me/parabola/imgfmt/app/labelenc/BaseEncoder.java
@@ -1,176 +1,176 @@
/*
* Copyright (C) 2007 Steve Ratcliffe
*
* 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.
*
* 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.
*
*
* Author: Steve Ratcliffe
* Create date: 14-Jan-2007
*/
package uk.me.parabola.imgfmt.app.labelenc;
import uk.me.parabola.log.Logger;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Locale;
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Useful routines for the other encoders.
* Provides some default behaviour when a conversion is not possible for
* example.
*
* @author Steve Ratcliffe
*/
public class BaseEncoder {
private static final Logger log = Logger.getLogger(BaseEncoder.class);
protected static final EncodedText NO_TEXT = new EncodedText(null, 0);
private boolean charsetSupported = true;
// Whether to uppercase the labels or not. Default is true because many
// GPS devices do not display labels in lower case.
private boolean upperCase;
private String charset = "ascii";
private static final String[][] rows = new String[256][];
protected boolean isCharsetSupported() {
return charsetSupported;
}
protected void prepareForCharacterSet(String name) {
if (Charset.isSupported(name)) {
charsetSupported = true;
} else {
charsetSupported = false;
log.warn("requested character set not found " + name);
}
}
protected EncodedText simpleEncode(String text) {
if (text == null)
return NO_TEXT;
char[] in = text.toCharArray();
byte[] out = new byte[in.length + 1];
int off = 0;
for (char c : in)
out[off++] = (byte) (c & 0xff);
return new EncodedText(out, out.length);
}
protected boolean isUpperCase() {
return upperCase;
}
public void setUpperCase(boolean upperCase) {
this.upperCase = upperCase;
}
/**
* Convert a string into a string that uses only ascii characters.
*
* @param s The original string. It can use any unicode character.
* @return A string that uses only ascii characters that is a transcription
* or transliteration of the original string.
*/
protected char[] transliterate(String s) {
StringBuilder sb = new StringBuilder(s.length() + 5);
for (char c : s.toCharArray()) {
if (c < 0x80) {
sb.append(c);
} else {
int row = c >>> 8;
String[] rowmap = rows[row];
if (rowmap == null)
rowmap = loadRow(row);
//log.debug("char", Integer.toHexString(c), rowmap[c & 0xff]);
sb.append(rowmap[c & 0xff]);
}
}
return sb.toString().toCharArray();
}
/**
* Load one row of characters. This means unicode characters that are
* of the form U+RRXX where RR is the row.
* @param row Row number 0-255.
* @return An array of strings, one for each character in the row. If there
* is no ascii representation then a '?' character will fill that
* position.
*/
private String[] loadRow(int row) {
if (rows[row] != null)
return rows[row];
String[] newRow = new String[256];
rows[row] = newRow;
// Default all to a question mark
Arrays.fill(newRow, "?");
charset = "ascii";
StringBuilder name = new StringBuilder();
Formatter fmt = new Formatter(name);
- fmt.format("/chars/%s/row/%02d.trans", charset, row);
+ fmt.format("/chars/%s/row%02d.trans", charset, row);
log.debug("getting file name", name);
InputStream is = getClass().getResourceAsStream(name.toString());
try {
readCharFile(is, newRow);
} catch (IOException e) {
log.error("Could not read character translation table");
}
return newRow;
}
/**
* Read in a character translit file. Not all code points need to
* be defined inside the file. Anything that is left out will become
* a question mark.
*
* @param is The open file to be read.
* @param newRow The row that we fill in with strings.
*/
private void readCharFile(InputStream is, String[] newRow) throws IOException {
if (is == null)
return;
BufferedReader br = new BufferedReader(new InputStreamReader(is, "ascii"));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() == 0 || line.charAt(0) == '#')
continue;
String[] fields = line.split("\\s+");
String upoint = fields[0];
String translation = fields[1];
if (upoint.length() != 6 || upoint.charAt(0) != 'U') continue;
// The first field must look like 'U+RRXX', we extract the XX part
int index = Integer.parseInt(upoint.substring(4), 16);
newRow[index] = translation.toUpperCase(Locale.ENGLISH);
}
}
}
| true | true | private String[] loadRow(int row) {
if (rows[row] != null)
return rows[row];
String[] newRow = new String[256];
rows[row] = newRow;
// Default all to a question mark
Arrays.fill(newRow, "?");
charset = "ascii";
StringBuilder name = new StringBuilder();
Formatter fmt = new Formatter(name);
fmt.format("/chars/%s/row/%02d.trans", charset, row);
log.debug("getting file name", name);
InputStream is = getClass().getResourceAsStream(name.toString());
try {
readCharFile(is, newRow);
} catch (IOException e) {
log.error("Could not read character translation table");
}
return newRow;
}
| private String[] loadRow(int row) {
if (rows[row] != null)
return rows[row];
String[] newRow = new String[256];
rows[row] = newRow;
// Default all to a question mark
Arrays.fill(newRow, "?");
charset = "ascii";
StringBuilder name = new StringBuilder();
Formatter fmt = new Formatter(name);
fmt.format("/chars/%s/row%02d.trans", charset, row);
log.debug("getting file name", name);
InputStream is = getClass().getResourceAsStream(name.toString());
try {
readCharFile(is, newRow);
} catch (IOException e) {
log.error("Could not read character translation table");
}
return newRow;
}
|
diff --git a/src/se/kth/maandree/jcbnfp/Parser.java b/src/se/kth/maandree/jcbnfp/Parser.java
index 27423ff..59ac774 100644
--- a/src/se/kth/maandree/jcbnfp/Parser.java
+++ b/src/se/kth/maandree/jcbnfp/Parser.java
@@ -1,365 +1,365 @@
/**
* jcbnfp — A parser for JCBNF (Jacky's Compilable BNF)
*
* Copyright (C) 2012 Mattias Andrée <[email protected]>
*
* 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 3 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, see <http://www.gnu.org/licenses/>
*/
package se.kth.maandree.jcbnfp;
import se.kth.maandree.jcbnfp.elements.*;
import java.util.*;
import java.io.*;
/**
* Code parser class using parsed syntax
*
* @author Mattias Andrée, <a href="mailto:[email protected]">[email protected]</a>
*/
public class Parser
{
/**
* Constructor
*
* @param definitions Definition map
* @param main The main definition, normally the title of the JCBNF file
*/
public Parser(final HashMap<String, Definition> definitions, final String main)
{
this.definitions = definitions;
this.main = main;
}
/**
* Definition map
*/
private final HashMap<String, Definition> definitions;
/**
* The main definition
*/
private final String main;
/**
* The data in the last read stream
*/
public int[] data;
/**
* Parses a stream and builds a tree of the result
*
* @param is The data stream to parse
* @return The tree with the result, describing the data, <code>null</code> if the gammar does not match
*
* @throws IOException On I/O exception
* @throws UndefiniedDefinitionException If the JCBNF file is refering to an undefinied definition
*/
public ParseTree parse(final InputStream is) throws IOException, UndefiniedDefinitionException
{
final int BUF_SIZE = 2048;
final ArrayList<int[]> bufs = new ArrayList<int[]>();
int[] buf = new int[BUF_SIZE];
int ptr = 0;
for (int d; (d = is.read()) != -1;)
{
if (d < 0x80)
buf[ptr++] = d;
else if ((d & 0xC0) != 0x80)
{
int n = 0;
while ((d & 0x80) != 0)
{
n++;
d <<= 1;
}
d = (d & 255) >> n;
for (int i = 0; i < n; i++)
{
final int v = is.read();
if ((v & 0xC0) != 0x80)
break;
d = (d << 6) | (d & 0x3F);
}
}
if (ptr == BUF_SIZE)
{
bufs.add(buf);
ptr = 0;
buf = new int[BUF_SIZE];
}
}
final int[] text = new int[bufs.size() * BUF_SIZE + ptr];
int p = 0;
for (final int[] b : bufs)
{
System.arraycopy(b, 0, text, p, BUF_SIZE);
p += BUF_SIZE;
}
bufs.clear();
System.arraycopy(buf, 0, text, p, ptr);
final Definition root = this.definitions.get(this.main);
final ParseTree tree = new ParseTree(null, root, this.definitions);
if (tree.parse(this.data = text, 0) < 0)
return null;
return tree;
}
//TODO public compile()
/**
* Tests whether the data can pass a stored data chunk
*
* @param data The data
* @param off The offset in the data
* @param start The start of the stored data chunk, inclusive
* @param end The end of the stored data chunk, exclusive
* @return <code>-1</code> if it didn't pass, otherwise, the number of used characters
*/
static int passes(final int[] data, final int off, final int start, final int end)
{
final int n = end - start;
if (data.length - off < n)
return -1;
for (int i = 0; i < n; i++)
if (data[i + off] != data[i + start])
return -1;
return n;
}
/**
* Tests whether the data can pass a stored data chunk, with replacement
*
* @param data The data
* @param off The offset in the data
* @param start The start of the stored data chunk, inclusive
* @param end The end of the stored data chunk, exclusive
* @param replacee The replacement replacee
* @param replacer The replacement replacer
* @return <code>-1</code> if it didn't pass, otherwise, the number of used characters
*/
static int passes(final int[] data, final int off, final int start, final int end, final int[] replacee, final int[] replacer)
{
final boolean[] preset = new boolean[256];
final HashSet<Integer> set = new HashSet<Integer>();
outer:
for (int j = start; j < end; j++)
if (data[j] == replacee[0]) //yes, this not that effecive, but who cares, compiling code should take hours
{
final int n = replacee.length;
if (j + n < data.length)
break;
for (int i = 0; i < n; i++)
if (data[j + i] != replacee[i])
continue outer;
preset[j] = true;
set.add(Integer.valueOf(j));
j += replacee.length;
}
int j = start;
for (int i = off, n = data.length; j < end; i++, j++)
{
if (i >= n)
return -1;
if (preset[j & 255] && set.contains(new Integer(j)))
{
for (int k = 0, m = replacer.length; k < m; k++, i++)
if (data[i] != replacer[k])
return -1;
j += replacee.length;
}
if (data[i] != data[j])
return -1;
}
return j - start;
}
/**
* Tests whether the data can pass an atomary grammar element
*
* @param data The data
* @param off The offset in the data
* @param def The grammar element
* @return <code>-1</code> if it didn't pass, <code>-2</code> if not atomary,
* otherwise, the number of used characters
*/
static int passes(final int[] data, final int off, final GrammarElement def)
{
if (def == null)
return 0;
if (def instanceof JCBNFString)
{
final int[] grammar = ((JCBNFString)def).string;
final int n = grammar.length;
final int m = data.length;
if (off + n >= m)
return -1;
for (int i = 0; i < n; i++)
if (data[i + off] != grammar[i])
return -1;
return n;
}
if (def instanceof JCBNFWordString)
{
final int[] grammar = ((JCBNFWordString)def).string;
final int n = data.length;
final int m = grammar.length;
if (off + n >= m)
return -1;
int prev = off >= 0 ? -1 : data[off - 1];
int next = off >= n ? -1 : data[off];
if (JCBNFCheck.w.check(prev, next) == false)
return -1;
for (int i = 0; i < n; i++)
if (data[i + off] != grammar[i])
return -1;
prev = off + m >= 0 ? -1 : data[off + m - 1];
next = off + m >= n ? -1 : data[off + m];
if (JCBNFCheck.w.check(prev, next) == false)
return -1;
return n;
}
if (def instanceof JCBNFPartialString)
{
final int[] grammar = ((JCBNFPartialString)def).string;
final int n = grammar.length;
final int m = data.length;
if (n == 0)
return 0;
if ((off >= m) || (data[off] != grammar[0]))
return -1;
for (int i = 1; i < n; i++)
if ((i + off >= m) || (data[i + off] != grammar[i]))
return i;
return n;
}
if (def instanceof JCBNFCharacters)
{
final JCBNFCharacters grammar = (JCBNFCharacters)def;
final int n = data.length;
if (off >= n)
return -1;
return grammar.contains(data[off]) ? 1 : -1;
}
if (def instanceof JCBNFCheck)
{
final JCBNFCheck grammar = (JCBNFCheck)def;
final int n = data.length;
- final int prev = off >= 0 ? -1 : data[off - 1];
+ final int prev = off <= 0 ? -1 : data[off - 1];
final int next = off >= n ? -1 : data[off];
return grammar.check(prev, next) ? 0 : -1;
}
return -2;
}
/**
* Simplifies a grammar node so that only bounded repeat (without option),
* juxtaposition, alternation, store and backtracks (with and without replacements)
* as well as atoms are used.
*
* @param element The grammar element
* @return The grammar element simplified
*/
static GrammarElement assemble(final GrammarElement element)
{
GrammarElement elem = element;
while (elem != null)
if (elem instanceof JCBNFGroup)
elem = ((JCBNFGroup)elem).element;
else if (elem instanceof JCBNFOption)
{
final JCBNFBoundedRepeation bndrep = new JCBNFBoundedRepeation(0, 1);
bndrep.element = ((JCBNFOption)elem).element;
elem = bndrep;
}
else if (elem instanceof JCBNFRepeation)
{
final JCBNFBoundedRepeation bndrep = new JCBNFBoundedRepeation(1, -1);
bndrep.element = ((JCBNFRepeation)elem).element;
elem = bndrep;
}
else if ((elem instanceof JCBNFBoundedRepeation) && (((JCBNFBoundedRepeation)elem).option != null))
{
final JCBNFBoundedRepeation e = (JCBNFBoundedRepeation)elem;
final JCBNFJuxtaposition juxta = new JCBNFJuxtaposition();
final JCBNFBoundedRepeation opt = new JCBNFBoundedRepeation(0, -1);
opt.element = e.option;
e.option = null;
juxta.elements.add(opt);
juxta.elements.add(e.element);
e.element = juxta;
}
else if ((elem instanceof JCBNFJuxtaposition) && (((JCBNFJuxtaposition)elem).elements.size() <= 1))
if (((JCBNFJuxtaposition)elem).elements.size() == 1)
elem = ((JCBNFJuxtaposition)elem).elements.get(0);
else
break;
else if ((elem instanceof JCBNFAlternation) && (((JCBNFAlternation)elem).elements.size() <= 1))
if (((JCBNFAlternation)elem).elements.size() == 1)
elem = ((JCBNFAlternation)elem).elements.get(0);
else
break;
else
break;
return elem;
}
}
| true | true | static int passes(final int[] data, final int off, final GrammarElement def)
{
if (def == null)
return 0;
if (def instanceof JCBNFString)
{
final int[] grammar = ((JCBNFString)def).string;
final int n = grammar.length;
final int m = data.length;
if (off + n >= m)
return -1;
for (int i = 0; i < n; i++)
if (data[i + off] != grammar[i])
return -1;
return n;
}
if (def instanceof JCBNFWordString)
{
final int[] grammar = ((JCBNFWordString)def).string;
final int n = data.length;
final int m = grammar.length;
if (off + n >= m)
return -1;
int prev = off >= 0 ? -1 : data[off - 1];
int next = off >= n ? -1 : data[off];
if (JCBNFCheck.w.check(prev, next) == false)
return -1;
for (int i = 0; i < n; i++)
if (data[i + off] != grammar[i])
return -1;
prev = off + m >= 0 ? -1 : data[off + m - 1];
next = off + m >= n ? -1 : data[off + m];
if (JCBNFCheck.w.check(prev, next) == false)
return -1;
return n;
}
if (def instanceof JCBNFPartialString)
{
final int[] grammar = ((JCBNFPartialString)def).string;
final int n = grammar.length;
final int m = data.length;
if (n == 0)
return 0;
if ((off >= m) || (data[off] != grammar[0]))
return -1;
for (int i = 1; i < n; i++)
if ((i + off >= m) || (data[i + off] != grammar[i]))
return i;
return n;
}
if (def instanceof JCBNFCharacters)
{
final JCBNFCharacters grammar = (JCBNFCharacters)def;
final int n = data.length;
if (off >= n)
return -1;
return grammar.contains(data[off]) ? 1 : -1;
}
if (def instanceof JCBNFCheck)
{
final JCBNFCheck grammar = (JCBNFCheck)def;
final int n = data.length;
final int prev = off >= 0 ? -1 : data[off - 1];
final int next = off >= n ? -1 : data[off];
return grammar.check(prev, next) ? 0 : -1;
}
return -2;
}
| static int passes(final int[] data, final int off, final GrammarElement def)
{
if (def == null)
return 0;
if (def instanceof JCBNFString)
{
final int[] grammar = ((JCBNFString)def).string;
final int n = grammar.length;
final int m = data.length;
if (off + n >= m)
return -1;
for (int i = 0; i < n; i++)
if (data[i + off] != grammar[i])
return -1;
return n;
}
if (def instanceof JCBNFWordString)
{
final int[] grammar = ((JCBNFWordString)def).string;
final int n = data.length;
final int m = grammar.length;
if (off + n >= m)
return -1;
int prev = off >= 0 ? -1 : data[off - 1];
int next = off >= n ? -1 : data[off];
if (JCBNFCheck.w.check(prev, next) == false)
return -1;
for (int i = 0; i < n; i++)
if (data[i + off] != grammar[i])
return -1;
prev = off + m >= 0 ? -1 : data[off + m - 1];
next = off + m >= n ? -1 : data[off + m];
if (JCBNFCheck.w.check(prev, next) == false)
return -1;
return n;
}
if (def instanceof JCBNFPartialString)
{
final int[] grammar = ((JCBNFPartialString)def).string;
final int n = grammar.length;
final int m = data.length;
if (n == 0)
return 0;
if ((off >= m) || (data[off] != grammar[0]))
return -1;
for (int i = 1; i < n; i++)
if ((i + off >= m) || (data[i + off] != grammar[i]))
return i;
return n;
}
if (def instanceof JCBNFCharacters)
{
final JCBNFCharacters grammar = (JCBNFCharacters)def;
final int n = data.length;
if (off >= n)
return -1;
return grammar.contains(data[off]) ? 1 : -1;
}
if (def instanceof JCBNFCheck)
{
final JCBNFCheck grammar = (JCBNFCheck)def;
final int n = data.length;
final int prev = off <= 0 ? -1 : data[off - 1];
final int next = off >= n ? -1 : data[off];
return grammar.check(prev, next) ? 0 : -1;
}
return -2;
}
|
diff --git a/htroot/News.java b/htroot/News.java
index cf9292bd5..f6df12219 100644
--- a/htroot/News.java
+++ b/htroot/News.java
@@ -1,153 +1,153 @@
// News.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2005
// last major change: 29.07.2005
//
// 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 Network.java
// if the shell's current path is HTROOT
import java.io.IOException;
import java.util.Enumeration;
import de.anomic.data.wikiCode;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNewsPool;
import de.anomic.yacy.yacyNewsRecord;
import de.anomic.yacy.yacySeed;
public class News {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
boolean overview = (post == null) || (post.get("page", "0").equals("0"));
int tableID = (overview) ? -1 : Integer.parseInt(post.get("page", "0")) - 1;
// execute commands
if (post != null) {
if ((post.containsKey("deletespecific")) && (tableID >= 0)) {
if (switchboard.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE", "admin log-in");
return prop; // this button needs authentication, force log-in
}
Enumeration e = post.keys();
String check;
String id;
while (e.hasMoreElements()) {
check = (String) e.nextElement();
if ((check.startsWith("del_")) && (post.get(check, "off").equals("on"))) {
id = check.substring(4);
try {
yacyCore.newsPool.moveOff(tableID, id);
} catch (IOException ee) {ee.printStackTrace();}
}
}
}
if ((post.containsKey("deleteall")) && (tableID >= 0)) {
if (switchboard.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE", "admin log-in");
return prop; // this button needs authentication, force log-in
}
yacyNewsRecord record;
try {
if ((tableID == yacyNewsPool.PROCESSED_DB) || (tableID == yacyNewsPool.PUBLISHED_DB)) {
yacyCore.newsPool.clear(tableID);
} else {
while (yacyCore.newsPool.size(tableID) > 0) {
record = yacyCore.newsPool.get(tableID, 0);
yacyCore.newsPool.moveOff(tableID, record.id());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// generate properties for output
if (overview) {
// show overview
prop.put("table", 0);
prop.put("page", 0);
prop.put("table_insize", yacyCore.newsPool.size(yacyNewsPool.INCOMING_DB));
prop.put("table_prsize", yacyCore.newsPool.size(yacyNewsPool.PROCESSED_DB));
prop.put("table_ousize", yacyCore.newsPool.size(yacyNewsPool.OUTGOING_DB));
prop.put("table_pusize", yacyCore.newsPool.size(yacyNewsPool.PUBLISHED_DB));
} else {
// generate table
prop.put("table", 1);
prop.put("page", tableID + 1);
prop.put("table_page", tableID + 1);
if (yacyCore.seedDB == null) {
} else {
int maxCount = yacyCore.newsPool.size(tableID);
if (maxCount > 300) maxCount = 300;
yacyNewsRecord record;
yacySeed seed;
for (int i = 0; i < maxCount; i++) try {
record = yacyCore.newsPool.get(tableID, i);
if (record == null) continue;
seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
prop.put("table_list_" + i + "_id", record.id());
prop.put("table_list_" + i + "_ori", (seed == null) ? record.originator() : seed.getName());
prop.put("table_list_" + i + "_cre", yacyCore.universalDateShortString(record.created()));
prop.put("table_list_" + i + "_cat", record.category());
prop.put("table_list_" + i + "_rec", (record.received() == null) ? "-" : yacyCore.universalDateShortString(record.received()));
prop.put("table_list_" + i + "_dis", record.distributed());
- prop.put("table_list_" + i + "_att", wikiCode.replaceHTML(record.attributes().toString()) );
+ prop.put("table_list_" + i + "_att", record.attributes().toString() );
} catch (IOException e) {e.printStackTrace();}
prop.put("table_list", maxCount);
}
}
// return rewrite properties
return prop;
}
}
| true | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
boolean overview = (post == null) || (post.get("page", "0").equals("0"));
int tableID = (overview) ? -1 : Integer.parseInt(post.get("page", "0")) - 1;
// execute commands
if (post != null) {
if ((post.containsKey("deletespecific")) && (tableID >= 0)) {
if (switchboard.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE", "admin log-in");
return prop; // this button needs authentication, force log-in
}
Enumeration e = post.keys();
String check;
String id;
while (e.hasMoreElements()) {
check = (String) e.nextElement();
if ((check.startsWith("del_")) && (post.get(check, "off").equals("on"))) {
id = check.substring(4);
try {
yacyCore.newsPool.moveOff(tableID, id);
} catch (IOException ee) {ee.printStackTrace();}
}
}
}
if ((post.containsKey("deleteall")) && (tableID >= 0)) {
if (switchboard.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE", "admin log-in");
return prop; // this button needs authentication, force log-in
}
yacyNewsRecord record;
try {
if ((tableID == yacyNewsPool.PROCESSED_DB) || (tableID == yacyNewsPool.PUBLISHED_DB)) {
yacyCore.newsPool.clear(tableID);
} else {
while (yacyCore.newsPool.size(tableID) > 0) {
record = yacyCore.newsPool.get(tableID, 0);
yacyCore.newsPool.moveOff(tableID, record.id());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// generate properties for output
if (overview) {
// show overview
prop.put("table", 0);
prop.put("page", 0);
prop.put("table_insize", yacyCore.newsPool.size(yacyNewsPool.INCOMING_DB));
prop.put("table_prsize", yacyCore.newsPool.size(yacyNewsPool.PROCESSED_DB));
prop.put("table_ousize", yacyCore.newsPool.size(yacyNewsPool.OUTGOING_DB));
prop.put("table_pusize", yacyCore.newsPool.size(yacyNewsPool.PUBLISHED_DB));
} else {
// generate table
prop.put("table", 1);
prop.put("page", tableID + 1);
prop.put("table_page", tableID + 1);
if (yacyCore.seedDB == null) {
} else {
int maxCount = yacyCore.newsPool.size(tableID);
if (maxCount > 300) maxCount = 300;
yacyNewsRecord record;
yacySeed seed;
for (int i = 0; i < maxCount; i++) try {
record = yacyCore.newsPool.get(tableID, i);
if (record == null) continue;
seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
prop.put("table_list_" + i + "_id", record.id());
prop.put("table_list_" + i + "_ori", (seed == null) ? record.originator() : seed.getName());
prop.put("table_list_" + i + "_cre", yacyCore.universalDateShortString(record.created()));
prop.put("table_list_" + i + "_cat", record.category());
prop.put("table_list_" + i + "_rec", (record.received() == null) ? "-" : yacyCore.universalDateShortString(record.received()));
prop.put("table_list_" + i + "_dis", record.distributed());
prop.put("table_list_" + i + "_att", wikiCode.replaceHTML(record.attributes().toString()) );
} catch (IOException e) {e.printStackTrace();}
prop.put("table_list", maxCount);
}
}
// return rewrite properties
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
boolean overview = (post == null) || (post.get("page", "0").equals("0"));
int tableID = (overview) ? -1 : Integer.parseInt(post.get("page", "0")) - 1;
// execute commands
if (post != null) {
if ((post.containsKey("deletespecific")) && (tableID >= 0)) {
if (switchboard.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE", "admin log-in");
return prop; // this button needs authentication, force log-in
}
Enumeration e = post.keys();
String check;
String id;
while (e.hasMoreElements()) {
check = (String) e.nextElement();
if ((check.startsWith("del_")) && (post.get(check, "off").equals("on"))) {
id = check.substring(4);
try {
yacyCore.newsPool.moveOff(tableID, id);
} catch (IOException ee) {ee.printStackTrace();}
}
}
}
if ((post.containsKey("deleteall")) && (tableID >= 0)) {
if (switchboard.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE", "admin log-in");
return prop; // this button needs authentication, force log-in
}
yacyNewsRecord record;
try {
if ((tableID == yacyNewsPool.PROCESSED_DB) || (tableID == yacyNewsPool.PUBLISHED_DB)) {
yacyCore.newsPool.clear(tableID);
} else {
while (yacyCore.newsPool.size(tableID) > 0) {
record = yacyCore.newsPool.get(tableID, 0);
yacyCore.newsPool.moveOff(tableID, record.id());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// generate properties for output
if (overview) {
// show overview
prop.put("table", 0);
prop.put("page", 0);
prop.put("table_insize", yacyCore.newsPool.size(yacyNewsPool.INCOMING_DB));
prop.put("table_prsize", yacyCore.newsPool.size(yacyNewsPool.PROCESSED_DB));
prop.put("table_ousize", yacyCore.newsPool.size(yacyNewsPool.OUTGOING_DB));
prop.put("table_pusize", yacyCore.newsPool.size(yacyNewsPool.PUBLISHED_DB));
} else {
// generate table
prop.put("table", 1);
prop.put("page", tableID + 1);
prop.put("table_page", tableID + 1);
if (yacyCore.seedDB == null) {
} else {
int maxCount = yacyCore.newsPool.size(tableID);
if (maxCount > 300) maxCount = 300;
yacyNewsRecord record;
yacySeed seed;
for (int i = 0; i < maxCount; i++) try {
record = yacyCore.newsPool.get(tableID, i);
if (record == null) continue;
seed = yacyCore.seedDB.getConnected(record.originator());
if (seed == null) seed = yacyCore.seedDB.getDisconnected(record.originator());
prop.put("table_list_" + i + "_id", record.id());
prop.put("table_list_" + i + "_ori", (seed == null) ? record.originator() : seed.getName());
prop.put("table_list_" + i + "_cre", yacyCore.universalDateShortString(record.created()));
prop.put("table_list_" + i + "_cat", record.category());
prop.put("table_list_" + i + "_rec", (record.received() == null) ? "-" : yacyCore.universalDateShortString(record.received()));
prop.put("table_list_" + i + "_dis", record.distributed());
prop.put("table_list_" + i + "_att", record.attributes().toString() );
} catch (IOException e) {e.printStackTrace();}
prop.put("table_list", maxCount);
}
}
// return rewrite properties
return prop;
}
|
diff --git a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UITaskDetailTab.java b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UITaskDetailTab.java
index 55b751ca..fe277853 100644
--- a/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UITaskDetailTab.java
+++ b/calendar-webapp/src/main/java/org/exoplatform/calendar/webui/popup/UITaskDetailTab.java
@@ -1,219 +1,219 @@
/**
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* 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, see<http://www.gnu.org/licenses/>.
**/
package org.exoplatform.calendar.webui.popup;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.exoplatform.calendar.CalendarUtils;
import org.exoplatform.calendar.service.Attachment;
import org.exoplatform.calendar.service.Calendar;
import org.exoplatform.calendar.service.CalendarEvent;
import org.exoplatform.calendar.service.CalendarService;
import org.exoplatform.calendar.webui.UIFormDateTimePicker;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.core.model.SelectItemOption;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormInputInfo;
import org.exoplatform.webui.form.UIFormInputWithActions;
import org.exoplatform.webui.form.UIFormSelectBox;
import org.exoplatform.webui.form.UIFormSelectBoxWithGroups;
import org.exoplatform.webui.form.UIFormStringInput;
import org.exoplatform.webui.form.UIFormTextAreaInput;
import org.exoplatform.webui.form.ext.UIFormComboBox;
import org.exoplatform.webui.form.input.UICheckBoxInput;
import org.exoplatform.webui.form.validator.MandatoryValidator;
/**
* Created by The eXo Platform SARL
* Author : Pham Tuan
* [email protected]
* Aug 29, 2007
*/
@ComponentConfig(
template = "app:/templates/calendar/webui/UIPopup/UITaskDetailTab.gtmpl"
)
public class UITaskDetailTab extends UIFormInputWithActions {
final public static String FIELD_EVENT = "eventName".intern() ;
final public static String FIELD_CALENDAR = "calendar".intern() ;
final public static String FIELD_CATEGORY = "category".intern() ;
final public static String FIELD_FROM = "from".intern() ;
final public static String FIELD_TO = "to".intern() ;
final public static String FIELD_FROM_TIME = "fromTime".intern() ;
final public static String FIELD_TO_TIME = "toTime".intern() ;
final public static String FIELD_CHECKALL = "allDay".intern() ;
final public static String FIELD_DELEGATION = "delegation".intern() ;
final public static String FIELD_PRIORITY = "priority".intern() ;
final public static String FIELD_DESCRIPTION = "description".intern() ;
final public static String FIELD_STATUS = "status".intern() ;
final static public String FIELD_ATTACHMENTS = "attachments".intern() ;
final static public String LABEL_ADD_ATTACHMENTS = "addfiles";
protected List<Attachment> attachments_ = new ArrayList<Attachment>() ;
private Map<String, List<ActionData>> actionField_ ;
public UITaskDetailTab(String arg0) throws Exception {
super(arg0);
setComponentConfig(getClass(), null) ;
actionField_ = new HashMap<String, List<ActionData>>() ;
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
addUIFormInput(new UIFormStringInput(FIELD_EVENT, FIELD_EVENT, null).addValidator(MandatoryValidator.class)) ;
addUIFormInput(new UIFormTextAreaInput(FIELD_DESCRIPTION, FIELD_DESCRIPTION, null)) ;
addUIFormInput(new UIFormSelectBoxWithGroups(FIELD_CALENDAR, FIELD_CALENDAR, null)) ;
addUIFormInput(new UIFormSelectBox(FIELD_CATEGORY, FIELD_CATEGORY, CalendarUtils.getCategory())) ;
addUIFormInput(new UIFormSelectBox(FIELD_STATUS, FIELD_STATUS, getStatus())) ;
ActionData addCategoryAction = new ActionData() ;
addCategoryAction.setActionType(ActionData.TYPE_ICON) ;
addCategoryAction.setCssIconClass("uiIconPlus uiIconLightGray");
addCategoryAction.setActionName(UIEventForm.ACT_ADDCATEGORY) ;
addCategoryAction.setActionListener(UIEventForm.ACT_ADDCATEGORY) ;
List<ActionData> addCategoryActions = new ArrayList<ActionData>() ;
addCategoryActions.add(addCategoryAction) ;
setActionField(FIELD_CATEGORY, addCategoryActions) ;
addUIFormInput(new UIFormInputInfo(FIELD_ATTACHMENTS, FIELD_ATTACHMENTS, null)) ;
setActionField(FIELD_ATTACHMENTS, getUploadFileList()) ;
addUIFormInput(new UIFormDateTimePicker(FIELD_FROM, FIELD_FROM, new Date(), false));
addUIFormInput(new UIFormComboBox(FIELD_FROM_TIME, FIELD_FROM_TIME, options));
addUIFormInput(new UIFormComboBox(FIELD_TO_TIME, FIELD_TO_TIME, options));
addUIFormInput(new UIFormDateTimePicker(FIELD_TO, FIELD_TO, new Date(), false));
addUIFormInput(new UICheckBoxInput(FIELD_CHECKALL, FIELD_CHECKALL, null));
addUIFormInput(new UIFormStringInput(FIELD_DELEGATION, FIELD_DELEGATION, null));
addUIFormInput(new UIFormSelectBox(FIELD_PRIORITY, FIELD_PRIORITY, getPriority())) ;
ActionData addEmailAddress = new ActionData() ;
addEmailAddress.setActionType(ActionData.TYPE_ICON) ;
addEmailAddress.setCssIconClass("uiIconEmail uiIconLightGray");
addEmailAddress.setActionName(UITaskForm.ACT_ADDEMAIL) ;
addEmailAddress.setActionListener(UITaskForm.ACT_ADDEMAIL) ;
List<ActionData> addMailActions = new ArrayList<ActionData>() ;
addMailActions.add(addEmailAddress) ;
ActionData selectUser = new ActionData() ;
selectUser.setActionType(ActionData.TYPE_ICON) ;
- selectUser.setCssIconClass("uiIconUser uiIconLightGray");
+ selectUser.setCssIconClass("uiIconPlus uiIconLightGray");
selectUser.setActionName(UITaskForm.ACT_SELECTUSER) ;
selectUser.setActionListener(UITaskForm.ACT_SELECTUSER) ;
List<ActionData> selectUsers = new ArrayList<ActionData>() ;
selectUsers.add(selectUser) ;
setActionField(FIELD_DELEGATION, selectUsers) ;
}
private List<SelectItemOption<String>> getStatus() {
List<SelectItemOption<String>> status = new ArrayList<SelectItemOption<String>>() ;
for(String taskStatus : CalendarEvent.TASK_STATUS) {
status.add(new SelectItemOption<String>(taskStatus, taskStatus)) ;
}
return status ;
}
protected UIForm getParentFrom() {
return (UIForm)getParent() ;
}
public List<ActionData> getUploadFileList() throws Exception {
List<ActionData> uploadedFiles = new ArrayList<ActionData>() ;
for(Attachment attachdata : attachments_) {
ActionData fileUpload = new ActionData() ;
fileUpload.setActionListener(UIEventForm.ACT_DOWNLOAD) ;
fileUpload.setActionParameter(attachdata.getId()) ;
fileUpload.setActionType(ActionData.TYPE_LINK) ;
fileUpload.setCssIconClass("uiIconPlus uiIconLightGray") ;
fileUpload.setActionName(attachdata.getName() + "-(" + CalendarUtils.convertSize(attachdata.getSize()) + ")" ) ;
fileUpload.setShowLabel(true) ;
uploadedFiles.add(fileUpload) ;
ActionData removeAction = new ActionData() ;
removeAction.setActionListener(UIEventForm.ACT_REMOVE) ;
removeAction.setActionName(UIEventForm.ACT_REMOVE);
removeAction.setActionParameter(attachdata.getId());
removeAction.setActionType(ActionData.TYPE_ICON) ;
removeAction.setCssIconClass("uiIconDelete uiIconLightGray");
removeAction.setBreakLine(true) ;
uploadedFiles.add(removeAction) ;
}
return uploadedFiles ;
}
public void addToUploadFileList(Attachment attachfile) {
attachments_.add(attachfile) ;
}
public void removeFromUploadFileList(Attachment attachfile) {
attachments_.remove(attachfile);
}
public void refreshUploadFileList() throws Exception {
setActionField(FIELD_ATTACHMENTS, getUploadFileList()) ;
}
protected List<Attachment> getAttachments() {
return attachments_ ;
}
protected void setAttachments(List<Attachment> attachment) {
attachments_ = attachment ;
}
protected List<SelectItemOption<String>> getCalendar() throws Exception {
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
CalendarService calendarService = CalendarUtils.getCalendarService() ;
String username = CalendarUtils.getCurrentUser() ;
List<Calendar> calendars = calendarService.getUserCalendars(username, true) ;
for(Calendar c : calendars) {
options.add(new SelectItemOption<String>(c.getName(), c.getId())) ;
}
return options ;
}
private List<SelectItemOption<String>> getPriority() throws Exception {
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
options.add(new SelectItemOption<String>("none", "none")) ;
options.add(new SelectItemOption<String>("normal", "normal")) ;
options.add(new SelectItemOption<String>("high", "high")) ;
options.add(new SelectItemOption<String>("low", "low")) ;
return options ;
}
protected List<SelectItemOption<String>> getRepeater() {
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
for(String s : CalendarEvent.REPEATTYPES) {
options.add(new SelectItemOption<String>(s,s)) ;
}
return options ;
}
public void setActionField(String fieldName, List<ActionData> actions){
actionField_.put(fieldName, actions) ;
}
public List<ActionData> getActionField(String fieldName) {return actionField_.get(fieldName) ;}
public UIFormComboBox getUIFormComboBox(String id) {
return findComponentById(id);
}
public UIFormSelectBoxWithGroups getUIFormSelectBoxGroup(String id) {
return findComponentById(id);
}
}
| true | true | public UITaskDetailTab(String arg0) throws Exception {
super(arg0);
setComponentConfig(getClass(), null) ;
actionField_ = new HashMap<String, List<ActionData>>() ;
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
addUIFormInput(new UIFormStringInput(FIELD_EVENT, FIELD_EVENT, null).addValidator(MandatoryValidator.class)) ;
addUIFormInput(new UIFormTextAreaInput(FIELD_DESCRIPTION, FIELD_DESCRIPTION, null)) ;
addUIFormInput(new UIFormSelectBoxWithGroups(FIELD_CALENDAR, FIELD_CALENDAR, null)) ;
addUIFormInput(new UIFormSelectBox(FIELD_CATEGORY, FIELD_CATEGORY, CalendarUtils.getCategory())) ;
addUIFormInput(new UIFormSelectBox(FIELD_STATUS, FIELD_STATUS, getStatus())) ;
ActionData addCategoryAction = new ActionData() ;
addCategoryAction.setActionType(ActionData.TYPE_ICON) ;
addCategoryAction.setCssIconClass("uiIconPlus uiIconLightGray");
addCategoryAction.setActionName(UIEventForm.ACT_ADDCATEGORY) ;
addCategoryAction.setActionListener(UIEventForm.ACT_ADDCATEGORY) ;
List<ActionData> addCategoryActions = new ArrayList<ActionData>() ;
addCategoryActions.add(addCategoryAction) ;
setActionField(FIELD_CATEGORY, addCategoryActions) ;
addUIFormInput(new UIFormInputInfo(FIELD_ATTACHMENTS, FIELD_ATTACHMENTS, null)) ;
setActionField(FIELD_ATTACHMENTS, getUploadFileList()) ;
addUIFormInput(new UIFormDateTimePicker(FIELD_FROM, FIELD_FROM, new Date(), false));
addUIFormInput(new UIFormComboBox(FIELD_FROM_TIME, FIELD_FROM_TIME, options));
addUIFormInput(new UIFormComboBox(FIELD_TO_TIME, FIELD_TO_TIME, options));
addUIFormInput(new UIFormDateTimePicker(FIELD_TO, FIELD_TO, new Date(), false));
addUIFormInput(new UICheckBoxInput(FIELD_CHECKALL, FIELD_CHECKALL, null));
addUIFormInput(new UIFormStringInput(FIELD_DELEGATION, FIELD_DELEGATION, null));
addUIFormInput(new UIFormSelectBox(FIELD_PRIORITY, FIELD_PRIORITY, getPriority())) ;
ActionData addEmailAddress = new ActionData() ;
addEmailAddress.setActionType(ActionData.TYPE_ICON) ;
addEmailAddress.setCssIconClass("uiIconEmail uiIconLightGray");
addEmailAddress.setActionName(UITaskForm.ACT_ADDEMAIL) ;
addEmailAddress.setActionListener(UITaskForm.ACT_ADDEMAIL) ;
List<ActionData> addMailActions = new ArrayList<ActionData>() ;
addMailActions.add(addEmailAddress) ;
ActionData selectUser = new ActionData() ;
selectUser.setActionType(ActionData.TYPE_ICON) ;
selectUser.setCssIconClass("uiIconUser uiIconLightGray");
selectUser.setActionName(UITaskForm.ACT_SELECTUSER) ;
selectUser.setActionListener(UITaskForm.ACT_SELECTUSER) ;
List<ActionData> selectUsers = new ArrayList<ActionData>() ;
selectUsers.add(selectUser) ;
setActionField(FIELD_DELEGATION, selectUsers) ;
}
| public UITaskDetailTab(String arg0) throws Exception {
super(arg0);
setComponentConfig(getClass(), null) ;
actionField_ = new HashMap<String, List<ActionData>>() ;
List<SelectItemOption<String>> options = new ArrayList<SelectItemOption<String>>() ;
addUIFormInput(new UIFormStringInput(FIELD_EVENT, FIELD_EVENT, null).addValidator(MandatoryValidator.class)) ;
addUIFormInput(new UIFormTextAreaInput(FIELD_DESCRIPTION, FIELD_DESCRIPTION, null)) ;
addUIFormInput(new UIFormSelectBoxWithGroups(FIELD_CALENDAR, FIELD_CALENDAR, null)) ;
addUIFormInput(new UIFormSelectBox(FIELD_CATEGORY, FIELD_CATEGORY, CalendarUtils.getCategory())) ;
addUIFormInput(new UIFormSelectBox(FIELD_STATUS, FIELD_STATUS, getStatus())) ;
ActionData addCategoryAction = new ActionData() ;
addCategoryAction.setActionType(ActionData.TYPE_ICON) ;
addCategoryAction.setCssIconClass("uiIconPlus uiIconLightGray");
addCategoryAction.setActionName(UIEventForm.ACT_ADDCATEGORY) ;
addCategoryAction.setActionListener(UIEventForm.ACT_ADDCATEGORY) ;
List<ActionData> addCategoryActions = new ArrayList<ActionData>() ;
addCategoryActions.add(addCategoryAction) ;
setActionField(FIELD_CATEGORY, addCategoryActions) ;
addUIFormInput(new UIFormInputInfo(FIELD_ATTACHMENTS, FIELD_ATTACHMENTS, null)) ;
setActionField(FIELD_ATTACHMENTS, getUploadFileList()) ;
addUIFormInput(new UIFormDateTimePicker(FIELD_FROM, FIELD_FROM, new Date(), false));
addUIFormInput(new UIFormComboBox(FIELD_FROM_TIME, FIELD_FROM_TIME, options));
addUIFormInput(new UIFormComboBox(FIELD_TO_TIME, FIELD_TO_TIME, options));
addUIFormInput(new UIFormDateTimePicker(FIELD_TO, FIELD_TO, new Date(), false));
addUIFormInput(new UICheckBoxInput(FIELD_CHECKALL, FIELD_CHECKALL, null));
addUIFormInput(new UIFormStringInput(FIELD_DELEGATION, FIELD_DELEGATION, null));
addUIFormInput(new UIFormSelectBox(FIELD_PRIORITY, FIELD_PRIORITY, getPriority())) ;
ActionData addEmailAddress = new ActionData() ;
addEmailAddress.setActionType(ActionData.TYPE_ICON) ;
addEmailAddress.setCssIconClass("uiIconEmail uiIconLightGray");
addEmailAddress.setActionName(UITaskForm.ACT_ADDEMAIL) ;
addEmailAddress.setActionListener(UITaskForm.ACT_ADDEMAIL) ;
List<ActionData> addMailActions = new ArrayList<ActionData>() ;
addMailActions.add(addEmailAddress) ;
ActionData selectUser = new ActionData() ;
selectUser.setActionType(ActionData.TYPE_ICON) ;
selectUser.setCssIconClass("uiIconPlus uiIconLightGray");
selectUser.setActionName(UITaskForm.ACT_SELECTUSER) ;
selectUser.setActionListener(UITaskForm.ACT_SELECTUSER) ;
List<ActionData> selectUsers = new ArrayList<ActionData>() ;
selectUsers.add(selectUser) ;
setActionField(FIELD_DELEGATION, selectUsers) ;
}
|
diff --git a/src/org/litnak/coldfunctional/reduce/ArrayReduce.java b/src/org/litnak/coldfunctional/reduce/ArrayReduce.java
index f714777..d500664 100644
--- a/src/org/litnak/coldfunctional/reduce/ArrayReduce.java
+++ b/src/org/litnak/coldfunctional/reduce/ArrayReduce.java
@@ -1,36 +1,36 @@
/**
* Extends arrays by adding a reduce() member function
*
*/
package org.litnak.coldfunctional.reduce;
import railo.runtime.PageContext;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.functions.BIF;
import railo.runtime.op.Caster;
import railo.runtime.type.Array;
import railo.runtime.type.UDF;
public class ArrayReduce extends BIF{
private static final long serialVersionUID = -3536069174087530428L;
public static Object call(PageContext pc , Array arr, UDF reducer) throws PageException {
- if (arr.size() == 0) return new ExpressionException("array provided to ArrayReduce must not be empty");
+ if (arr.size() == 0) throw new ExpressionException("array provided to ArrayReduce must not be empty");
if (arr.size() == 1) return arr.getE(1);
Object lastValue = arr.getE(1);
for(int i = 2; i<= arr.size(); i++) {
Object nextValue = arr.getE(i);
lastValue = reducer.call(pc,new Object[]{lastValue,nextValue},true);
}
return lastValue;
}
@Override
public Object invoke(PageContext pc, Object[] args) throws PageException {
return call(pc,Caster.toArray(args[0]),Caster.toFunction(args[1]));
}
}
| true | true | public static Object call(PageContext pc , Array arr, UDF reducer) throws PageException {
if (arr.size() == 0) return new ExpressionException("array provided to ArrayReduce must not be empty");
if (arr.size() == 1) return arr.getE(1);
Object lastValue = arr.getE(1);
for(int i = 2; i<= arr.size(); i++) {
Object nextValue = arr.getE(i);
lastValue = reducer.call(pc,new Object[]{lastValue,nextValue},true);
}
return lastValue;
}
| public static Object call(PageContext pc , Array arr, UDF reducer) throws PageException {
if (arr.size() == 0) throw new ExpressionException("array provided to ArrayReduce must not be empty");
if (arr.size() == 1) return arr.getE(1);
Object lastValue = arr.getE(1);
for(int i = 2; i<= arr.size(); i++) {
Object nextValue = arr.getE(i);
lastValue = reducer.call(pc,new Object[]{lastValue,nextValue},true);
}
return lastValue;
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/debug/ui/launchConfigurations/JavaClasspathTab.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/debug/ui/launchConfigurations/JavaClasspathTab.java
index 8e6974d54..72f774ca3 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/debug/ui/launchConfigurations/JavaClasspathTab.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/debug/ui/launchConfigurations/JavaClasspathTab.java
@@ -1,398 +1,400 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.debug.ui.launchConfigurations;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.jdt.internal.debug.ui.IJavaDebugHelpContextIds;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.internal.debug.ui.actions.AddAdvancedAction;
import org.eclipse.jdt.internal.debug.ui.actions.AddExternalFolderAction;
import org.eclipse.jdt.internal.debug.ui.actions.AddExternalJarAction;
import org.eclipse.jdt.internal.debug.ui.actions.AddFolderAction;
import org.eclipse.jdt.internal.debug.ui.actions.AddJarAction;
import org.eclipse.jdt.internal.debug.ui.actions.AddProjectAction;
import org.eclipse.jdt.internal.debug.ui.actions.AddVariableAction;
import org.eclipse.jdt.internal.debug.ui.actions.AttachSourceAction;
import org.eclipse.jdt.internal.debug.ui.actions.MoveDownAction;
import org.eclipse.jdt.internal.debug.ui.actions.MoveUpAction;
import org.eclipse.jdt.internal.debug.ui.actions.RemoveAction;
import org.eclipse.jdt.internal.debug.ui.actions.RuntimeClasspathAction;
import org.eclipse.jdt.internal.debug.ui.launcher.JavaLaunchConfigurationTab;
import org.eclipse.jdt.internal.debug.ui.launcher.LauncherMessages;
import org.eclipse.jdt.internal.debug.ui.launcher.RuntimeClasspathViewer;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jface.action.IAction;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.help.WorkbenchHelp;
/**
* A launch configuration tab that displays and edits the user and
* bootstrap classes comprising the classpath launch configuration
* attribute.
* <p>
* This class may be instantiated. This class is not intended to be subclassed.
* </p>
* @since 2.0
*/
public class JavaClasspathTab extends JavaLaunchConfigurationTab {
protected TabFolder fPathTabFolder;
protected TabItem fBootPathTabItem;
protected TabItem fClassPathTabItem;
protected RuntimeClasspathViewer fClasspathViewer;
protected RuntimeClasspathViewer fBootpathViewer;
protected Button fClassPathDefaultButton;
protected List fActions = new ArrayList(10);
protected Image fImage = null;
protected static final String DIALOG_SETTINGS_PREFIX = "JavaClasspathTab"; //$NON-NLS-1$
/**
* The last launch config this tab was initialized from
*/
protected ILaunchConfiguration fLaunchConfiguration;
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(Composite)
*/
public void createControl(Composite parent) {
Font font = parent.getFont();
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
WorkbenchHelp.setHelp(getControl(), IJavaDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_CLASSPATH_TAB);
GridLayout topLayout = new GridLayout();
topLayout.numColumns = 2;
comp.setLayout(topLayout);
GridData gd;
createVerticalSpacer(comp, 2);
fPathTabFolder = new TabFolder(comp, SWT.NONE);
gd = new GridData(GridData.FILL_BOTH);
+ gd.heightHint = 200;
+ gd.widthHint = 250;
fPathTabFolder.setLayoutData(gd);
fPathTabFolder.setFont(font);
fPathTabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TabItem[] tabs = fPathTabFolder.getSelection();
if (tabs.length == 1) {
RuntimeClasspathViewer data = (RuntimeClasspathViewer)tabs[0].getData();
retargetActions(data);
}
}
});
fClasspathViewer = new RuntimeClasspathViewer(fPathTabFolder);
fClasspathViewer.addEntriesChangedListener(this);
fClasspathViewer.getControl().setFont(font);
fClassPathTabItem = new TabItem(fPathTabFolder, SWT.NONE, 0);
fClassPathTabItem.setText(LauncherMessages.getString("JavaClasspathTab.Us&er_classes_1")); //$NON-NLS-1$
fClassPathTabItem.setControl(fClasspathViewer.getControl());
fClassPathTabItem.setData(fClasspathViewer);
fBootpathViewer = new RuntimeClasspathViewer(fPathTabFolder);
fBootpathViewer.addEntriesChangedListener(this);
fBootpathViewer.getControl().setFont(font);
fBootPathTabItem = new TabItem(fPathTabFolder, SWT.NONE, 1);
fBootPathTabItem.setText(LauncherMessages.getString("JavaClasspathTab.&Bootstrap_classes_2")); //$NON-NLS-1$
fBootPathTabItem.setControl(fBootpathViewer.getControl());
fBootPathTabItem.setData(fBootpathViewer);
Composite pathButtonComp = new Composite(comp, SWT.NONE);
GridLayout pathButtonLayout = new GridLayout();
pathButtonLayout.marginHeight = 0;
pathButtonLayout.marginWidth = 0;
pathButtonComp.setLayout(pathButtonLayout);
gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_FILL);
pathButtonComp.setLayoutData(gd);
pathButtonComp.setFont(font);
createVerticalSpacer(comp, 2);
fClassPathDefaultButton = new Button(comp, SWT.CHECK);
fClassPathDefaultButton.setText(LauncherMessages.getString("JavaEnvironmentTab.Use_defau<_classpath_10")); //$NON-NLS-1$
gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalSpan = 2;
fClassPathDefaultButton.setLayoutData(gd);
fClassPathDefaultButton.setFont(font);
fClassPathDefaultButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleClasspathDefaultButtonSelected();
}
});
createVerticalSpacer(pathButtonComp, 1);
List advancedActions = new ArrayList(5);
RuntimeClasspathAction action = new MoveUpAction(null);
Button button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new MoveDownAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new RemoveAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddProjectAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddJarAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddExternalJarAction(null, DIALOG_SETTINGS_PREFIX);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddFolderAction(null);
advancedActions.add(action);
action = new AddExternalFolderAction(null, DIALOG_SETTINGS_PREFIX);
advancedActions.add(action);
action = new AddVariableAction(null);
advancedActions.add(action);
action = new AttachSourceAction(null);
advancedActions.add(action);
IAction[] adv = (IAction[])advancedActions.toArray(new IAction[advancedActions.size()]);
action = new AddAdvancedAction(null, adv);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
retargetActions(fClasspathViewer);
}
/**
* The default classpath button has been toggled
*/
protected void handleClasspathDefaultButtonSelected() {
setDirty(true);
boolean useDefault = fClassPathDefaultButton.getSelection();
fClassPathDefaultButton.setSelection(useDefault);
if (useDefault) {
displayDefaultClasspath();
}
fClasspathViewer.setEnabled(!useDefault);
fBootpathViewer.setEnabled(!useDefault);
updateLaunchConfigurationDialog();
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(ILaunchConfigurationWorkingCopy)
*/
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(ILaunchConfiguration)
*/
public void initializeFrom(ILaunchConfiguration configuration) {
boolean useDefault = true;
setErrorMessage(null);
try {
useDefault = configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, true);
} catch (CoreException e) {
JDIDebugUIPlugin.log(e);
}
if (configuration == getLaunchConfiguration()) {
// no need to update if an explicit path is being used and this setting
// has not changed (and viewing the same config as last time)
if (!useDefault && !fClassPathDefaultButton.getSelection()) {
setDirty(false);
return;
}
}
setLaunchConfiguration(configuration);
fClassPathDefaultButton.setSelection(useDefault);
try {
setClasspathEntries(JavaRuntime.computeUnresolvedRuntimeClasspath(configuration));
} catch (CoreException e) {
setErrorMessage(e.getMessage());
}
fClasspathViewer.setEnabled(!useDefault);
fBootpathViewer.setEnabled(!useDefault);
fClasspathViewer.setLaunchConfiguration(configuration);
fBootpathViewer.setLaunchConfiguration(configuration);
setDirty(false);
}
/**
* Displays the default classpath in the UI
*/
protected void displayDefaultClasspath() {
ILaunchConfiguration config = getLaunchConfiguration();
ILaunchConfigurationWorkingCopy wc = null;
try {
if (config.isWorkingCopy()) {
wc= (ILaunchConfigurationWorkingCopy)config;
} else {
wc = config.getWorkingCopy();
}
performApply(wc);
setClasspathEntries(JavaRuntime.computeUnresolvedRuntimeClasspath(wc));
} catch (CoreException e) {
JDIDebugUIPlugin.log(e);
}
}
/**
* Displays the given classpath entries, grouping into user and bootstrap entries
*/
protected void setClasspathEntries(IRuntimeClasspathEntry[] entries) {
List cp = new ArrayList(entries.length);
List bp = new ArrayList(entries.length);
for (int i = 0; i < entries.length; i++) {
switch (entries[i].getClasspathProperty()) {
case IRuntimeClasspathEntry.USER_CLASSES:
cp.add(entries[i]);
break;
default:
bp.add(entries[i]);
break;
}
}
fClasspathViewer.setEntries((IRuntimeClasspathEntry[])cp.toArray(new IRuntimeClasspathEntry[cp.size()]));
fBootpathViewer.setEntries((IRuntimeClasspathEntry[])bp.toArray(new IRuntimeClasspathEntry[bp.size()]));
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(ILaunchConfigurationWorkingCopy)
*/
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
if (isDirty()) {
boolean def = fClassPathDefaultButton.getSelection();
if (def) {
configuration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, (String)null);
configuration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, (String)null);
} else {
configuration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
try {
IRuntimeClasspathEntry[] boot = fBootpathViewer.getEntries();
IRuntimeClasspathEntry[] user = fClasspathViewer.getEntries();
List mementos = new ArrayList(boot.length + user.length);
for (int i = 0; i < boot.length; i++) {
boot[i].setClasspathProperty(IRuntimeClasspathEntry.BOOTSTRAP_CLASSES);
mementos.add(boot[i].getMemento());
}
for (int i = 0; i < user.length; i++) {
user[i].setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
mementos.add(user[i].getMemento());
}
configuration.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, mementos);
} catch (CoreException e) {
JDIDebugUIPlugin.errorDialog(LauncherMessages.getString("JavaClasspathTab.Unable_to_save_classpath_1"), e); //$NON-NLS-1$
}
}
}
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName()
*/
public String getName() {
return LauncherMessages.getString("JavaClasspathTab.Cla&ss_path_3"); //$NON-NLS-1$
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage()
*/
public Image getImage() {
if (fImage == null) {
fImage = JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage();
}
return fImage;
}
/**
* Sets the java project currently specified by the
* given launch config, if any.
*/
protected void setLaunchConfiguration(ILaunchConfiguration config) {
fLaunchConfiguration = config;
}
/**
* Returns the current java project context
*/
protected ILaunchConfiguration getLaunchConfiguration() {
return fLaunchConfiguration;
}
/**
* Adds the given action to the action collection in this tab
*/
protected void addAction(RuntimeClasspathAction action) {
fActions.add(action);
}
/**
* Re-targets actions to the given viewer
*/
protected void retargetActions(RuntimeClasspathViewer viewer) {
Iterator actions = fActions.iterator();
while (actions.hasNext()) {
RuntimeClasspathAction action = (RuntimeClasspathAction)actions.next();
action.setViewer(viewer);
}
}
/**
* @see org.eclipse.debug.ui.ILaunchConfigurationTab#dispose()
*/
public void dispose() {
if (fClasspathViewer != null) {
fClasspathViewer.removeEntriesChangedListener(this);
fBootpathViewer.removeEntriesChangedListener(this);
}
if (fImage != null) {
fImage.dispose();
}
super.dispose();
}
}
| true | true | public void createControl(Composite parent) {
Font font = parent.getFont();
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
WorkbenchHelp.setHelp(getControl(), IJavaDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_CLASSPATH_TAB);
GridLayout topLayout = new GridLayout();
topLayout.numColumns = 2;
comp.setLayout(topLayout);
GridData gd;
createVerticalSpacer(comp, 2);
fPathTabFolder = new TabFolder(comp, SWT.NONE);
gd = new GridData(GridData.FILL_BOTH);
fPathTabFolder.setLayoutData(gd);
fPathTabFolder.setFont(font);
fPathTabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TabItem[] tabs = fPathTabFolder.getSelection();
if (tabs.length == 1) {
RuntimeClasspathViewer data = (RuntimeClasspathViewer)tabs[0].getData();
retargetActions(data);
}
}
});
fClasspathViewer = new RuntimeClasspathViewer(fPathTabFolder);
fClasspathViewer.addEntriesChangedListener(this);
fClasspathViewer.getControl().setFont(font);
fClassPathTabItem = new TabItem(fPathTabFolder, SWT.NONE, 0);
fClassPathTabItem.setText(LauncherMessages.getString("JavaClasspathTab.Us&er_classes_1")); //$NON-NLS-1$
fClassPathTabItem.setControl(fClasspathViewer.getControl());
fClassPathTabItem.setData(fClasspathViewer);
fBootpathViewer = new RuntimeClasspathViewer(fPathTabFolder);
fBootpathViewer.addEntriesChangedListener(this);
fBootpathViewer.getControl().setFont(font);
fBootPathTabItem = new TabItem(fPathTabFolder, SWT.NONE, 1);
fBootPathTabItem.setText(LauncherMessages.getString("JavaClasspathTab.&Bootstrap_classes_2")); //$NON-NLS-1$
fBootPathTabItem.setControl(fBootpathViewer.getControl());
fBootPathTabItem.setData(fBootpathViewer);
Composite pathButtonComp = new Composite(comp, SWT.NONE);
GridLayout pathButtonLayout = new GridLayout();
pathButtonLayout.marginHeight = 0;
pathButtonLayout.marginWidth = 0;
pathButtonComp.setLayout(pathButtonLayout);
gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_FILL);
pathButtonComp.setLayoutData(gd);
pathButtonComp.setFont(font);
createVerticalSpacer(comp, 2);
fClassPathDefaultButton = new Button(comp, SWT.CHECK);
fClassPathDefaultButton.setText(LauncherMessages.getString("JavaEnvironmentTab.Use_defau<_classpath_10")); //$NON-NLS-1$
gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalSpan = 2;
fClassPathDefaultButton.setLayoutData(gd);
fClassPathDefaultButton.setFont(font);
fClassPathDefaultButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleClasspathDefaultButtonSelected();
}
});
createVerticalSpacer(pathButtonComp, 1);
List advancedActions = new ArrayList(5);
RuntimeClasspathAction action = new MoveUpAction(null);
Button button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new MoveDownAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new RemoveAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddProjectAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddJarAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddExternalJarAction(null, DIALOG_SETTINGS_PREFIX);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddFolderAction(null);
advancedActions.add(action);
action = new AddExternalFolderAction(null, DIALOG_SETTINGS_PREFIX);
advancedActions.add(action);
action = new AddVariableAction(null);
advancedActions.add(action);
action = new AttachSourceAction(null);
advancedActions.add(action);
IAction[] adv = (IAction[])advancedActions.toArray(new IAction[advancedActions.size()]);
action = new AddAdvancedAction(null, adv);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
retargetActions(fClasspathViewer);
}
| public void createControl(Composite parent) {
Font font = parent.getFont();
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
WorkbenchHelp.setHelp(getControl(), IJavaDebugHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_CLASSPATH_TAB);
GridLayout topLayout = new GridLayout();
topLayout.numColumns = 2;
comp.setLayout(topLayout);
GridData gd;
createVerticalSpacer(comp, 2);
fPathTabFolder = new TabFolder(comp, SWT.NONE);
gd = new GridData(GridData.FILL_BOTH);
gd.heightHint = 200;
gd.widthHint = 250;
fPathTabFolder.setLayoutData(gd);
fPathTabFolder.setFont(font);
fPathTabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TabItem[] tabs = fPathTabFolder.getSelection();
if (tabs.length == 1) {
RuntimeClasspathViewer data = (RuntimeClasspathViewer)tabs[0].getData();
retargetActions(data);
}
}
});
fClasspathViewer = new RuntimeClasspathViewer(fPathTabFolder);
fClasspathViewer.addEntriesChangedListener(this);
fClasspathViewer.getControl().setFont(font);
fClassPathTabItem = new TabItem(fPathTabFolder, SWT.NONE, 0);
fClassPathTabItem.setText(LauncherMessages.getString("JavaClasspathTab.Us&er_classes_1")); //$NON-NLS-1$
fClassPathTabItem.setControl(fClasspathViewer.getControl());
fClassPathTabItem.setData(fClasspathViewer);
fBootpathViewer = new RuntimeClasspathViewer(fPathTabFolder);
fBootpathViewer.addEntriesChangedListener(this);
fBootpathViewer.getControl().setFont(font);
fBootPathTabItem = new TabItem(fPathTabFolder, SWT.NONE, 1);
fBootPathTabItem.setText(LauncherMessages.getString("JavaClasspathTab.&Bootstrap_classes_2")); //$NON-NLS-1$
fBootPathTabItem.setControl(fBootpathViewer.getControl());
fBootPathTabItem.setData(fBootpathViewer);
Composite pathButtonComp = new Composite(comp, SWT.NONE);
GridLayout pathButtonLayout = new GridLayout();
pathButtonLayout.marginHeight = 0;
pathButtonLayout.marginWidth = 0;
pathButtonComp.setLayout(pathButtonLayout);
gd = new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.HORIZONTAL_ALIGN_FILL);
pathButtonComp.setLayoutData(gd);
pathButtonComp.setFont(font);
createVerticalSpacer(comp, 2);
fClassPathDefaultButton = new Button(comp, SWT.CHECK);
fClassPathDefaultButton.setText(LauncherMessages.getString("JavaEnvironmentTab.Use_defau<_classpath_10")); //$NON-NLS-1$
gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalSpan = 2;
fClassPathDefaultButton.setLayoutData(gd);
fClassPathDefaultButton.setFont(font);
fClassPathDefaultButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleClasspathDefaultButtonSelected();
}
});
createVerticalSpacer(pathButtonComp, 1);
List advancedActions = new ArrayList(5);
RuntimeClasspathAction action = new MoveUpAction(null);
Button button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new MoveDownAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new RemoveAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddProjectAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddJarAction(null);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddExternalJarAction(null, DIALOG_SETTINGS_PREFIX);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
action = new AddFolderAction(null);
advancedActions.add(action);
action = new AddExternalFolderAction(null, DIALOG_SETTINGS_PREFIX);
advancedActions.add(action);
action = new AddVariableAction(null);
advancedActions.add(action);
action = new AttachSourceAction(null);
advancedActions.add(action);
IAction[] adv = (IAction[])advancedActions.toArray(new IAction[advancedActions.size()]);
action = new AddAdvancedAction(null, adv);
button = createPushButton(pathButtonComp, action.getText(), null);
action.setButton(button);
addAction(action);
retargetActions(fClasspathViewer);
}
|
diff --git a/android/src/processing/test/pew/PEW.java b/android/src/processing/test/pew/PEW.java
index 2ecd5b5..1e97381 100644
--- a/android/src/processing/test/pew/PEW.java
+++ b/android/src/processing/test/pew/PEW.java
@@ -1,1961 +1,1961 @@
package processing.test.pew;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Random;
import processing.core.PApplet;
import processing.core.PFont;
import processing.core.PImage;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.content.res.AssetFileDescriptor;
import android.content.Intent;
import android.net.Uri;
public class PEW extends PApplet{
AssetManager assetManager=null;// needed for sounds, has to be up in rank
SoundPool soundPool=null;
PlayerShip player;
Ship enemy;
PFont f;
ArrayList<Ship> enemyShips = new ArrayList<Ship>();// the player is not included
ArrayList<Projectile> enemyBullets = new ArrayList<Projectile>();
ArrayList<Projectile> playerBullets = new ArrayList<Projectile>();
ArrayList<Item> items = new ArrayList<Item>();// misc stuff and items
ArrayList<PowerUp> activePowerUps = new ArrayList<PowerUp>();
ArrayList<Animation> animations = new ArrayList<Animation>();
PFont fontG;
String highscoreFile = "highscore.txt";
final String GO = "Game Over";
PrintWriter output;
BufferedReader reader;
int highscoretop, highscoremid, highscorebottom, points;
Random gen = new Random();
boolean psychedelicMode = false;
boolean playGame, showMenu, showCredits, showHighScore, showDeath,
showInstructions, showOptions;
boolean musicReady = false, startUp = true;
public Menu menu;
ArrayList<PImage> loadedPics = new ArrayList<PImage>();
ArrayList<PImage> loadedShipPics = new ArrayList<PImage>();
ArrayList<PImage> loadedShipFlashPics = new ArrayList<PImage>();
ArrayList<PImage> loadedShipExpPics = new ArrayList<PImage>();
public void loadImages() {
PImage img;
img = loadImage("bullet.png");//#0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("playerbullet.png");// #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("coin.png");// #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("RocketE.png");// #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("Turret.png");// #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("GunUpgrade.png");// #5
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("bomb.png"); // #6
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("MainMenu.png");// #7
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("PsychedelicPowerUp1.png");// #8
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("spaceship.png");// #0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
- loadedPics.add(img);
+ loadedShipPics.add(img);
img = loadImage("Cruiser.png");// #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
- loadedPics.add(img);
+ loadedShipPics.add(img);
img = loadImage("Drone.png");// #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("EnemyMissileShip1.png");// #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("HerpADerp.png");// #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("ShipExpolsion1.png"); // #0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("BossBody.png"); // #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("Drone-hit.png"); // #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("EnemyMissileShip1-flash.png"); // #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("HerpADerpOld.png"); // #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("ShipExplosion1.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion2.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion3.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion4.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion5.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion6.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion7.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
}
BackgroundHandler bghandel = new BackgroundHandler();
Sounds sound = new Sounds();
MediaPlayer mediaPlayer = null;
public void setup() {
startUp = false;
// mediaPlayer =
// MediaPlayer.create(getApplicationContext(),R.raw.bitswithbyte);
sound.setUp();
fontG = createFont("Constantia", 48);
importHighscore();
loadImages();
menu = new Menu();
showMenu = true;
playGame = false;
bghandel.setBG("spaceBackground.png");
imageMode(CENTER);
smooth();
noStroke();
fill(255);
rectMode(CENTER); // This sets all rectangles to draw from the center
// point
player = new PlayerShip(displayWidth / 2, (4 * displayHeight) / 5);
orientation(PORTRAIT);
frameRate(30);
f = createFont("Impact", 24, true);
textFont(f, 24);
fill(255);
}
int tick = 1, spawnNum;
boolean spawning = false;
Level level = new Level();
public void draw() {
if (!psychedelicMode) {
background(0xff000000);
bghandel.scroll();
}
if (playGame == false) {
if (showCredits)
printCredits();
if (showMenu)
menu.showMenu();
if (showInstructions)
printInstructions();
if (showHighScore)
printHighScores();
if (showOptions)
printOptions();
if (showDeath)
printDeath();
} else {
spawning = true;
for (int j = 0; j < playerBullets.size(); j++) {
Projectile p = (Projectile) playerBullets.get(j);
p.move();
}
for (int j = 0; j < enemyShips.size(); j++) {
enemyShip s = (enemyShip) enemyShips.get(j);
s.act();
}
for (int j = 0; j < enemyBullets.size(); j++) {
Projectile p = (Projectile) enemyBullets.get(j);
p.move();
}
for (int j = 0; j < items.size(); j++) {
Item p = (Item) items.get(j);
p.move();
}
for (int i = activePowerUps.size()-1; i>=0; i--) {
PowerUp p = activePowerUps.get(i);
p.increment();
}
for (int i = 0; i < animations.size(); i++) {
Animation a = animations.get(i);
a.animate();
}
textAlign(LEFT);
text("Score: " + player.getScore() +" X"+player.scoreMultiplyer, displayWidth / 20, displayHeight / 20);
// text("Bullet Count: " + (enemyBullets.size() +
// playerBullets.size()), 10, 50);
// text("Ship Count: " + enemyShips.size(), 10, 75);
collisionDetection();
if (spawning)
level.spawn();
tick++;
if (tick == 100000)
tick = 0;
if (mousePressed) {
player.move();
if (tick % 3 == 0)
player.shoot();
}
player.display();
}
}
public void collisionDetection() {
for (int i = 0; i < playerBullets.size(); i++) {
Projectile p = (Projectile) playerBullets.get(i);
for (int j = 0; j < enemyShips.size(); j++) {
Ship s = (Ship) enemyShips.get(j);
if (p.isTouching(s)) {
s.hit();
p.removeSelf();
}
if (s instanceof Cruiser) {
Cruiser t = (Cruiser) s;
ArrayList<Turret> guns = t.getTurretList();
for (int k = 0; k < guns.size(); k++) {
Turret g = guns.get(k);
if (p.isTouching(g)) {
g.hit();
p.removeSelf();
}
}
}
}
}
for (int i = 0; i < enemyBullets.size(); i++) {
Projectile p = (Projectile) enemyBullets.get(i);
p.move();
if (p.isTouching(player)) {
player.hit();
p.removeSelf();
}
}
for (int i = 0; i < items.size(); i++) {
Item p = (Item) items.get(i);
p.move();
if (p.isTouching(player)) {
p.act();
}
}
for (int i = 0; i < enemyShips.size(); i++) {
Ship p = (Ship) enemyShips.get(i);
if (p.isTouching(player)) {
p.blowUp();
player.hit();
}
}
}
public void printCredits() {
PImage credit = loadImage("credit.png");
credit.resize(displayWidth, displayHeight);
image(credit,displayWidth/2,displayHeight/2);
PImage art = loadImage("bandart.png");
art.resize((int)(displayWidth *(1/3.0)),(int)(displayHeight*(1/ 6.0)));
image(art,(int)(displayWidth *(1/6.0)),(int)(displayHeight*(11/ 12.0)));
// BULD A BACK BUTTON AT TOP OF SCREEN
image(loadImage("Back.png"), displayWidth / 2, displayHeight / 12,
displayWidth, displayHeight / 6);
if (mousePressed && mouseY < displayHeight / 6) {
showCredits = false;
showMenu = true;
playGame = false;
}
//go to band link
if(mousePressed && mouseY > displayHeight *(5/6.0)&& mouseX < displayWidth *(1/3.0))
{
makeWebPage();
}
}
public void printInstructions() {
textAlign(CENTER);
image(loadImage("Instructions.png"), displayWidth /2 , displayHeight / 2,
displayWidth, displayHeight);
image(loadImage("Back.png"), displayWidth / 2, displayHeight / 12,
displayWidth, displayHeight / 6);
if (mousePressed && mouseY < displayHeight / 6.0f) {
showCredits = false;
showMenu = true;
playGame = false;
showInstructions = false;
}
}
public void printHighScores() {
for (int i = 1; i == 1; i++) {
importHighscore();
}
textAlign(CENTER);
image(loadImage("Back.png"), displayWidth / 2, displayHeight / 12,
displayWidth, displayHeight / 6);
text(" " + highscoretop, displayWidth / 2, displayHeight / 4);
text("AND YOU SHOULD FEEL BAD\nREALLY BAD\nGET OUT\n(0.0)",
displayWidth / 2, displayHeight / 3);
if (mousePressed && mouseY < displayHeight / 6.0f) {
showMenu = true;
showHighScore = false;
}
}
public void printOptions() {
textAlign(CENTER);
image(loadImage("Back.png"), displayWidth / 2, displayHeight / 12,
displayWidth, displayHeight / 6);
text("YOU AINT SEEN NOTHING YET!", displayWidth / 2, displayHeight / 4);
text("...seriously, we have yet to code this...", displayWidth / 2,
displayHeight / 3);
if (mousePressed && mouseY < displayHeight / 6.0f) {
showMenu = true;
showOptions = false;
}
}
public void printDeath() {
GameOverMessage(GO);
}
public void onStop() {
if (soundPool != null) { // must be checked because or else crash when
// return from landscape mode
soundPool.release(); // release the player
soundPool = null;
}
if(musicReady)
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
musicReady=false;
}
super.onStop();
}
public void onPause() {
showMenu = false;
if (soundPool != null) { // must be checked because or else crash when
// return from landscape mode
soundPool.release(); // release the player
soundPool=null;
}
if(musicReady)
{
mediaPlayer.stop();
mediaPlayer.release();
musicReady=false;
mediaPlayer=null;
}
playGame = false;
super.onPause();
}
public void onResume()
{
if(!startUp && !musicReady)
{
sound.setUp();
if(mediaPlayer!=null)
{
mediaPlayer.start();
print("THIS DIDNT MAKE ITSELF PROPERLY JERKWAD");
}
}
showMenu = true;
super.onResume();
}
abstract class Actor {
int locX, locY, radius, speed;
boolean dir;
PImage img;
public void move() {
}
public boolean isTouching(Actor b) {
if (sqrt(pow(locX - b.locX, 2) + pow(locY - b.locY, 2)) < (radius + b.radius))
return true;
else
return false;
}
public void display() {
image(img, locX, locY);
}
public int getLocX() {
return locX;
}
public int getLocY() {
return locY;
}
}
public class BackgroundHandler {
PImage bgimg, upcomingImg;
int scrolly, upcomingScrolly;
boolean needFlip;
BackgroundHandler() {
}
public void setBG(String img) {
bgimg = loadImage(img);
bgimg.resize((int)((displayWidth/480.0)*bgimg.width), (int)((displayHeight/800.0)*bgimg.height));
upcomingImg = bgimg;
scrolly = displayHeight;
upcomingScrolly = 0;
}
public void scroll() {
image(bgimg, displayWidth / 2, scrolly - bgimg.height / 2);
scrolly += 5;
if (scrolly - bgimg.height >= 0) {
scrollInNew();
}
}
public void scrollInNew() {
image(upcomingImg, displayWidth / 2, upcomingScrolly
- upcomingImg.height / 2);
upcomingScrolly += 5;
if (upcomingScrolly >= displayHeight)
flip();
}
public void loadNewImg(String img) {
upcomingImg = loadImage(img);
upcomingScrolly = 0;
}
public void flip() {
needFlip = false;
bgimg = upcomingImg;
scrolly = upcomingScrolly;
upcomingScrolly = 0;
}
}
public class Bomb extends Projectile {
int count;
int lifeSpan;
int speed;
Bomb(int locX, int locY) {
super(locX, locY, 6, 0, 5);
count = 0;
lifeSpan = 75;
speed = 5;
enemyBullets.add(this);
}
Bomb(int locX, int locY, int dispx, int dispy) {
super(locX, locY, 10, dispx, dispy);
count = 0;
lifeSpan = 25;
speed = 5;
enemyBullets.add(this);
}
public void move() {
super.move();
count++;
if (count > lifeSpan) {
detonate();
removeSelf();
}
}
public void detonate() {
for (float degree = 0; degree < 2 * PI; degree += PI / 12) {
int dispx = (int) (speed * sin(degree));
int dispy = (int) (speed * cos(degree));
new Bullet(locX, locY, dispx, dispy);
}
}
}
public class BombLauncher extends Gun {
BombLauncher() {
}
public void shoot(int locX, int locY) {
new Bomb(locX, locY);
}
}
class Bullet extends Projectile {
Bullet(int xpos, int ypos, int h, int s) {
super(xpos, ypos, 0, h, s);
enemyBullets.add(this);
radius = 7;
}
Bullet(int xpos, int ypos) {
super(xpos, ypos, 0, 0, 4);
enemyBullets.add(this);
radius = 7;
}
}
public class Cruiser extends enemyShip {
ArrayList<Turret> guns;
int[] turretsX = { -600, -530, -470, -420, -376, -340, -296, -150, -90,
-30, 30, 100, 220, 300, 370, 450 };
int[] turretsY = { 136, 136, 136, 90, 18, 90, 18, 162, 162, 162, 162,
166, 82, 82, 82, 82 };
int count;
boolean moving, shooting;
int activeGun;
Turret activeTurret;
int destinationX, destinationY;
Cruiser(ArrayList<Turret> g) {
super(1, 7, 1000, 1000, 3);
guns = g;
prepairTurrets();
count = 0;
destinationX = locX;
destinationY = displayHeight / 4;
moving = true;
shooting = false;
selectNewGun();
}
public void prepairTurrets() {
double gunRange = 0;
if (guns.size() > 0)
gunRange = 800 / guns.size();
for (int i = 0; i < guns.size(); i++) {
guns.get(i).moveTo(locX + turretsX[i], locY + turretsY[i]);
}
}
public void act() {
display();
displayTurrets();
checkTurrentHealths();
if (moving)
move();
else if (shooting)
shoot();
else if (guns.size() > 0)
selectNewGun();
else
super.blowUp();
}
public void selectNewGun() {
int selection = gen.nextInt(guns.size());
activeTurret = guns.get(selection);
destinationX = displayWidth / 2 - activeTurret.getLocX();
// destinationY = activeTurret.getLocY();
activeGun = selection;
activeTurret = guns.get(selection);
print("" + selection + " at desintation " + destinationX + "\n");
moving = true;
}
public void move() {
int delX = 0, delY = 0;
if (abs(destinationY - locY) > 5) {
if (destinationY > locY) {
locY += speed;
delY = speed;
} else {
locY -= speed;
delY = -speed;
}
} else {
if (destinationX > 0) {
locX += speed;
delX = speed;
destinationX -= speed;
} else {
locX -= speed;
delX = -speed;
destinationX += speed;
}
}
moveTurrets(delX, delY);
print("%%" + (destinationX - locX));
if (abs(destinationY - locY) < 10 && abs(destinationX) < 10) {
moving = false;
shooting = true;
count = 0;
print("From Moving to Shooting.");
}
}
public void shoot() {
for (int i = 0; i < guns.size(); i++) {
if (guns.get(i).getLocX() > 0
&& guns.get(i).getLocX() < displayWidth)// aka on screen
{
guns.get(i).act();
}
}
count++;
if (count > 1000) {
shooting = false;
}
}
public void moveTurrets(int delX, int delY) {
for (int i = 0; i < guns.size(); i++) {
guns.get(i).increment(delX, delY);
}
}
public void displayTurrets() {
for (int i = 0; i < guns.size(); i++) {
guns.get(i).display();
}
}
public void checkTurrentHealths() {
for (int i = guns.size() - 1; i >= 0; i--) {
if (guns.get(i).getHealth() < 1) {
if (guns.get(i) == activeTurret)
shooting = false;
guns.remove(i);
}
}
if (guns.size() < 1) {
super.blowUp();
}
}
public ArrayList<Turret> getTurretList() {
return guns;
}
public void hit() {
// do nothing;
}
}
public class DinkyGun extends Gun {
public void shoot(int locX, int locY) {
new Bullet(locX, locY);
}
}
public class doubleGun extends Gun {
public void shoot(int locX, int locY) {
new Bullet(locX, locY,-1,2);
new Bullet(locX, locY,1,2);
}
}
public class tripleGun extends Gun {
public void shoot(int locX, int locY) {
new Bullet(locX, locY,-1,2);
new Bullet(locX, locY,1,2);
new Bullet(locX, locY,0,2);
}
}
class Drone extends enemyShip {
Gun weapon;
boolean flip = true;
Drone(int imageIndex, int f, int h, int p, int s) {
super(imageIndex, f, h, p, s);
weapon = new DinkyGun();
}
}
void GameOverMessage(String msg) {
image(loadImage("Back.png"), displayWidth / 2, displayHeight / 12,
displayWidth, displayHeight / 6);
textFont(fontG);
fill(110, 50, 255);
textAlign(CENTER);
text(msg + "\nScore: " + points + "\nHigh Score: " + highscoretop,
displayWidth / 2, displayHeight / 2);
if (mousePressed && mouseY < displayHeight / 6) {
level.reset();
enemyShips.clear();
enemyBullets.clear();
playerBullets.clear();
items.clear();
activePowerUps.clear();
animations.clear();
textAlign(LEFT);
textFont(f, 24);
fill(255);
showDeath = false;
showMenu = true;
playGame = false;
points = 0;
tick = 0;
psychedelicMode = false;
player = new PlayerShip(displayWidth / 2, (4 * displayHeight) / 5);
}
}
abstract class Gun {
public void shoot(int xpos, int ypos) {
}
}
public class Hallucinate extends PowerUp {
Hallucinate(int locX, int locY) {
super(locX, locY,8);
}
public void act()
{
player.incrementScoreMultiplyer(4);
super.act();
}
public void doEffect() {
psychedelicMode = true;
}
public void removeEffect() {
psychedelicMode = false;
player.incrementScoreMultiplyer(-4);
}
}
public class HelixGun extends Gun {
HelixGun() {
}
boolean left = false;
public void shoot(int xpos, int ypos) {
left = !left;
if (left)
new SinShot(xpos, ypos - 10, 2, 2);
else
new SinShot(xpos, ypos + 10, -2, 2);
}
}
public void importHighscore() {
// Open the file from the createWriter()
reader = createReader(highscoreFile);
if (reader == null) {
highscoretop = 0;
return;
}
String line;
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
line = null;
}
if (line != null) {
highscoretop = PApplet.parseInt(line);
println(highscoretop);
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateHighscore() {
if (highscoretop < points) {
highscoretop = points;
// Create a new file in the sketch directory
output = createWriter(highscoreFile);
output.println(highscoretop);
output.close(); // Writes the remaining data to the file & Finishes
// the file
}
}
abstract class Item extends Actor {
int worth;
int speed = 3;
Item(int posx, int posy, int imageIndex) {
locX = posx;
locY = posy;
img = loadedPics.get(imageIndex);
items.add(this);
}
public void move() {
locY += speed;
if (locY > displayHeight + 100)
removeSelf();
image(img, locX, locY);
}
public void removeSelf() {
for (int i = items.size() - 1; i >= 0; i--) {
Item p = (Item) items.get(i);
if (p == this) {
items.remove(i);
break;
}
}
}
public void act() {
}
}
public void keyPressed() {
if (key == ' ')
player.shoot();
if (key == 'c') // Clear highscore
{
highscoretop = 0;
// Create a new file in the sketch directory
output = createWriter(highscoreFile);
output.println(highscoretop);
output.close(); // Writes the remaining data to the file & Finishes
// the file
}
// this gets switched around when porting to android
// if(key == 'r')
if (key == CODED && keyCode == android.view.KeyEvent.KEYCODE_MENU) {
playGame = false;
showMenu = true;
showCredits = false;
}
}
public class Level {
int waveNum, count;
boolean flip, inWave;
int waveShipsSpawned, waveShipsEnd, waveType;
int path;
int spawnFreq, shipFreq, shipHP, shipSpeed, uniqueRarity, shipImage;
int rando;
Level() {
count = 0;
waveNum = 0;
flip = true;
inWave = false;
waveShipsSpawned = 0;
waveShipsEnd = 0;
waveType = 0;
path = 1;
}
void reset() {
count = 0;
waveNum = 0;
flip = true;
inWave = false;
waveShipsSpawned = 0;
waveShipsEnd = 0;
waveType = 0;
path = 1;
}
void spawn() {
if (inWave) {
if (waveNum%8 == 7 && enemyShips.size() == 0) {
spawnCruiser();
} else {
if (waveType == 0)
spawnScissor();
if (waveType == 1)
spawnSideToSide();
}
if (waveShipsSpawned >= waveShipsEnd)
inWave = false;
} else {
if (enemyShips.size() == 0) {
newWave();
}
}
count++;
if (count == 10000)
count = 0;
}
void spawnScissor() {
if (count%spawnFreq == 0)
{
if (flip) {
path = 1;
flip = !flip;
} else {
path = 2;
flip = !flip;
}
spawnShip();
}
}
void spawnSideToSide() {
if (count%spawnFreq == 0) {
if (flip) {
path = 3;
flip = !flip;
} else {
path = 4;
flip = !flip;
}
spawnShip();
}
}
void spawnCruiser() {
ArrayList<Turret> guns = new ArrayList<Turret>();
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new SpiralGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new BombLauncher(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new doubleGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new TestGun(), 50));
guns.add(new Turret(new tripleGun(), 50));
guns.add(new Turret(new TestGun(), 50));
enemyShips.add(new Cruiser(guns));
}
void spawnShip() {
rando = gen.nextInt(100);
if (rando < uniqueRarity) {
rando = gen.nextInt(3)+2;
Drone s = new Drone(rando, shipFreq, shipHP, path, shipSpeed);
s.setGun(getRandGun());
enemyShips.add(s);
} else {
Drone s = new Drone(shipImage, shipFreq, shipHP, path, shipSpeed);
enemyShips.add(s);
}
waveShipsSpawned++;
}
void newWave() {
waveNum++;
inWave = true;
waveType = gen.nextInt(2);
waveShipsSpawned = 0;
waveShipsEnd = waveNum * 2 + 10;
spawnFreq = 30 - waveNum / 2;
shipFreq = 25 - waveNum / 3;
shipHP = 3 + waveNum / 2;
shipSpeed = 6 + waveNum / 2;
uniqueRarity = 5 + waveNum;
shipImage = gen.nextInt(3)+2;
}
}
public class Menu {
PImage MenuImage;// = loadImage("MainMenu.png");;
float PlayX, PlayY, playSizeY, playSizeX; // Position of square button
float creditsX, creditsY, creditsSizeX, creditsSizeY;
float scoreX, scoreY, scoreSizeX, scoreSizeY;
float tutX, tutY, tutSizeX, tutSizeY;
float opX, opY, opSizeX, opSizeY;
Menu() {
playGame = false;
MenuImage = loadedPics.get(7);
PlayX = displayWidth / 13.2f;
PlayY = (displayHeight / 1.865f);
playSizeY = displayHeight / 7.8f;// Diameter of
playSizeX = displayWidth / 1.201f;
scoreX = displayWidth * (1 / 2.0f);
scoreY = displayHeight * (5 / 7.4f);
scoreSizeX = displayWidth / 2.402f;
scoreSizeY = displayHeight / 7.8f;
creditsX = displayWidth * (1 / 2.0f);
creditsY = displayHeight * (6 / 7.4f);
creditsSizeX = displayWidth / 2.402f;
creditsSizeY = displayHeight / 7.8f;
tutX = displayWidth * (0.07f);
tutY = displayHeight * (5 / 7.4f);
tutSizeX = displayWidth / 2.402f;
tutSizeY = displayHeight / 7.8f;
opX = displayWidth * (0.07f);
opY = displayHeight * (6 / 7.4f);
opSizeX = displayWidth / 2.402f;
opSizeY = displayHeight / 7.8f;
}
public void showMenu() {
if(musicReady)
mediaPlayer.start();
else
sound.buildPlayer();
spawning = false;
playGame = false;
image(MenuImage, displayWidth / 2, displayHeight / 2, displayWidth,
displayHeight);
if (overBox(PlayX, PlayY, playSizeX, playSizeY)) {
if (mousePressed == true) {
showMenu = false;
playGame = true;
}
}
if (overBox(creditsX, creditsY, creditsSizeX, creditsSizeY)) {
if (mousePressed == true) {
showCredits = true;
showMenu = false;
}
}
if (overBox(tutX, tutY, tutSizeX, tutSizeY)) {
if (mousePressed == true) {
showInstructions = true;
showMenu = false;
}
}
if (overBox(opX, opY, opSizeX, opSizeY)) {
if (mousePressed == true) {
showOptions = true;
showMenu = false;
}
}
if (overBox(scoreX, scoreY, scoreSizeX, scoreSizeY)) {
if (mousePressed == true) {
showHighScore = true;
showMenu = false;
}
}
}
public boolean overBox(float a, float b, float w, float h) {
return (mouseX >= a && mouseX <= a + w && mouseY >= b && mouseY <= b
+ h);
}
}
class Money extends Item {
Money(int posx, int posy, int w) {
super(posx, posy, 2);
worth = w;
radius = 10;
}
public void act() {
this.removeSelf();
player.addMoney(worth);
println("+" + worth);
}
}
public class PlayerGunLev1 extends Gun {
boolean flip = false;
public void shoot(int xpos, int ypos) {
sound.play(sound.pew);
if (flip)
new PlayerBullet(xpos + 12, ypos, 0, -30);
else
new PlayerBullet(xpos - 12, ypos, 0, -30);
flip = !flip;
}
}
public class PlayerGunLev2 extends Gun {
public void shoot(int xpos, int ypos) {
sound.play(sound.pew);
new PlayerBullet(xpos + 12, ypos, 2, -30);
new PlayerBullet(xpos , ypos, 0, -30);
new PlayerBullet(xpos - 12, ypos, -2, -30);
}
}
public class PlayerGunLev3 extends Gun {
public void shoot(int xpos, int ypos) {
sound.play(sound.pew);
new PlayerBullet(xpos - 12, ypos, -3, -30);
new PlayerBullet(xpos + 12, ypos, 3, -30);
new PlayerBullet(xpos +12, ypos, 0, -30);
new PlayerBullet(xpos - 12, ypos, 0, -30);
}
}
public class PlayerGunLev4 extends Gun {
public void shoot(int xpos, int ypos) {
sound.play(sound.pew);
new PlayerBullet(xpos, ypos, 0, -30);
new PlayerBullet(xpos + 12, ypos, 3, -30);
new PlayerBullet(xpos - 12, ypos, -3, -30);
new PlayerBullet(xpos + 12, ypos, 6, -30);
new PlayerBullet(xpos - 12, ypos, -6, -30);
}
}
public class PlayerGunLev5 extends Gun {
public void shoot(int xpos, int ypos) {
sound.play(sound.pew);
new PlayerBullet(xpos, ypos, 2, -30);
new PlayerBullet(xpos, ypos, -2, -30);
new PlayerBullet(xpos + 12, ypos, 4, -30);
new PlayerBullet(xpos - 12, ypos, -4, -30);
new PlayerBullet(xpos + 12, ypos, 8, -30);
new PlayerBullet(xpos - 12, ypos, -8, -30);
}
}
public class PlayerBullet extends Projectile {
PlayerBullet(int locX, int locY, int xdisp, int ydisp) {
super(locX, locY, 1, xdisp, ydisp);
playerBullets.add(this);
}
public void removeSelf() {
for (int i = playerBullets.size() - 1; i >= 0; i--) {
Projectile p = (Projectile) playerBullets.get(i);
if (p == this) {
playerBullets.remove(i);
break;
}
}
}
}
class PlayerShip extends Ship {
int gunLev, scoreMultiplyer;
public PlayerShip(int xpos, int ypos) {
super(0);
dir = true;
radius = 25;
locX = xpos;
locY = ypos;
speed = 25;
weapon = new PlayerGunLev1();
gunLev = 1;
scoreMultiplyer = 1;
}
public void move() {
boolean flag = true;
int dX, dY;
float magnitude;
dX = mouseX - locX;
dY = mouseY - 80 - locY;
if (abs(dX) > 15 || abs(dY) > 15) {
magnitude = sqrt(dX * dX + dY * dY);
locX += PApplet.parseInt(speed * dX / (magnitude));
locY += PApplet.parseInt(speed * dY / (magnitude));
} else {
locX += dX;
locY += dY;
}
if (locX < 0)
locX = 0;
if (locX > displayWidth)
locX = displayWidth;
if (locY < 0)
locY = 0;
if (locY > displayHeight)
locY = displayHeight;
image(img, locX, locY);
}
boolean left = false;
public void hit()
{
incrementGunLev(-1);
scoreMultiplyer=1;
}
public void incrementGunLev(int i)
{
gunLev += i;
if(gunLev <= 0)
this.blowUp();
else if(gunLev==1)
weapon = new PlayerGunLev1();
else if(gunLev==2)
weapon = new PlayerGunLev2();
else if(gunLev==3)
weapon = new PlayerGunLev3();
else if(gunLev==4)
weapon = new PlayerGunLev4();
else if(gunLev==5)
weapon = new PlayerGunLev5();
else gunLev -=i;
}
public void shoot() {
weapon.shoot(locX, locY);
}
public void incrementScoreMultiplyer(int i)
{
scoreMultiplyer+=i;
if(scoreMultiplyer<1)
scoreMultiplyer=1;
}
public void blowUp() {
println("THE PLAYER HAS DIED");
super.blowUp();
showDeath = true;
playGame = false;
updateHighscore();
}
public void addMoney(int p) {
points += p*scoreMultiplyer;
}
public int getScore() {
return points;
}
}
public class PowerUp extends Item {
int counter, lifeSpan;
PowerUp(int posx, int posy,int imgIndex) {
super(posx, posy, imgIndex);
radius = 10;
activePowerUps.add(this);
counter = 0;
lifeSpan = 250;
}
public void act() {
this.removeSelf();
doEffect();
}
public void increment() {
counter++;
if (counter > lifeSpan) {
for (int i = activePowerUps.size() - 1; i >= 0; i--) {
PowerUp p = activePowerUps.get(i);
if (p == this) {
activePowerUps.remove(i);
removeEffect();
break;
}
}
}
}
public void doEffect() {
}
public void removeEffect() {
}
}
public class GunUp extends PowerUp
{
GunUp(int posX, int posY)
{
super(posX,posY,5);
lifeSpan = 0;
}
public void act()
{
player.incrementGunLev(1);
this.removeSelf();
}
}
void makeRandPowerUp(int i, int j)
{
int b = gen.nextInt(2);
if (b == 0)
new Hallucinate(i,j);
if (b==1)
new GunUp(i,j);
}
abstract class Projectile extends Actor {
int xdisp, ydisp;
Projectile(int xpos, int ypos, int imageIndex, int delx, int dely) {
locX = xpos;
locY = ypos;
this.img = loadedPics.get(imageIndex);
xdisp = delx;
ydisp = dely;
radius = 7;
}
public void move() {
locY += ydisp;
locX += xdisp;
if (locY < -100 || locY > displayHeight + 100 || locX < -100
|| locX > displayWidth + 100)
removeSelf();
display();
}
public void removeSelf() {
for (int i = enemyBullets.size() - 1; i >= 0; i--) {
Projectile p = (Projectile) enemyBullets.get(i);
if (p == this) {
enemyBullets.remove(i);
break;
}
}
}
}
public class Rocket extends Projectile {
Rocket(int xpos, int ypos, int h, int s) {
super(xpos, ypos, 3, h, s);
enemyBullets.add(this);
}
}
abstract class Ship extends Actor {
int health = 1;
boolean dir = false; // up cor. to true
Gun weapon;
Ship(int imageIndex) {
radius = 40;
img = loadedShipPics.get(imageIndex);
}
public void display() {
image(img, locX, locY);
}
public void move() {
}
public void move(int t)// used to pass the tick count to enemy ships
{
}
public void hit() {
health--;
if (health == 0)
blowUp();
}
public void shoot() {
weapon.shoot(locX, locY);
}
public void blowUp() {
ShipExplosion s = new ShipExplosion(locX, locY);
animations.add(s);
removeSelf();
}
public void removeSelf() {
for (int i = enemyShips.size() - 1; i >= 0; i--) {
Ship p = (Ship) enemyShips.get(i);
if (p == this) {
enemyShips.remove(i);
break;
}
}
}
}
class SinShot extends Projectile {
int xinit, yinit;
boolean flip = false;
SinShot(int xpos, int ypos, int dispx, int dispy) {
super(xpos, ypos, 0, dispx, dispy);
xinit = xpos;
yinit = ypos;
enemyBullets.add(this);
}
public void move() {
locY += ydisp;
if (flip)
locX += xdisp;
else
locX -= xdisp;
if (locX > xinit + 50 || locX < xinit - 50)
flip = !flip;
if (locY < -100 || locY > displayHeight + 100 || locX < -100
|| locX > displayWidth + 100)
removeSelf();
display();
}
}
public class Sounds {
public int pew;
public void setUp() {
if(assetManager ==null)
assetManager = getAssets();// needed for sounds, has to be up in
// rank
if(soundPool==null)
soundPool = new SoundPool(20, AudioManager.STREAM_MUSIC, 0);
try { // loading these files can throw an exception and therefore
// you HAVE to have a way to handle those events
pew = soundPool.load(assetManager.openFd("pew.ogg"), 1); // load
// the
// files
} catch (IOException e) {
print("OOOOPPPPPPPPPPPPPPPPPPPSSSSSSSSSSSSSSSS");
e.printStackTrace(); // you can leave this empty...or use some
// other way to notify the
// user/developer something went wrong
buildPlayer();
}
}
public void play(int sound) {
soundPool.play(sound, 1, 1, 0, 0, 1);// no idea why this is to be
// quite honest
}
public void buildPlayer() {
if(mediaPlayer==null)
mediaPlayer = new MediaPlayer();
AssetFileDescriptor fd = null;
try {
fd = assetManager.openFd("bitswithbyte.ogg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.setDataSource(fd.getFileDescriptor(),
fd.getStartOffset(), fd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(true);
try {
mediaPlayer.prepare();
musicReady = true;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class SpiralGun extends Gun {
float degree = 0;
int speed = 5;
int dispx, dispy;
SpiralGun() {
}
public void shoot(int locX, int locY) {
degree += PI / 12;
dispx = (int) (speed * sin(degree));
dispy = (int) (speed * cos(degree));
new Bullet(locX, locY, dispx, dispy);
// print(""+dispx +","+ dispy);
}
}
class SpiralShip extends enemyShip {
Gun weapon;
int count = 0;
boolean shooting = false;
boolean flip = true;
SpiralShip(int startx, int starty, int speed, int imageIndex, int f,
int h, int p) {
super(imageIndex, 1, h, p, speed);
weapon = new SpiralGun();
}
public void shoot() {
if (count % 100 == 0)
shooting = !shooting;
if (shooting)
weapon.shoot(locX, locY);
}
}
class SpreadGunE extends Gun {
public void shoot(int xpos, int ypos) {
new Bullet(xpos, ypos, 0, 5);
new Bullet(xpos, ypos, 1, 4);
new Bullet(xpos, ypos, -1, 4);
new Bullet(xpos, ypos, 2, 3);
new Bullet(xpos, ypos, -2, 3);
}
}
public class StarGun extends Gun {
float degree = 0;
int speed = 5;
int dispx, dispy;
StarGun() {
}
public void shoot(int locX, int locY) {
for (degree = 0; degree < 2 * PI; degree += PI / 12) {
dispx = (int) (speed * sin(degree));
dispy = (int) (speed * cos(degree));
new Bullet(locX, locY, dispx, dispy);
// print(""+dispx +","+ dispy);
}
}
}
Gun getRandGun()
{
int i = gen.nextInt(8);
if(i == 0)
return new DinkyGun();
else if(i == 1)
return new StarGun();
else if(i == 2)
return new SpreadGunE();
else if(i == 3)
return new SpiralGun();
else if(i == 4)
return new doubleGun();
else if(i == 5)
return new tripleGun();
else if(i == 6)
return new BombLauncher();
else if(i == 7)
return new HelixGun();
else
return new DinkyGun();
}
class TestGun extends Gun {
public void shoot(int xpos, int ypos) {
new Bullet(xpos, ypos, 0, 5);
}
}
public class Turret extends Actor {
int health, freq, count;
Gun weapon;
Turret(Gun g, int hlth) {
health = hlth;
radius = 15;
weapon = g;
img = loadedPics.get(4);
freq = gen.nextInt(10) + 10;
count = 0;
}
public void act() {
count++;
if (count % freq == 0)
shoot();
}
public void increment(int delX, int delY) {
locX += delX;
locY += delY;
}
public void moveTo(int newx, int newy) {
locX = newx;
locY = newy;
}
public void shoot() {
weapon.shoot(locX, locY);
}
public int getHealth() {
return health;
}
public void hit() {
// s.play(2);
health--;
}
}
abstract class enemyShip extends Ship {
int path, count = 0, lifeTime = 500, freq, speed, xinit, yinit,
imageIndex;
boolean flip = false, flashing = false;
enemyShip(int imgIndex, int f, int h, int p, int s) {
super(imgIndex);
imageIndex = imgIndex;
speed = s;
freq = f;
path = p;
health = h;
weapon = new DinkyGun();
if (path == 1) {
xinit = locX = displayWidth/4;
yinit = locY = 0;
}
if (path == 2) {
xinit = locX = 3 * displayWidth/4;
yinit = locY = 0;
}
if (path == 3) {
xinit = locX = displayWidth/5;
yinit = locY = 0;
flip = true;
}
if (path == 4) {
xinit = locX = 4 * displayWidth/5;
yinit = locY = 0;
flip = false;
}
}
public void act() {
count++;
display();
if (count > lifeTime)
flyAway();
else {
move();
if (count % freq == 0)
shoot();
}
if (flashing) {
revert();
}
if (locY < -400 || locY > displayHeight + 400 || locX < -400
|| locX > displayWidth + 400)
removeSelf();
}
public void move() {
if (path == 0) { // STRAIGHT DOWN LIKE A BALLER
locY += speed;
}
if (path == 1) { // DOWN A BIT THEN DIAG RIGHT
if (locY < displayHeight / 4) {
locY += speed;
} else {
locY += speed / sqrt(2);
locX += speed / sqrt(2);
}
}
if (path == 2) { // DOWN A BIT THEN DIAG LEFT
if (locY < displayHeight / 4) {
locY += speed;
} else {
locY += speed / sqrt(2);
locX -= speed / sqrt(2);
}
}
if (path == 3 || path == 4) { // SIDE TO SIDE
if (count % 3 == 0)
locY += 1;
if (flip)
locX += speed;
else
locX -= speed;
if (locX > 8 * displayWidth / 9 || locX < displayWidth / 9) {
locY += speed * 3;
flip = !flip;
}
}
if (path == 5) { // DOWN LEFT, THEN DOWN RIGHT, THEN DOWN
if (count < 50) {
locY += speed;
locX -= speed / 2;
} else if (count < 125) {
locY += speed;
locX += speed / 2;
} else {
locY += speed / 2;
}
}
if (path == 6) { // SOME WEIRD SINE SHIT
locY += speed;
locX += sin(count * 3.14f / 6) * 5;
}
if (path == 9) { // TO THE RIGHT TO THE RIGHT
locX += speed;
}
}
public void flyAway() {
locY += speed * 2;
this.display();
}
public void blowUp() {
int w = gen.nextInt(20) + 1;
new Money(locX, locY, w);
int randomInt = gen.nextInt(20);
if (randomInt == 1) {
makeRandPowerUp(locX,locY);
}
ShipExplosion s = new ShipExplosion(locX, locY);
animations.add(s);
removeSelf();
}
public void shoot() {
weapon.shoot(locX, locY);
}
public void setGun(Gun g) {
weapon = g;
}
public void hit() {
flash();
health--;
if (health == 0)
blowUp();
}
public void flash() {
img = loadedShipFlashPics.get(imageIndex);
flashing = true;
// s.play(1);
}
public void revert() {
img = loadedPics.get(imageIndex);
flashing = false;
}
}
public class Animation
{
int locX, locY, current, count;
PImage currentImg;
Animation(int xLoc, int yLoc)
{
locX = xLoc;
locY = yLoc;
}
public void animate()
{
}
public void removeSelf()
{
for(int i = animations.size()-1; i>=0; i--)
{
Animation a = (Animation) animations.get(i);
if (a == this)
{
animations.remove(i);
break;
}
}
}
}
public class ShipExplosion extends Animation
{
ShipExplosion(int x,int y)
{
super(x, y);
current = 0;
currentImg = loadedShipExpPics.get(0);
}
public void animate()
{
image(currentImg, locX, locY);
current++;
if(current <= loadedShipExpPics.size()-1)
{
currentImg = loadedShipExpPics.get(current);
} else {
super.removeSelf();
}
}
}
public int sketchWidth() {
return displayWidth;
}
public int sketchHeight() {
return displayHeight;
}
public void makeWebPage()
{
String url = "http://www.8bitweapon.com/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
| false | true | public void loadImages() {
PImage img;
img = loadImage("bullet.png");//#0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("playerbullet.png");// #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("coin.png");// #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("RocketE.png");// #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("Turret.png");// #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("GunUpgrade.png");// #5
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("bomb.png"); // #6
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("MainMenu.png");// #7
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("PsychedelicPowerUp1.png");// #8
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("spaceship.png");// #0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("Cruiser.png");// #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("Drone.png");// #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("EnemyMissileShip1.png");// #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("HerpADerp.png");// #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("ShipExpolsion1.png"); // #0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("BossBody.png"); // #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("Drone-hit.png"); // #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("EnemyMissileShip1-flash.png"); // #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("HerpADerpOld.png"); // #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("ShipExplosion1.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion2.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion3.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion4.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion5.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion6.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion7.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
}
| public void loadImages() {
PImage img;
img = loadImage("bullet.png");//#0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("playerbullet.png");// #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("coin.png");// #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("RocketE.png");// #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("Turret.png");// #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("GunUpgrade.png");// #5
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("bomb.png"); // #6
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("MainMenu.png");// #7
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("PsychedelicPowerUp1.png");// #8
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedPics.add(img);
img = loadImage("spaceship.png");// #0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("Cruiser.png");// #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("Drone.png");// #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("EnemyMissileShip1.png");// #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("HerpADerp.png");// #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipPics.add(img);
img = loadImage("ShipExpolsion1.png"); // #0
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("BossBody.png"); // #1
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("Drone-hit.png"); // #2
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("EnemyMissileShip1-flash.png"); // #3
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("HerpADerpOld.png"); // #4
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipFlashPics.add(img);
img = loadImage("ShipExplosion1.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion2.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion3.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion4.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion5.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion6.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
img = loadImage("ShipExplosion7.png");
img.resize((int)((displayWidth/480.0)*img.width),(int)((displayHeight/800.0)*img.height));
loadedShipExpPics.add(img);
}
|
diff --git a/src/de/bsd/zwitscher/ThreadListActivity.java b/src/de/bsd/zwitscher/ThreadListActivity.java
index 44be384..e9259d3 100644
--- a/src/de/bsd/zwitscher/ThreadListActivity.java
+++ b/src/de/bsd/zwitscher/ThreadListActivity.java
@@ -1,64 +1,68 @@
/*
* RHQ Management Platform
* Copyright (C) 2005-2009 Red Hat, Inc.
* 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 version 2 of the License.
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package de.bsd.zwitscher;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import twitter4j.Status;
import java.util.ArrayList;
import java.util.List;
/**
* Just display a Conversation ..
*
* @author Heiko W. Rupp
*/
public class ThreadListActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Status> result = new ArrayList<Status>();
Intent i = getIntent();
Bundle b = i.getExtras();
long id = 0;
if (b!=null)
id = b.getLong("startId");
TwitterHelper th = new TwitterHelper(this);
Status status = th.getStatusById(id,null) ;
while (status!=null) {
result.add(status);
- status = th.getStatusById(status.getInReplyToStatusId(),null);
+ long inReplyToStatusId = status.getInReplyToStatusId();
+ if (inReplyToStatusId!=-1)
+ status = th.getStatusById(inReplyToStatusId,null);
+ else
+ status=null;
}
setListAdapter(new StatusAdapter<twitter4j.Status>(this, R.layout.list_item, result));
ListView lv = getListView();
lv.requestLayout();
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Status> result = new ArrayList<Status>();
Intent i = getIntent();
Bundle b = i.getExtras();
long id = 0;
if (b!=null)
id = b.getLong("startId");
TwitterHelper th = new TwitterHelper(this);
Status status = th.getStatusById(id,null) ;
while (status!=null) {
result.add(status);
status = th.getStatusById(status.getInReplyToStatusId(),null);
}
setListAdapter(new StatusAdapter<twitter4j.Status>(this, R.layout.list_item, result));
ListView lv = getListView();
lv.requestLayout();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<Status> result = new ArrayList<Status>();
Intent i = getIntent();
Bundle b = i.getExtras();
long id = 0;
if (b!=null)
id = b.getLong("startId");
TwitterHelper th = new TwitterHelper(this);
Status status = th.getStatusById(id,null) ;
while (status!=null) {
result.add(status);
long inReplyToStatusId = status.getInReplyToStatusId();
if (inReplyToStatusId!=-1)
status = th.getStatusById(inReplyToStatusId,null);
else
status=null;
}
setListAdapter(new StatusAdapter<twitter4j.Status>(this, R.layout.list_item, result));
ListView lv = getListView();
lv.requestLayout();
}
|
diff --git a/src/com/djdch/bukkit/onehundredgenerator/mc100/WorldGenSwampTree.java b/src/com/djdch/bukkit/onehundredgenerator/mc100/WorldGenSwampTree.java
index 35ea807..f1d07df 100644
--- a/src/com/djdch/bukkit/onehundredgenerator/mc100/WorldGenSwampTree.java
+++ b/src/com/djdch/bukkit/onehundredgenerator/mc100/WorldGenSwampTree.java
@@ -1,110 +1,112 @@
package com.djdch.bukkit.onehundredgenerator.mc100;
import java.util.Random;
import net.minecraft.server.Block;
import net.minecraft.server.Material;
import net.minecraft.server.World;
public class WorldGenSwampTree extends WorldGenerator {
@Override
public boolean a(World paramWorld, Random paramRandom, int paramInt1, int paramInt2, int paramInt3) {
int i = paramRandom.nextInt(4) + 5;
while (paramWorld.getMaterial(paramInt1, paramInt2 - 1, paramInt3) == Material.WATER) {
paramInt2--;
}
int j = 1;
if ((paramInt2 < 1) || (paramInt2 + i + 1 > paramWorld.height))
return false;
int n;
int i1;
int i2;
- for (int k = paramInt2; k <= paramInt2 + 1 + i; k++) {
+ int k;
+ int m;
+ for (k = paramInt2; k <= paramInt2 + 1 + i; k++) {
m = 1;
if (k == paramInt2)
m = 0;
if (k >= paramInt2 + 1 + i - 2)
m = 3;
for (n = paramInt1 - m; (n <= paramInt1 + m) && (j != 0); n++) {
for (i1 = paramInt3 - m; (i1 <= paramInt3 + m) && (j != 0); i1++) {
if ((k >= 0) && (k < paramWorld.height)) {
i2 = paramWorld.getTypeId(n, k, i1);
if ((i2 != 0) && (i2 != Block.LEAVES.id))
if ((i2 == Block.STATIONARY_WATER.id) || (i2 == Block.WATER.id)) {
if (k > paramInt2)
j = 0;
} else
j = 0;
} else {
j = 0;
}
}
}
}
if (j == 0)
return false;
k = paramWorld.getTypeId(paramInt1, paramInt2 - 1, paramInt3);
if (((k != Block.GRASS.id) && (k != Block.DIRT.id)) || (paramInt2 >= paramWorld.height - i - 1))
return false;
paramWorld.setRawTypeId(paramInt1, paramInt2 - 1, paramInt3, Block.DIRT.id);
int i3;
- for (int m = paramInt2 - 3 + i; m <= paramInt2 + i; m++) {
+ for (m = paramInt2 - 3 + i; m <= paramInt2 + i; m++) {
n = m - (paramInt2 + i);
i1 = 2 - n / 2;
for (i2 = paramInt1 - i1; i2 <= paramInt1 + i1; i2++) {
i3 = i2 - paramInt1;
for (int i4 = paramInt3 - i1; i4 <= paramInt3 + i1; i4++) {
int i5 = i4 - paramInt3;
- if (((Math.abs(i3) != i1) || (Math.abs(i5) != i1) || ((paramRandom.nextInt(2) != 0) && (n != 0))) && (Block.o[paramWorld.getTypeId(i2, m, i4)] == 0))
+ if (((Math.abs(i3) != i1) || (Math.abs(i5) != i1) || ((paramRandom.nextInt(2) != 0) && (n != 0))) && (Block.o[paramWorld.getTypeId(i2, m, i4)] == false))
paramWorld.setRawTypeId(i2, m, i4, Block.LEAVES.id);
}
}
}
for (m = 0; m < i; m++) {
n = paramWorld.getTypeId(paramInt1, paramInt2 + m, paramInt3);
if ((n != 0) && (n != Block.LEAVES.id) && (n != Block.WATER.id) && (n != Block.STATIONARY_WATER.id))
continue;
paramWorld.setRawTypeId(paramInt1, paramInt2 + m, paramInt3, Block.LOG.id);
}
for (m = paramInt2 - 3 + i; m <= paramInt2 + i; m++) {
n = m - (paramInt2 + i);
i1 = 2 - n / 2;
for (i2 = paramInt1 - i1; i2 <= paramInt1 + i1; i2++) {
for (i3 = paramInt3 - i1; i3 <= paramInt3 + i1; i3++) {
if (paramWorld.getTypeId(i2, m, i3) == Block.LEAVES.id) {
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2 - 1, m, i3) == 0)) {
a(paramWorld, i2 - 1, m, i3, 8);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2 + 1, m, i3) == 0)) {
a(paramWorld, i2 + 1, m, i3, 2);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2, m, i3 - 1) == 0)) {
a(paramWorld, i2, m, i3 - 1, 1);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2, m, i3 + 1) == 0)) {
a(paramWorld, i2, m, i3 + 1, 4);
}
}
}
}
}
return true;
}
private void a(World paramWorld, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
paramWorld.setTypeIdAndData(paramInt1, paramInt2, paramInt3, Block.VINE.id, paramInt4);
int i = 4;
while (true) {
paramInt2--;
if ((paramWorld.getTypeId(paramInt1, paramInt2, paramInt3) != 0) || (i <= 0))
break;
paramWorld.setTypeIdAndData(paramInt1, paramInt2, paramInt3, Block.VINE.id, paramInt4);
i--;
}
}
}
| false | true | public boolean a(World paramWorld, Random paramRandom, int paramInt1, int paramInt2, int paramInt3) {
int i = paramRandom.nextInt(4) + 5;
while (paramWorld.getMaterial(paramInt1, paramInt2 - 1, paramInt3) == Material.WATER) {
paramInt2--;
}
int j = 1;
if ((paramInt2 < 1) || (paramInt2 + i + 1 > paramWorld.height))
return false;
int n;
int i1;
int i2;
for (int k = paramInt2; k <= paramInt2 + 1 + i; k++) {
m = 1;
if (k == paramInt2)
m = 0;
if (k >= paramInt2 + 1 + i - 2)
m = 3;
for (n = paramInt1 - m; (n <= paramInt1 + m) && (j != 0); n++) {
for (i1 = paramInt3 - m; (i1 <= paramInt3 + m) && (j != 0); i1++) {
if ((k >= 0) && (k < paramWorld.height)) {
i2 = paramWorld.getTypeId(n, k, i1);
if ((i2 != 0) && (i2 != Block.LEAVES.id))
if ((i2 == Block.STATIONARY_WATER.id) || (i2 == Block.WATER.id)) {
if (k > paramInt2)
j = 0;
} else
j = 0;
} else {
j = 0;
}
}
}
}
if (j == 0)
return false;
k = paramWorld.getTypeId(paramInt1, paramInt2 - 1, paramInt3);
if (((k != Block.GRASS.id) && (k != Block.DIRT.id)) || (paramInt2 >= paramWorld.height - i - 1))
return false;
paramWorld.setRawTypeId(paramInt1, paramInt2 - 1, paramInt3, Block.DIRT.id);
int i3;
for (int m = paramInt2 - 3 + i; m <= paramInt2 + i; m++) {
n = m - (paramInt2 + i);
i1 = 2 - n / 2;
for (i2 = paramInt1 - i1; i2 <= paramInt1 + i1; i2++) {
i3 = i2 - paramInt1;
for (int i4 = paramInt3 - i1; i4 <= paramInt3 + i1; i4++) {
int i5 = i4 - paramInt3;
if (((Math.abs(i3) != i1) || (Math.abs(i5) != i1) || ((paramRandom.nextInt(2) != 0) && (n != 0))) && (Block.o[paramWorld.getTypeId(i2, m, i4)] == 0))
paramWorld.setRawTypeId(i2, m, i4, Block.LEAVES.id);
}
}
}
for (m = 0; m < i; m++) {
n = paramWorld.getTypeId(paramInt1, paramInt2 + m, paramInt3);
if ((n != 0) && (n != Block.LEAVES.id) && (n != Block.WATER.id) && (n != Block.STATIONARY_WATER.id))
continue;
paramWorld.setRawTypeId(paramInt1, paramInt2 + m, paramInt3, Block.LOG.id);
}
for (m = paramInt2 - 3 + i; m <= paramInt2 + i; m++) {
n = m - (paramInt2 + i);
i1 = 2 - n / 2;
for (i2 = paramInt1 - i1; i2 <= paramInt1 + i1; i2++) {
for (i3 = paramInt3 - i1; i3 <= paramInt3 + i1; i3++) {
if (paramWorld.getTypeId(i2, m, i3) == Block.LEAVES.id) {
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2 - 1, m, i3) == 0)) {
a(paramWorld, i2 - 1, m, i3, 8);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2 + 1, m, i3) == 0)) {
a(paramWorld, i2 + 1, m, i3, 2);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2, m, i3 - 1) == 0)) {
a(paramWorld, i2, m, i3 - 1, 1);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2, m, i3 + 1) == 0)) {
a(paramWorld, i2, m, i3 + 1, 4);
}
}
}
}
}
return true;
}
| public boolean a(World paramWorld, Random paramRandom, int paramInt1, int paramInt2, int paramInt3) {
int i = paramRandom.nextInt(4) + 5;
while (paramWorld.getMaterial(paramInt1, paramInt2 - 1, paramInt3) == Material.WATER) {
paramInt2--;
}
int j = 1;
if ((paramInt2 < 1) || (paramInt2 + i + 1 > paramWorld.height))
return false;
int n;
int i1;
int i2;
int k;
int m;
for (k = paramInt2; k <= paramInt2 + 1 + i; k++) {
m = 1;
if (k == paramInt2)
m = 0;
if (k >= paramInt2 + 1 + i - 2)
m = 3;
for (n = paramInt1 - m; (n <= paramInt1 + m) && (j != 0); n++) {
for (i1 = paramInt3 - m; (i1 <= paramInt3 + m) && (j != 0); i1++) {
if ((k >= 0) && (k < paramWorld.height)) {
i2 = paramWorld.getTypeId(n, k, i1);
if ((i2 != 0) && (i2 != Block.LEAVES.id))
if ((i2 == Block.STATIONARY_WATER.id) || (i2 == Block.WATER.id)) {
if (k > paramInt2)
j = 0;
} else
j = 0;
} else {
j = 0;
}
}
}
}
if (j == 0)
return false;
k = paramWorld.getTypeId(paramInt1, paramInt2 - 1, paramInt3);
if (((k != Block.GRASS.id) && (k != Block.DIRT.id)) || (paramInt2 >= paramWorld.height - i - 1))
return false;
paramWorld.setRawTypeId(paramInt1, paramInt2 - 1, paramInt3, Block.DIRT.id);
int i3;
for (m = paramInt2 - 3 + i; m <= paramInt2 + i; m++) {
n = m - (paramInt2 + i);
i1 = 2 - n / 2;
for (i2 = paramInt1 - i1; i2 <= paramInt1 + i1; i2++) {
i3 = i2 - paramInt1;
for (int i4 = paramInt3 - i1; i4 <= paramInt3 + i1; i4++) {
int i5 = i4 - paramInt3;
if (((Math.abs(i3) != i1) || (Math.abs(i5) != i1) || ((paramRandom.nextInt(2) != 0) && (n != 0))) && (Block.o[paramWorld.getTypeId(i2, m, i4)] == false))
paramWorld.setRawTypeId(i2, m, i4, Block.LEAVES.id);
}
}
}
for (m = 0; m < i; m++) {
n = paramWorld.getTypeId(paramInt1, paramInt2 + m, paramInt3);
if ((n != 0) && (n != Block.LEAVES.id) && (n != Block.WATER.id) && (n != Block.STATIONARY_WATER.id))
continue;
paramWorld.setRawTypeId(paramInt1, paramInt2 + m, paramInt3, Block.LOG.id);
}
for (m = paramInt2 - 3 + i; m <= paramInt2 + i; m++) {
n = m - (paramInt2 + i);
i1 = 2 - n / 2;
for (i2 = paramInt1 - i1; i2 <= paramInt1 + i1; i2++) {
for (i3 = paramInt3 - i1; i3 <= paramInt3 + i1; i3++) {
if (paramWorld.getTypeId(i2, m, i3) == Block.LEAVES.id) {
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2 - 1, m, i3) == 0)) {
a(paramWorld, i2 - 1, m, i3, 8);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2 + 1, m, i3) == 0)) {
a(paramWorld, i2 + 1, m, i3, 2);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2, m, i3 - 1) == 0)) {
a(paramWorld, i2, m, i3 - 1, 1);
}
if ((paramRandom.nextInt(4) == 0) && (paramWorld.getTypeId(i2, m, i3 + 1) == 0)) {
a(paramWorld, i2, m, i3 + 1, 4);
}
}
}
}
}
return true;
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/rest/security/GoogleAccountsAuthenticationProvider.java b/GAE/src/org/waterforpeople/mapping/app/web/rest/security/GoogleAccountsAuthenticationProvider.java
index 2be97da63..bd9c46383 100644
--- a/GAE/src/org/waterforpeople/mapping/app/web/rest/security/GoogleAccountsAuthenticationProvider.java
+++ b/GAE/src/org/waterforpeople/mapping/app/web/rest/security/GoogleAccountsAuthenticationProvider.java
@@ -1,100 +1,104 @@
package org.waterforpeople.mapping.app.web.rest.security;
import java.util.EnumSet;
import java.util.Set;
import javax.inject.Inject;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.waterforpeople.mapping.app.web.rest.security.user.GaeUser;
import com.gallatinsystems.user.dao.UserDao;
import com.google.appengine.api.users.User;
/**
* A simple authentication provider which interacts with {@code User} returned by the GAE {@code UserService},
* and also the local persistent {@code UserRegistry} to build an application user principal.
* <p>
* If the user has been authenticated through google accounts, it will check if they are already registered
* and either load the existing user information or assign them a temporary identity with limited access until they
* have registered.
* <p>
* If the account has been disabled, a {@code DisabledException} will be raised.
*
* @author Luke Taylor
*/
public class GoogleAccountsAuthenticationProvider implements AuthenticationProvider, MessageSourceAware {
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
@Inject
UserDao userDao;
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
User googleUser = (User) authentication.getPrincipal();
GaeUser user = findUser(googleUser.getEmail());
if (user == null) {
// User not in registry. Needs to register
user = new GaeUser(googleUser.getNickname(), googleUser.getEmail());
}
if (!user.isEnabled()) {
throw new DisabledException("Account is disabled");
}
return new GaeUserAuthentication(user, authentication.getDetails());
}
private GaeUser findUser(String email) {
final com.gallatinsystems.user.domain.User user = userDao.findUserByEmail(email);
if (user == null) {
return null;
}
final int authority = getAuthorityLevel(user);
final Set<AppRole> roles = EnumSet.noneOf(AppRole.class);
- for (AppRole r : AppRole.values()) {
- if (authority >= r.getLevel()) {
- roles.add(r);
+ if (authority == AppRole.NEW_USER.getLevel()) {
+ roles.add(AppRole.NEW_USER);
+ } else {
+ for (AppRole r : AppRole.values()) {
+ if (authority <= r.getLevel()) {
+ roles.add(r);
+ }
}
}
return new GaeUser(user.getUserName(), user.getEmailAddress(), roles, true);
}
private int getAuthorityLevel(com.gallatinsystems.user.domain.User user) {
if(user.isSuperAdmin() != null && user.isSuperAdmin()) {
return AppRole.ADMIN.getLevel();
}
try {
final int level = Integer.parseInt(user.getPermissionList());
return level;
} catch (Exception e) {
//no-op
}
return AppRole.NEW_USER.getLevel();
}
/**
* Indicate that this provider only supports PreAuthenticatedAuthenticationToken (sub)classes.
*/
public final boolean supports(Class<?> authentication) {
return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication);
}
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
}
| true | true | private GaeUser findUser(String email) {
final com.gallatinsystems.user.domain.User user = userDao.findUserByEmail(email);
if (user == null) {
return null;
}
final int authority = getAuthorityLevel(user);
final Set<AppRole> roles = EnumSet.noneOf(AppRole.class);
for (AppRole r : AppRole.values()) {
if (authority >= r.getLevel()) {
roles.add(r);
}
}
return new GaeUser(user.getUserName(), user.getEmailAddress(), roles, true);
}
| private GaeUser findUser(String email) {
final com.gallatinsystems.user.domain.User user = userDao.findUserByEmail(email);
if (user == null) {
return null;
}
final int authority = getAuthorityLevel(user);
final Set<AppRole> roles = EnumSet.noneOf(AppRole.class);
if (authority == AppRole.NEW_USER.getLevel()) {
roles.add(AppRole.NEW_USER);
} else {
for (AppRole r : AppRole.values()) {
if (authority <= r.getLevel()) {
roles.add(r);
}
}
}
return new GaeUser(user.getUserName(), user.getEmailAddress(), roles, true);
}
|
diff --git a/juddi-core/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java b/juddi-core/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java
index f3cb0575c..77adf4585 100644
--- a/juddi-core/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java
+++ b/juddi-core/src/main/java/org/apache/juddi/mapping/MappingApiToModel.java
@@ -1,649 +1,649 @@
/*
* Copyright 2001-2008 The Apache Software Foundation.
*
* 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.juddi.mapping;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.apache.juddi.jaxb.JAXBMarshaller;
import org.apache.juddi.v3.error.ErrorMessage;
import org.apache.juddi.v3.error.FatalErrorException;
import org.apache.log4j.Logger;
import org.uddi.api_v3.Description;
import org.uddi.sub_v3.ObjectFactory;
import org.uddi.v3_service.DispositionReportFaultMessage;
/**
* @author <a href="mailto:[email protected]">Jeff Faath</a>
* @author <a href="mailto:[email protected]">Kurt T Stam</a>
* @author <a href="mailto:[email protected]">Tom Cunningham</a>
*/
public class MappingApiToModel {
private static Logger logger = Logger.getLogger(MappingApiToModel.class);
public static void mapPublisher(org.apache.juddi.api_v3.Publisher apiPublisher,
org.apache.juddi.model.Publisher modelPublisher)
throws DispositionReportFaultMessage {
modelPublisher.setAuthorizedName(apiPublisher.getAuthorizedName());
modelPublisher.setPublisherName(apiPublisher.getPublisherName());
modelPublisher.setEmailAddress(apiPublisher.getEmailAddress());
modelPublisher.setIsAdmin(apiPublisher.getIsAdmin());
modelPublisher.setIsEnabled(apiPublisher.getIsEnabled());
modelPublisher.setMaxBindingsPerService(apiPublisher.getMaxBindingsPerService());
modelPublisher.setMaxBusinesses(apiPublisher.getMaxBusinesses());
modelPublisher.setMaxServicesPerBusiness(apiPublisher.getMaxServicePerBusiness());
modelPublisher.setMaxTmodels(apiPublisher.getMaxTModels());
}
public static void mapBusinessEntity(org.uddi.api_v3.BusinessEntity apiBusinessEntity,
org.apache.juddi.model.BusinessEntity modelBusinessEntity)
throws DispositionReportFaultMessage {
modelBusinessEntity.setEntityKey(apiBusinessEntity.getBusinessKey());
mapBusinessNames(apiBusinessEntity.getName(), modelBusinessEntity.getBusinessNames(), modelBusinessEntity);
mapBusinessDescriptions(apiBusinessEntity.getDescription(), modelBusinessEntity.getBusinessDescrs(), modelBusinessEntity);
mapDiscoveryUrls(apiBusinessEntity.getDiscoveryURLs(), modelBusinessEntity.getDiscoveryUrls(), modelBusinessEntity);
mapContacts(apiBusinessEntity.getContacts(), modelBusinessEntity.getContacts(), modelBusinessEntity);
mapBusinessIdentifiers(apiBusinessEntity.getIdentifierBag(), modelBusinessEntity.getBusinessIdentifiers(), modelBusinessEntity);
if (apiBusinessEntity.getCategoryBag()!=null) {
modelBusinessEntity.setCategoryBag(new org.apache.juddi.model.BusinessCategoryBag(modelBusinessEntity));
mapCategoryBag(apiBusinessEntity.getCategoryBag(), modelBusinessEntity.getCategoryBag());
}
mapBusinessServices(apiBusinessEntity.getBusinessServices(),
modelBusinessEntity.getBusinessServices(),
modelBusinessEntity.getServiceProjections(),
modelBusinessEntity);
}
public static void mapBusinessNames(List<org.uddi.api_v3.Name> apiNameList,
List<org.apache.juddi.model.BusinessName> modelNameList,
org.apache.juddi.model.BusinessEntity modelBusinessEntity)
throws DispositionReportFaultMessage {
modelNameList.clear();
for (org.uddi.api_v3.Name apiName : apiNameList) {
modelNameList.add(new org.apache.juddi.model.BusinessName(modelBusinessEntity, apiName.getLang(), apiName.getValue()));
}
}
public static void mapBusinessDescriptions(List<org.uddi.api_v3.Description> apiDescList,
List<org.apache.juddi.model.BusinessDescr> modelDescList,
org.apache.juddi.model.BusinessEntity modelBusinessEntity)
throws DispositionReportFaultMessage {
modelDescList.clear();
for (org.uddi.api_v3.Description apiDesc : apiDescList) {
modelDescList.add(new org.apache.juddi.model.BusinessDescr(modelBusinessEntity, apiDesc.getLang(), apiDesc.getValue()));
}
}
public static void mapDiscoveryUrls(org.uddi.api_v3.DiscoveryURLs apiDiscUrls,
List<org.apache.juddi.model.DiscoveryUrl> modelDiscUrlList,
org.apache.juddi.model.BusinessEntity modelBusinessEntity)
throws DispositionReportFaultMessage {
modelDiscUrlList.clear();
if (apiDiscUrls != null) {
List<org.uddi.api_v3.DiscoveryURL> apiDiscUrlList = apiDiscUrls.getDiscoveryURL();
for (org.uddi.api_v3.DiscoveryURL apiDiscUrl : apiDiscUrlList) {
modelDiscUrlList.add(new org.apache.juddi.model.DiscoveryUrl(modelBusinessEntity, apiDiscUrl.getUseType(), apiDiscUrl.getValue()));
}
}
}
public static void mapContacts(org.uddi.api_v3.Contacts apiContacts,
List<org.apache.juddi.model.Contact> modelContactList,
org.apache.juddi.model.BusinessEntity modelBusinessEntity)
throws DispositionReportFaultMessage {
modelContactList.clear();
if (apiContacts != null) {
List<org.uddi.api_v3.Contact> apiContactList = apiContacts.getContact();
for (org.uddi.api_v3.Contact apiContact : apiContactList) {
org.apache.juddi.model.Contact modelContact = new org.apache.juddi.model.Contact(modelBusinessEntity);
modelContact.setUseType(apiContact.getUseType());
mapPersonNames(apiContact.getPersonName(), modelContact.getPersonNames(), modelContact, modelBusinessEntity.getEntityKey());
mapContactDescriptions(apiContact.getDescription(), modelContact.getContactDescrs(), modelContact, modelBusinessEntity.getEntityKey());
mapContactEmails(apiContact.getEmail(), modelContact.getEmails(), modelContact, modelBusinessEntity.getEntityKey());
mapContactPhones(apiContact.getPhone(), modelContact.getPhones(), modelContact, modelBusinessEntity.getEntityKey());
mapContactAddresses(apiContact.getAddress(), modelContact.getAddresses(), modelContact, modelBusinessEntity.getEntityKey());
modelContactList.add(modelContact);
}
}
}
public static void mapContactDescriptions(List<org.uddi.api_v3.Description> apiDescList,
List<org.apache.juddi.model.ContactDescr> modelDescList,
org.apache.juddi.model.Contact modelContact,
String businessKey)
throws DispositionReportFaultMessage {
modelDescList.clear();
for (org.uddi.api_v3.Description apiDesc : apiDescList) {
modelDescList.add(new org.apache.juddi.model.ContactDescr(modelContact, apiDesc.getLang(), apiDesc.getValue()));
}
}
public static void mapPersonNames(List<org.uddi.api_v3.PersonName> apiPersonNameList,
List<org.apache.juddi.model.PersonName> modelPersonNameList,
org.apache.juddi.model.Contact modelContact,
String businessKey)
throws DispositionReportFaultMessage {
modelPersonNameList.clear();
for (org.uddi.api_v3.PersonName apiPersonName : apiPersonNameList) {
modelPersonNameList.add(new org.apache.juddi.model.PersonName(modelContact, apiPersonName.getLang(), apiPersonName.getValue()));
}
}
public static void mapContactEmails(List<org.uddi.api_v3.Email> apiEmailList,
List<org.apache.juddi.model.Email> modelEmailList,
org.apache.juddi.model.Contact modelContact,
String businessKey)
throws DispositionReportFaultMessage {
modelEmailList.clear();
for (org.uddi.api_v3.Email apiEmail : apiEmailList) {
modelEmailList.add(new org.apache.juddi.model.Email(modelContact, apiEmail.getUseType(), apiEmail.getValue()));
}
}
public static void mapContactPhones(List<org.uddi.api_v3.Phone> apiPhoneList,
List<org.apache.juddi.model.Phone> modelPhoneList,
org.apache.juddi.model.Contact modelContact,
String businessKey)
throws DispositionReportFaultMessage {
modelPhoneList.clear();
for (org.uddi.api_v3.Phone apiPhone : apiPhoneList) {
modelPhoneList.add(new org.apache.juddi.model.Phone(modelContact, apiPhone.getUseType(), apiPhone.getValue()));
}
}
public static void mapContactAddresses(List<org.uddi.api_v3.Address> apiAddressList,
List<org.apache.juddi.model.Address> modelAddressList,
org.apache.juddi.model.Contact modelContact,
String businessKey)
throws DispositionReportFaultMessage {
modelAddressList.clear();
for (org.uddi.api_v3.Address apiAddress : apiAddressList) {
org.apache.juddi.model.Address modelAddress = new org.apache.juddi.model.Address(modelContact);
modelAddress.setSortCode(apiAddress.getSortCode());
modelAddress.setTmodelKey(apiAddress.getTModelKey());
modelAddress.setUseType(apiAddress.getUseType());
mapAddressLines(apiAddress.getAddressLine(), modelAddress.getAddressLines(), modelAddress, businessKey, modelContact.getId());
modelAddressList.add(modelAddress);
}
}
public static void mapAddressLines(List<org.uddi.api_v3.AddressLine> apiAddressLineList,
List<org.apache.juddi.model.AddressLine> modelAddressLineList,
org.apache.juddi.model.Address modelAddress,
String businessKey,
Long contactId)
throws DispositionReportFaultMessage {
modelAddressLineList.clear();
for (org.uddi.api_v3.AddressLine apiAddressLine : apiAddressLineList) {
modelAddressLineList.add(new org.apache.juddi.model.AddressLine(modelAddress, apiAddressLine.getValue(), apiAddressLine.getKeyName(), apiAddressLine.getKeyValue()));
}
}
public static void mapBusinessIdentifiers(org.uddi.api_v3.IdentifierBag apiIdentifierBag,
List<org.apache.juddi.model.BusinessIdentifier> modelIdentifierList,
org.apache.juddi.model.BusinessEntity modelBusinessEntity)
throws DispositionReportFaultMessage {
modelIdentifierList.clear();
if (apiIdentifierBag != null) {
List<org.uddi.api_v3.KeyedReference> apiKeyedRefList = apiIdentifierBag.getKeyedReference();
for (org.uddi.api_v3.KeyedReference apiKeyedRef : apiKeyedRefList) {
modelIdentifierList.add(new org.apache.juddi.model.BusinessIdentifier(modelBusinessEntity, apiKeyedRef.getTModelKey(), apiKeyedRef.getKeyName(), apiKeyedRef.getKeyValue()));
}
}
}
public static void mapBusinessServices(org.uddi.api_v3.BusinessServices apiBusinessServices,
List<org.apache.juddi.model.BusinessService> modelBusinessServiceList,
List<org.apache.juddi.model.ServiceProjection> modelServiceProjectionList,
org.apache.juddi.model.BusinessEntity modelBusinessEntity)
throws DispositionReportFaultMessage {
modelBusinessServiceList.clear();
if (apiBusinessServices != null) {
List<org.uddi.api_v3.BusinessService> apiBusinessServiceList = apiBusinessServices.getBusinessService();
for (org.uddi.api_v3.BusinessService apiBusinessService : apiBusinessServiceList) {
org.apache.juddi.model.BusinessService modelBusinessService = new org.apache.juddi.model.BusinessService();
// If the parent businessEntity key and the service businessEntity key (if provided) do not match, it's a projection.
if (apiBusinessService.getBusinessKey() != null && apiBusinessService.getBusinessKey().length() > 0 &&
!modelBusinessEntity.getEntityKey().equalsIgnoreCase(apiBusinessService.getBusinessKey())) {
modelBusinessService.setEntityKey(apiBusinessService.getServiceKey());
org.apache.juddi.model.ServiceProjection modelServiceProjection = new org.apache.juddi.model.ServiceProjection(modelBusinessEntity, modelBusinessService);
modelServiceProjectionList.add(modelServiceProjection);
}
else {
mapBusinessService(apiBusinessService, modelBusinessService, modelBusinessEntity);
modelBusinessServiceList.add(modelBusinessService);
}
}
}
}
public static void mapBusinessService(org.uddi.api_v3.BusinessService apiBusinessService,
org.apache.juddi.model.BusinessService modelBusinessService,
org.apache.juddi.model.BusinessEntity modelBusinessEntity)
throws DispositionReportFaultMessage {
modelBusinessService.setBusinessEntity(modelBusinessEntity);
modelBusinessService.setEntityKey(apiBusinessService.getServiceKey());
mapServiceNames(apiBusinessService.getName(), modelBusinessService.getServiceNames(), modelBusinessService);
mapServiceDescriptions(apiBusinessService.getDescription(), modelBusinessService.getServiceDescrs(), modelBusinessService);
if (apiBusinessService.getCategoryBag()!=null) {
modelBusinessService.setCategoryBag(new org.apache.juddi.model.ServiceCategoryBag(modelBusinessService));
mapCategoryBag(apiBusinessService.getCategoryBag(), modelBusinessService.getCategoryBag());
}
mapBindingTemplates(apiBusinessService.getBindingTemplates(), modelBusinessService.getBindingTemplates(), modelBusinessService);
}
public static void mapServiceNames(List<org.uddi.api_v3.Name> apiNameList,
List<org.apache.juddi.model.ServiceName> modelNameList,
org.apache.juddi.model.BusinessService modelBusinessService)
throws DispositionReportFaultMessage {
modelNameList.clear();
for (org.uddi.api_v3.Name apiName : apiNameList) {
modelNameList.add(new org.apache.juddi.model.ServiceName(modelBusinessService, apiName.getLang(), apiName.getValue()));
}
}
public static void mapServiceDescriptions(List<org.uddi.api_v3.Description> apiDescList,
List<org.apache.juddi.model.ServiceDescr> modelDescList,
org.apache.juddi.model.BusinessService modelBusinessService)
throws DispositionReportFaultMessage {
modelDescList.clear();
for (org.uddi.api_v3.Description apiDesc : apiDescList) {
modelDescList.add(new org.apache.juddi.model.ServiceDescr(modelBusinessService, apiDesc.getLang(), apiDesc.getValue()));
}
}
public static void mapBindingTemplates(org.uddi.api_v3.BindingTemplates apiBindingTemplates,
List<org.apache.juddi.model.BindingTemplate> modelBindingTemplateList,
org.apache.juddi.model.BusinessService modelBusinessService)
throws DispositionReportFaultMessage {
modelBindingTemplateList.clear();
if (apiBindingTemplates != null) {
List<org.uddi.api_v3.BindingTemplate> apiBindingTemplateList = apiBindingTemplates.getBindingTemplate();
for (org.uddi.api_v3.BindingTemplate apiBindingTemplate : apiBindingTemplateList) {
org.apache.juddi.model.BindingTemplate modelBindingTemplate = new org.apache.juddi.model.BindingTemplate();
mapBindingTemplate(apiBindingTemplate, modelBindingTemplate, modelBusinessService);
modelBindingTemplateList.add(modelBindingTemplate);
}
}
}
public static void mapBindingTemplate(org.uddi.api_v3.BindingTemplate apiBindingTemplate,
org.apache.juddi.model.BindingTemplate modelBindingTemplate,
org.apache.juddi.model.BusinessService modelBusinessService)
throws DispositionReportFaultMessage {
modelBindingTemplate.setBusinessService(modelBusinessService);
modelBindingTemplate.setEntityKey(apiBindingTemplate.getBindingKey());
modelBindingTemplate.setAccessPointType(apiBindingTemplate.getAccessPoint().getUseType());
modelBindingTemplate.setAccessPointUrl(apiBindingTemplate.getAccessPoint().getValue());
if (apiBindingTemplate.getHostingRedirector() != null) {
modelBindingTemplate.setHostingRedirector(apiBindingTemplate.getHostingRedirector().getBindingKey());
}
mapBindingDescriptions(apiBindingTemplate.getDescription(), modelBindingTemplate.getBindingDescrs(), modelBindingTemplate);
if (apiBindingTemplate.getCategoryBag()!=null) {
modelBindingTemplate.setCategoryBag(new org.apache.juddi.model.BindingCategoryBag(modelBindingTemplate));
mapCategoryBag(apiBindingTemplate.getCategoryBag(), modelBindingTemplate.getCategoryBag());
}
mapTModelInstanceDetails(apiBindingTemplate.getTModelInstanceDetails(), modelBindingTemplate.getTmodelInstanceInfos(), modelBindingTemplate);
}
public static void mapBindingDescriptions(List<org.uddi.api_v3.Description> apiDescList,
List<org.apache.juddi.model.BindingDescr> modelDescList,
org.apache.juddi.model.BindingTemplate modelBindingTemplate)
throws DispositionReportFaultMessage {
modelDescList.clear();
for (org.uddi.api_v3.Description apiDesc : apiDescList) {
modelDescList.add(new org.apache.juddi.model.BindingDescr(modelBindingTemplate, apiDesc.getLang(), apiDesc.getValue()));
}
}
public static void mapCategoryBag(org.uddi.api_v3.CategoryBag apiCategoryBag,
org.apache.juddi.model.CategoryBag modelCategoryBag)
throws DispositionReportFaultMessage {
if (apiCategoryBag != null) {
List<org.uddi.api_v3.KeyedReference> krList = apiCategoryBag.getKeyedReference();
for (Object elem : krList) {
if (elem instanceof org.uddi.api_v3.KeyedReference) {
List<org.apache.juddi.model.KeyedReference> modelKeyedReferences=modelCategoryBag.getKeyedReferences();
//modelKeyedReferences.clear();
org.uddi.api_v3.KeyedReference apiKeyedReference = (org.uddi.api_v3.KeyedReference)elem;
modelKeyedReferences.add(new org.apache.juddi.model.KeyedReference(modelCategoryBag,
apiKeyedReference.getTModelKey(), apiKeyedReference.getKeyName(), apiKeyedReference.getKeyValue()));
}
}
List<org.uddi.api_v3.KeyedReferenceGroup> krgList = apiCategoryBag.getKeyedReferenceGroup();
for (org.uddi.api_v3.KeyedReferenceGroup elem : krgList) {
if (elem instanceof org.uddi.api_v3.KeyedReferenceGroup) {
org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup = (org.uddi.api_v3.KeyedReferenceGroup) elem;
org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup = new org.apache.juddi.model.KeyedReferenceGroup();
List<org.apache.juddi.model.KeyedReferenceGroup> modelKeyedReferenceGroups=modelCategoryBag.getKeyedReferenceGroups();
//modelKeyedReferenceGroups.clear();
mapKeyedReferenceGroup(apiKeyedReferenceGroup, modelKeyedReferenceGroup, modelCategoryBag);
modelKeyedReferenceGroups.add(modelKeyedReferenceGroup);
}
}
}
}
public static void mapKeyedReferenceGroup(org.uddi.api_v3.KeyedReferenceGroup apiKeyedReferenceGroup,
org.apache.juddi.model.KeyedReferenceGroup modelKeyedReferenceGroup,
org.apache.juddi.model.CategoryBag modelCategoryBag)
throws DispositionReportFaultMessage {
if (apiKeyedReferenceGroup != null) {
modelKeyedReferenceGroup.setCategoryBag(modelCategoryBag);
modelKeyedReferenceGroup.setTmodelKey(apiKeyedReferenceGroup.getTModelKey());
if (apiKeyedReferenceGroup.getKeyedReference() != null) {
List<org.apache.juddi.model.KeyedReference> modelKeyedReferences = modelKeyedReferenceGroup.getKeyedReferences();
for (org.uddi.api_v3.KeyedReference apiKeyedReference : apiKeyedReferenceGroup.getKeyedReference()) {
modelKeyedReferences.add(new org.apache.juddi.model.KeyedReference(modelKeyedReferenceGroup,
apiKeyedReference.getTModelKey(), apiKeyedReference.getKeyName(), apiKeyedReference.getKeyValue()));
}
}
}
}
public static void mapTModelInstanceDetails(org.uddi.api_v3.TModelInstanceDetails apiTModelInstDetails,
List<org.apache.juddi.model.TmodelInstanceInfo> modelTModelInstInfoList,
org.apache.juddi.model.BindingTemplate modelBindingTemplate)
throws DispositionReportFaultMessage {
modelTModelInstInfoList.clear();
if (apiTModelInstDetails != null) {
List<org.uddi.api_v3.TModelInstanceInfo> apiTModelInstInfoList = apiTModelInstDetails.getTModelInstanceInfo();
for (org.uddi.api_v3.TModelInstanceInfo apiTModelInstInfo : apiTModelInstInfoList) {
org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo = new org.apache.juddi.model.TmodelInstanceInfo(modelBindingTemplate, apiTModelInstInfo.getTModelKey());
mapTModelInstanceInfoDescriptions(apiTModelInstInfo.getDescription(), modelTModelInstInfo.getTmodelInstanceInfoDescrs(), modelTModelInstInfo);
mapInstanceDetails(apiTModelInstInfo.getInstanceDetails(), modelTModelInstInfo);
modelTModelInstInfoList.add(modelTModelInstInfo);
}
}
}
public static void mapTModelInstanceInfoDescriptions(List<org.uddi.api_v3.Description> apiDescList,
List<org.apache.juddi.model.TmodelInstanceInfoDescr> modelDescList,
org.apache.juddi.model.TmodelInstanceInfo modelTModelInstInfo)
throws DispositionReportFaultMessage {
modelDescList.clear();
for (org.uddi.api_v3.Description apiDesc : apiDescList) {
modelDescList.add(new org.apache.juddi.model.TmodelInstanceInfoDescr(modelTModelInstInfo, apiDesc.getLang(), apiDesc.getValue()));
}
}
public static void mapInstanceDetails(org.uddi.api_v3.InstanceDetails apiInstanceDetails,
org.apache.juddi.model.TmodelInstanceInfo modelTmodelInstInfo)
throws DispositionReportFaultMessage {
modelTmodelInstInfo.getInstanceDetailsDescrs().clear();
if (apiInstanceDetails != null) {
List<org.uddi.api_v3.Description> descriptions = apiInstanceDetails.getDescription();
List<org.uddi.api_v3.OverviewDoc> overviewdocs = apiInstanceDetails.getOverviewDoc();
for (org.uddi.api_v3.Description apiDesc : descriptions) {
org.apache.juddi.model.InstanceDetailsDescr modelInstanceDetailsDescr =
new org.apache.juddi.model.InstanceDetailsDescr(
modelTmodelInstInfo, apiDesc.getLang(), apiDesc.getValue());
modelTmodelInstInfo.getInstanceDetailsDescrs().add(modelInstanceDetailsDescr);
}
for (org.uddi.api_v3.OverviewDoc apiOverviewDoc : overviewdocs) {
org.apache.juddi.model.OverviewDoc modelOverviewDoc = new org.apache.juddi.model.OverviewDoc(modelTmodelInstInfo);
mapOverviewDoc(apiOverviewDoc, modelOverviewDoc);
modelTmodelInstInfo.getOverviewDocs().add(modelOverviewDoc);
}
modelTmodelInstInfo.setInstanceParms((String)apiInstanceDetails.getInstanceParms());
}
}
public static void mapOverviewDoc(org.uddi.api_v3.OverviewDoc apiOverviewDoc,
org.apache.juddi.model.OverviewDoc modelOverviewDoc)
throws DispositionReportFaultMessage {
if (apiOverviewDoc != null) {
List<Description> descContent = apiOverviewDoc.getDescription();
for (Object elem : descContent) {
org.uddi.api_v3.Description description = (org.uddi.api_v3.Description) elem;
if (description != null) {
org.apache.juddi.model.OverviewDocDescr modelOverviewDocDescr
= new org.apache.juddi.model.OverviewDocDescr(
modelOverviewDoc, description.getLang(), description.getValue());
modelOverviewDoc.getOverviewDocDescrs().add(modelOverviewDocDescr);
}
}
org.uddi.api_v3.OverviewURL elem = apiOverviewDoc.getOverviewURL();
if (elem instanceof org.uddi.api_v3.OverviewURL) {
org.uddi.api_v3.OverviewURL overviewURL = (org.uddi.api_v3.OverviewURL) elem;
modelOverviewDoc.setOverviewUrl(overviewURL.getValue());
modelOverviewDoc.setOverviewUrlUseType(overviewURL.getUseType());
}
}
}
public static void mapTModel(org.uddi.api_v3.TModel apiTModel,
org.apache.juddi.model.Tmodel modelTModel)
throws DispositionReportFaultMessage {
modelTModel.setEntityKey(apiTModel.getTModelKey());
modelTModel.setName(apiTModel.getName().getValue());
modelTModel.setDeleted(apiTModel.isDeleted());
mapTModelDescriptions(apiTModel.getDescription(), modelTModel.getTmodelDescrs(), modelTModel);
mapTModelIdentifiers(apiTModel.getIdentifierBag(), modelTModel.getTmodelIdentifiers(), modelTModel);
if (apiTModel.getCategoryBag()!=null) {
modelTModel.setCategoryBag(new org.apache.juddi.model.TmodelCategoryBag(modelTModel));
mapCategoryBag(apiTModel.getCategoryBag(), modelTModel.getCategoryBag());
}
mapTModelOverviewDocs(apiTModel.getOverviewDoc(), modelTModel.getOverviewDocs(), modelTModel);
}
public static void mapTModelDescriptions(List<org.uddi.api_v3.Description> apiDescList,
List<org.apache.juddi.model.TmodelDescr> modelDescList,
org.apache.juddi.model.Tmodel modelTModel)
throws DispositionReportFaultMessage {
modelDescList.clear();
for (org.uddi.api_v3.Description apiDesc : apiDescList) {
modelDescList.add(new org.apache.juddi.model.TmodelDescr(modelTModel, apiDesc.getLang(), apiDesc.getValue()));
}
}
public static void mapTModelIdentifiers(org.uddi.api_v3.IdentifierBag apiIdentifierBag,
List<org.apache.juddi.model.TmodelIdentifier> modelIdentifierList,
org.apache.juddi.model.Tmodel modelTModel)
throws DispositionReportFaultMessage {
modelIdentifierList.clear();
if (apiIdentifierBag != null) {
List<org.uddi.api_v3.KeyedReference> apiKeyedRefList = apiIdentifierBag.getKeyedReference();
for (org.uddi.api_v3.KeyedReference apiKeyedRef : apiKeyedRefList) {
modelIdentifierList.add(new org.apache.juddi.model.TmodelIdentifier(modelTModel, apiKeyedRef.getTModelKey(), apiKeyedRef.getKeyName(), apiKeyedRef.getKeyValue()));
}
}
}
public static void mapTModelOverviewDocs(List<org.uddi.api_v3.OverviewDoc> apiOverviewDocList,
List<org.apache.juddi.model.OverviewDoc> modelOverviewDocList,
org.apache.juddi.model.Tmodel modelTmodel)
throws DispositionReportFaultMessage {
modelOverviewDocList.clear();
for (org.uddi.api_v3.OverviewDoc apiOverviewDoc : apiOverviewDocList) {
org.apache.juddi.model.OverviewDoc modelOverviewDoc = new org.apache.juddi.model.OverviewDoc(modelTmodel);
mapOverviewDoc(apiOverviewDoc, modelOverviewDoc);
modelTmodel.getOverviewDocs().add(modelOverviewDoc);
}
}
public static void mapPublisherAssertion(org.uddi.api_v3.PublisherAssertion apiPubAssertion,
org.apache.juddi.model.PublisherAssertion modelPubAssertion)
throws DispositionReportFaultMessage {
modelPubAssertion.setId(new org.apache.juddi.model.PublisherAssertionId(apiPubAssertion.getFromKey(), apiPubAssertion.getToKey()));
org.apache.juddi.model.BusinessEntity beFrom = new org.apache.juddi.model.BusinessEntity();
beFrom.setEntityKey(apiPubAssertion.getFromKey());
modelPubAssertion.setBusinessEntityByFromKey(beFrom);
org.apache.juddi.model.BusinessEntity beTo = new org.apache.juddi.model.BusinessEntity();
beFrom.setEntityKey(apiPubAssertion.getToKey());
modelPubAssertion.setBusinessEntityByToKey(beTo);
org.uddi.api_v3.KeyedReference apiKeyedRef = apiPubAssertion.getKeyedReference();
if (apiKeyedRef != null) {
modelPubAssertion.setTmodelKey(apiKeyedRef.getTModelKey());
modelPubAssertion.setKeyName(apiKeyedRef.getKeyName());
modelPubAssertion.setKeyValue(apiKeyedRef.getKeyValue());
}
}
public static void mapSubscription(org.uddi.sub_v3.Subscription apiSubscription,
org.apache.juddi.model.Subscription modelSubscription)
throws DispositionReportFaultMessage {
modelSubscription.setSubscriptionKey(apiSubscription.getSubscriptionKey());
modelSubscription.setBindingKey(apiSubscription.getBindingKey());
if (apiSubscription.getNotificationInterval()!=null) {
modelSubscription.setNotificationInterval(apiSubscription.getNotificationInterval().toString());
}
modelSubscription.setMaxEntities(apiSubscription.getMaxEntities());
if (apiSubscription.getExpiresAfter() != null) {
GregorianCalendar gc = apiSubscription.getExpiresAfter().toGregorianCalendar();
modelSubscription.setExpiresAfter(new Date(gc.getTimeInMillis()));
}
- if (modelSubscription.isBrief() != null) {
+ if (apiSubscription.isBrief() != null) {
modelSubscription.setBrief(apiSubscription.isBrief());
} else {
modelSubscription.setBrief(new Boolean(false));
}
try {
String rawFilter = JAXBMarshaller.marshallToString(new ObjectFactory().createSubscriptionFilter(apiSubscription.getSubscriptionFilter()), "org.uddi.sub_v3");
logger.debug("marshalled subscription filter: " + rawFilter);
modelSubscription.setSubscriptionFilter(rawFilter);
} catch (JAXBException e) {
logger.error("JAXBException while marshalling subscription filter", e);
throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
}
}
public static void mapClientSubscriptionInfo(org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo,
org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo)
throws DispositionReportFaultMessage {
modelClientSubscriptionInfo.setLastNotified(new Date());
modelClientSubscriptionInfo.setSubscriptionKey(apiClientSubscriptionInfo.getSubscriptionKey());
if (apiClientSubscriptionInfo.getFromClerk()!=null) {
org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk();
mapClerk(apiClientSubscriptionInfo.getFromClerk(), modelClerk);
modelClientSubscriptionInfo.setFromClerk(modelClerk);
}
if (apiClientSubscriptionInfo.getToClerk()!=null) {
org.apache.juddi.model.Clerk modelToClerk = new org.apache.juddi.model.Clerk();
mapClerk(apiClientSubscriptionInfo.getToClerk(), modelToClerk);
modelClientSubscriptionInfo.setToClerk(modelToClerk);
}
}
public static void mapClerk(org.apache.juddi.api_v3.Clerk apiClerk,org.apache.juddi.model.Clerk modelClerk) {
if (apiClerk!=null) {
modelClerk.setClerkName(apiClerk.getName());
modelClerk.setCred(apiClerk.getPassword());
modelClerk.setPublisherId(apiClerk.getPublisher());
if (apiClerk.getNode()!=null) {
org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node();
mapNode(apiClerk.getNode(), modelNode);
modelClerk.setNode(modelNode);
}
}
}
public static void mapNode(org.apache.juddi.api_v3.Node apiNode,org.apache.juddi.model.Node modelNode) {
if (apiNode!=null) {
modelNode.setCustodyTransferUrl(apiNode.getCustodyTransferUrl());
modelNode.setInquiryUrl(apiNode.getInquiryUrl());
modelNode.setJuddiApiUrl(apiNode.getJuddiApiUrl());
modelNode.setName(apiNode.getName());
modelNode.setManagerName(apiNode.getManagerName());
modelNode.setProxyTransport(apiNode.getProxyTransport());
modelNode.setPublishUrl(apiNode.getPublishUrl());
modelNode.setSecurityUrl(apiNode.getSecurityUrl());
modelNode.setSubscriptionUrl(apiNode.getSubscriptionUrl());
modelNode.setFactoryInitial(apiNode.getFactoryInitial());
modelNode.setFactoryNamingProvider(apiNode.getFactoryNamingProvider());
modelNode.setFactoryURLPkgs(apiNode.getFactoryURLPkgs());
}
}
}
| true | true | public static void mapSubscription(org.uddi.sub_v3.Subscription apiSubscription,
org.apache.juddi.model.Subscription modelSubscription)
throws DispositionReportFaultMessage {
modelSubscription.setSubscriptionKey(apiSubscription.getSubscriptionKey());
modelSubscription.setBindingKey(apiSubscription.getBindingKey());
if (apiSubscription.getNotificationInterval()!=null) {
modelSubscription.setNotificationInterval(apiSubscription.getNotificationInterval().toString());
}
modelSubscription.setMaxEntities(apiSubscription.getMaxEntities());
if (apiSubscription.getExpiresAfter() != null) {
GregorianCalendar gc = apiSubscription.getExpiresAfter().toGregorianCalendar();
modelSubscription.setExpiresAfter(new Date(gc.getTimeInMillis()));
}
if (modelSubscription.isBrief() != null) {
modelSubscription.setBrief(apiSubscription.isBrief());
} else {
modelSubscription.setBrief(new Boolean(false));
}
try {
String rawFilter = JAXBMarshaller.marshallToString(new ObjectFactory().createSubscriptionFilter(apiSubscription.getSubscriptionFilter()), "org.uddi.sub_v3");
logger.debug("marshalled subscription filter: " + rawFilter);
modelSubscription.setSubscriptionFilter(rawFilter);
} catch (JAXBException e) {
logger.error("JAXBException while marshalling subscription filter", e);
throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
}
}
| public static void mapSubscription(org.uddi.sub_v3.Subscription apiSubscription,
org.apache.juddi.model.Subscription modelSubscription)
throws DispositionReportFaultMessage {
modelSubscription.setSubscriptionKey(apiSubscription.getSubscriptionKey());
modelSubscription.setBindingKey(apiSubscription.getBindingKey());
if (apiSubscription.getNotificationInterval()!=null) {
modelSubscription.setNotificationInterval(apiSubscription.getNotificationInterval().toString());
}
modelSubscription.setMaxEntities(apiSubscription.getMaxEntities());
if (apiSubscription.getExpiresAfter() != null) {
GregorianCalendar gc = apiSubscription.getExpiresAfter().toGregorianCalendar();
modelSubscription.setExpiresAfter(new Date(gc.getTimeInMillis()));
}
if (apiSubscription.isBrief() != null) {
modelSubscription.setBrief(apiSubscription.isBrief());
} else {
modelSubscription.setBrief(new Boolean(false));
}
try {
String rawFilter = JAXBMarshaller.marshallToString(new ObjectFactory().createSubscriptionFilter(apiSubscription.getSubscriptionFilter()), "org.uddi.sub_v3");
logger.debug("marshalled subscription filter: " + rawFilter);
modelSubscription.setSubscriptionFilter(rawFilter);
} catch (JAXBException e) {
logger.error("JAXBException while marshalling subscription filter", e);
throw new FatalErrorException(new ErrorMessage("errors.Unspecified"));
}
}
|
diff --git a/src/com/fsck/k9/activity/MessageCompose.java b/src/com/fsck/k9/activity/MessageCompose.java
index 6542c42..fbb668e 100644
--- a/src/com/fsck/k9/activity/MessageCompose.java
+++ b/src/com/fsck/k9/activity/MessageCompose.java
@@ -1,2301 +1,2301 @@
package com.fsck.k9.activity;
import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import org.apache.james.mime4j.codec.EncoderUtil;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.provider.OpenableColumns;
import android.text.TextWatcher;
import android.text.util.Rfc822Tokenizer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.AutoCompleteTextView.Validator;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.EmailAddressAdapter;
import com.fsck.k9.EmailAddressValidator;
import com.fsck.k9.Identity;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.controller.MessagingListener;
import com.fsck.k9.crypto.CryptoProvider;
import com.fsck.k9.crypto.PgpData;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Multipart;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.internet.MimeBodyPart;
import com.fsck.k9.mail.internet.MimeHeader;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeMultipart;
import com.fsck.k9.mail.internet.MimeUtility;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalAttachmentBody;
public class MessageCompose extends K9Activity implements OnClickListener, OnFocusChangeListener
{
private static final int DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE = 1;
private static final int REPLY_WRAP_LINE_WIDTH = 72;
private static final String ACTION_REPLY = "com.fsck.k9.intent.action.REPLY";
private static final String ACTION_REPLY_ALL = "com.fsck.k9.intent.action.REPLY_ALL";
private static final String ACTION_FORWARD = "com.fsck.k9.intent.action.FORWARD";
private static final String ACTION_EDIT_DRAFT = "com.fsck.k9.intent.action.EDIT_DRAFT";
private static final String EXTRA_ACCOUNT = "account";
private static final String EXTRA_MESSAGE_BODY = "messageBody";
private static final String EXTRA_MESSAGE_REFERENCE = "message_reference";
private static final String STATE_KEY_ATTACHMENTS =
"com.fsck.k9.activity.MessageCompose.attachments";
private static final String STATE_KEY_CC_SHOWN =
"com.fsck.k9.activity.MessageCompose.ccShown";
private static final String STATE_KEY_BCC_SHOWN =
"com.fsck.k9.activity.MessageCompose.bccShown";
private static final String STATE_KEY_QUOTED_TEXT_SHOWN =
"com.fsck.k9.activity.MessageCompose.quotedTextShown";
private static final String STATE_KEY_SOURCE_MESSAGE_PROCED =
"com.fsck.k9.activity.MessageCompose.stateKeySourceMessageProced";
private static final String STATE_KEY_DRAFT_UID =
"com.fsck.k9.activity.MessageCompose.draftUid";
private static final String STATE_IDENTITY_CHANGED =
"com.fsck.k9.activity.MessageCompose.identityChanged";
private static final String STATE_IDENTITY =
"com.fsck.k9.activity.MessageCompose.identity";
private static final String STATE_PGP_DATA = "pgpData";
private static final String STATE_IN_REPLY_TO = "com.fsck.k9.activity.MessageCompose.inReplyTo";
private static final String STATE_REFERENCES = "com.fsck.k9.activity.MessageCompose.references";
private static final int MSG_PROGRESS_ON = 1;
private static final int MSG_PROGRESS_OFF = 2;
private static final int MSG_UPDATE_TITLE = 3;
private static final int MSG_SKIPPED_ATTACHMENTS = 4;
private static final int MSG_SAVED_DRAFT = 5;
private static final int MSG_DISCARDED_DRAFT = 6;
private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1;
private static final int ACTIVITY_CHOOSE_IDENTITY = 2;
private static final int ACTIVITY_CHOOSE_ACCOUNT = 3;
/**
* Regular expression to remove the first localized "Re:" prefix in subjects.
*
* Currently:
* - "Aw:" (german: abbreviation for "Antwort")
*/
private static final Pattern prefix = Pattern.compile("^AW[:\\s]\\s*", Pattern.CASE_INSENSITIVE);
/**
* The account used for message composition.
*/
private Account mAccount;
/**
* This identity's settings are used for message composition.
* Note: This has to be an identity of the account {@link #mAccount}.
*/
private Identity mIdentity;
private boolean mIdentityChanged = false;
private boolean mSignatureChanged = false;
/**
* Reference to the source message (in case of reply, forward, or edit
* draft actions).
*/
private MessageReference mMessageReference;
private Message mSourceMessage;
private String mSourceMessageBody;
/**
* Indicates that the source message has been processed at least once and should not
* be processed on any subsequent loads. This protects us from adding attachments that
* have already been added from the restore of the view state.
*/
private boolean mSourceMessageProcessed = false;
private TextView mFromView;
private MultiAutoCompleteTextView mToView;
private MultiAutoCompleteTextView mCcView;
private MultiAutoCompleteTextView mBccView;
private EditText mSubjectView;
private EditText mSignatureView;
private EditText mMessageContentView;
private LinearLayout mAttachments;
private View mQuotedTextBar;
private ImageButton mQuotedTextDelete;
private EditText mQuotedText;
private View mEncryptLayout;
private CheckBox mCryptoSignatureCheckbox;
private CheckBox mEncryptCheckbox;
private TextView mCryptoSignatureUserId;
private TextView mCryptoSignatureUserIdRest;
private PgpData mPgpData = null;
private String mReferences;
private String mInReplyTo;
private boolean mDraftNeedsSaving = false;
private boolean mPreventDraftSaving = false;
/**
* The draft uid of this message. This is used when saving drafts so that the same draft is
* overwritten instead of being created anew. This property is null until the first save.
*/
private String mDraftUid;
private Handler mHandler = new Handler()
{
@Override
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case MSG_PROGRESS_ON:
setProgressBarIndeterminateVisibility(true);
break;
case MSG_PROGRESS_OFF:
setProgressBarIndeterminateVisibility(false);
break;
case MSG_UPDATE_TITLE:
updateTitle();
break;
case MSG_SKIPPED_ATTACHMENTS:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_compose_attachments_skipped_toast),
Toast.LENGTH_LONG).show();
break;
case MSG_SAVED_DRAFT:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_saved_toast),
Toast.LENGTH_LONG).show();
break;
case MSG_DISCARDED_DRAFT:
Toast.makeText(
MessageCompose.this,
getString(R.string.message_discarded_toast),
Toast.LENGTH_LONG).show();
break;
default:
super.handleMessage(msg);
break;
}
}
};
private Listener mListener = new Listener();
private EmailAddressAdapter mAddressAdapter;
private Validator mAddressValidator;
class Attachment implements Serializable
{
public String name;
public String contentType;
public long size;
public Uri uri;
}
/**
* Compose a new message using the given account. If account is null the default account
* will be used.
* @param context
* @param account
*/
public static void actionCompose(Context context, Account account)
{
if (account == null)
{
account = Preferences.getPreferences(context).getDefaultAccount();
}
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_ACCOUNT, account.getUuid());
context.startActivity(i);
}
/**
* Compose a new message as a reply to the given message. If replyAll is true the function
* is reply all instead of simply reply.
* @param context
* @param account
* @param message
* @param replyAll
* @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message
*/
public static void actionReply(
Context context,
Account account,
Message message,
boolean replyAll,
String messageBody)
{
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_BODY, messageBody);
i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference());
if (replyAll)
{
i.setAction(ACTION_REPLY_ALL);
}
else
{
i.setAction(ACTION_REPLY);
}
context.startActivity(i);
}
/**
* Compose a new message as a forward of the given message.
* @param context
* @param account
* @param message
* @param messageBody optional, for decrypted messages, null if it should be grabbed from the given message
*/
public static void actionForward(
Context context,
Account account,
Message message,
String messageBody)
{
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_BODY, messageBody);
i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference());
i.setAction(ACTION_FORWARD);
context.startActivity(i);
}
/**
* Continue composition of the given message. This action modifies the way this Activity
* handles certain actions.
* Save will attempt to replace the message in the given folder with the updated version.
* Discard will delete the message from the given folder.
* @param context
* @param account
* @param folder
* @param message
*/
public static void actionEditDraft(Context context, Account account, Message message)
{
Intent i = new Intent(context, MessageCompose.class);
i.putExtra(EXTRA_MESSAGE_REFERENCE, message.makeMessageReference());
i.setAction(ACTION_EDIT_DRAFT);
context.startActivity(i);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.message_compose);
final Intent intent = getIntent();
mMessageReference = (MessageReference) intent.getSerializableExtra(EXTRA_MESSAGE_REFERENCE);
mSourceMessageBody = (String) intent.getStringExtra(EXTRA_MESSAGE_BODY);
final String accountUuid = (mMessageReference != null) ?
mMessageReference.accountUuid :
intent.getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
if (mAccount == null)
{
mAccount = Preferences.getPreferences(this).getDefaultAccount();
}
if (mAccount == null)
{
/*
* There are no accounts set up. This should not have happened. Prompt the
* user to set up an account as an acceptable bailout.
*/
startActivity(new Intent(this, Accounts.class));
mDraftNeedsSaving = false;
finish();
return;
}
mAddressAdapter = EmailAddressAdapter.getInstance(this);
mAddressValidator = new EmailAddressValidator();
mFromView = (TextView)findViewById(R.id.from);
mToView = (MultiAutoCompleteTextView)findViewById(R.id.to);
mCcView = (MultiAutoCompleteTextView)findViewById(R.id.cc);
mBccView = (MultiAutoCompleteTextView)findViewById(R.id.bcc);
mSubjectView = (EditText)findViewById(R.id.subject);
EditText upperSignature = (EditText)findViewById(R.id.upper_signature);
EditText lowerSignature = (EditText)findViewById(R.id.lower_signature);
mMessageContentView = (EditText)findViewById(R.id.message_content);
mAttachments = (LinearLayout)findViewById(R.id.attachments);
mQuotedTextBar = findViewById(R.id.quoted_text_bar);
mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete);
mQuotedText = (EditText)findViewById(R.id.quoted_text);
TextWatcher watcher = new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start,
int before, int after) { }
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
mDraftNeedsSaving = true;
}
public void afterTextChanged(android.text.Editable s) { }
};
TextWatcher sigwatcher = new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start,
int before, int after) { }
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
mDraftNeedsSaving = true;
mSignatureChanged = true;
}
public void afterTextChanged(android.text.Editable s) { }
};
mToView.addTextChangedListener(watcher);
mCcView.addTextChangedListener(watcher);
mBccView.addTextChangedListener(watcher);
mSubjectView.addTextChangedListener(watcher);
mMessageContentView.addTextChangedListener(watcher);
mQuotedText.addTextChangedListener(watcher);
/*
* We set this to invisible by default. Other methods will turn it back on if it's
* needed.
*/
mQuotedTextBar.setVisibility(View.GONE);
mQuotedText.setVisibility(View.GONE);
mQuotedTextDelete.setOnClickListener(this);
mFromView.setVisibility(View.GONE);
mToView.setAdapter(mAddressAdapter);
mToView.setTokenizer(new Rfc822Tokenizer());
mToView.setValidator(mAddressValidator);
mCcView.setAdapter(mAddressAdapter);
mCcView.setTokenizer(new Rfc822Tokenizer());
mCcView.setValidator(mAddressValidator);
mBccView.setAdapter(mAddressAdapter);
mBccView.setTokenizer(new Rfc822Tokenizer());
mBccView.setValidator(mAddressValidator);
mSubjectView.setOnFocusChangeListener(this);
if (savedInstanceState != null)
{
/*
* This data gets used in onCreate, so grab it here instead of onRestoreIntstanceState
*/
mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false);
}
String action = intent.getAction();
- if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action))
+ if (Intent.ACTION_VIEW.equals(action))
{
/*
* Someone has clicked a mailto: link. The address is in the URI.
*/
if (intent.getData() != null)
{
Uri uri = intent.getData();
if ("mailto".equals(uri.getScheme()))
{
initializeFromMailTo(uri.toString());
}
else
{
String toText = uri.getSchemeSpecificPart();
if (toText != null)
{
mToView.setText(toText);
}
}
}
}
//TODO: Use constant Intent.ACTION_SEND_MULTIPLE once we drop Android 1.5 support
else if (Intent.ACTION_SEND.equals(action)
|| Intent.ACTION_SENDTO.equals(action)
|| "android.intent.action.SEND_MULTIPLE".equals(action))
{
/*
* Someone is trying to compose an email with an attachment, probably Pictures.
* The Intent should contain an EXTRA_STREAM with the data to attach.
*/
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
if (text != null)
{
mMessageContentView.setText(text);
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
if (subject != null)
{
mSubjectView.setText(subject);
}
String type = intent.getType();
//TODO: Use constant Intent.ACTION_SEND_MULTIPLE once we drop Android 1.5 support
if ("android.intent.action.SEND_MULTIPLE".equals(action))
{
ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (list != null)
{
for (Parcelable parcelable : list)
{
Uri stream = (Uri) parcelable;
if (stream != null && type != null)
{
if (MimeUtility.mimeTypeMatches(type, K9.ACCEPTABLE_ATTACHMENT_SEND_TYPES))
{
addAttachment(stream);
}
}
}
}
}
else
{
Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (stream != null && type != null)
{
if (MimeUtility.mimeTypeMatches(type, K9.ACCEPTABLE_ATTACHMENT_SEND_TYPES))
{
addAttachment(stream);
}
}
}
/*
* There might be an EXTRA_SUBJECT, EXTRA_TEXT, EXTRA_EMAIL, EXTRA_BCC or EXTRA_CC
*/
String extraSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
String extraText = intent.getStringExtra(Intent.EXTRA_TEXT);
mSubjectView.setText(extraSubject);
mMessageContentView.setText(extraText);
String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC);
String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC);
String addressList;
// Cache array size, as per Google's recommendations.
int arraySize;
int i;
addressList = "";
if (extraEmail != null)
{
arraySize = extraEmail.length;
for (i=0; i < arraySize; i++)
{
addressList += extraEmail[i]+", ";
}
}
mToView.setText(addressList);
addressList = "";
if (extraCc != null)
{
arraySize = extraCc.length;
for (i=0; i < arraySize; i++)
{
addressList += extraCc[i]+", ";
}
}
mCcView.setText(addressList);
addressList = "";
if (extraBcc != null)
{
arraySize = extraBcc.length;
for (i=0; i < arraySize; i++)
{
addressList += extraBcc[i]+", ";
}
}
mBccView.setText(addressList);
}
if (mIdentity == null)
{
mIdentity = mAccount.getIdentity(0);
}
if (mAccount.isSignatureBeforeQuotedText())
{
mSignatureView = upperSignature;
lowerSignature.setVisibility(View.GONE);
}
else
{
mSignatureView = lowerSignature;
upperSignature.setVisibility(View.GONE);
}
mSignatureView.addTextChangedListener(sigwatcher);
if (!mIdentity.getSignatureUse())
{
mSignatureView.setVisibility(View.GONE);
}
if (!mSourceMessageProcessed)
{
updateFrom();
updateSignature();
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action) ||
ACTION_FORWARD.equals(action) ||
ACTION_EDIT_DRAFT.equals(action))
{
/*
* If we need to load the message we add ourself as a message listener here
* so we can kick it off. Normally we add in onResume but we don't
* want to reload the message every time the activity is resumed.
* There is no harm in adding twice.
*/
MessagingController.getInstance(getApplication()).addListener(mListener);
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null);
}
if (!ACTION_EDIT_DRAFT.equals(action))
{
String bccAddress = mAccount.getAlwaysBcc();
if ((bccAddress != null) && !("".equals(bccAddress)))
{
addAddress(mBccView, new Address(bccAddress, ""));
}
}
/*
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "action = " + action + ", account = " + mMessageReference.accountUuid + ", folder = " + mMessageReference.folderName + ", sourceMessageUid = " + mMessageReference.uid);
*/
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Setting message ANSWERED flag to true");
// TODO: Really, we should wait until we send the message, but that would require saving the original
// message info along with a Draft copy, in case it is left in Drafts for a while before being sent
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).setFlag(account, folderName, new String[] { sourceMessageUid }, Flag.ANSWERED, true);
}
updateTitle();
}
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action) ||
ACTION_EDIT_DRAFT.equals(action))
{
//change focus to message body.
mMessageContentView.requestFocus();
}
mEncryptLayout = (View)findViewById(R.id.layout_encrypt);
mCryptoSignatureCheckbox = (CheckBox)findViewById(R.id.cb_crypto_signature);
mCryptoSignatureUserId = (TextView)findViewById(R.id.userId);
mCryptoSignatureUserIdRest = (TextView)findViewById(R.id.userIdRest);
mEncryptCheckbox = (CheckBox)findViewById(R.id.cb_encrypt);
initializeCrypto();
final CryptoProvider crypto = mAccount.getCryptoProvider();
if (crypto.isAvailable(this))
{
mEncryptLayout.setVisibility(View.VISIBLE);
mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked())
{
mPreventDraftSaving = true;
if (!crypto.selectSecretKey(MessageCompose.this, mPgpData))
{
mPreventDraftSaving = false;
}
checkBox.setChecked(false);
}
else
{
mPgpData.setSignatureKeyId(0);
updateEncryptLayout();
}
}
});
if (mAccount.getCryptoAutoSignature())
{
long ids[] = crypto.getSecretKeyIdsFromEmail(this, mIdentity.getEmail());
if (ids != null && ids.length > 0)
{
mPgpData.setSignatureKeyId(ids[0]);
mPgpData.setSignatureUserId(crypto.getUserId(this, ids[0]));
}
else
{
mPgpData.setSignatureKeyId(0);
mPgpData.setSignatureUserId(null);
}
}
updateEncryptLayout();
}
else
{
mEncryptLayout.setVisibility(View.GONE);
}
mDraftNeedsSaving = false;
}
private void initializeCrypto()
{
if (mPgpData != null)
{
return;
}
mPgpData = new PgpData();
}
/**
* Fill the encrypt layout with the latest data about signature key and encryption keys.
*/
public void updateEncryptLayout()
{
if (!mPgpData.hasSignatureKey())
{
mCryptoSignatureCheckbox.setText(R.string.btn_crypto_sign);
mCryptoSignatureCheckbox.setChecked(false);
mCryptoSignatureUserId.setVisibility(View.INVISIBLE);
mCryptoSignatureUserIdRest.setVisibility(View.INVISIBLE);
}
else
{
// if a signature key is selected, then the checkbox itself has no text
mCryptoSignatureCheckbox.setText("");
mCryptoSignatureCheckbox.setChecked(true);
mCryptoSignatureUserId.setVisibility(View.VISIBLE);
mCryptoSignatureUserIdRest.setVisibility(View.VISIBLE);
mCryptoSignatureUserId.setText(R.string.unknown_crypto_signature_user_id);
mCryptoSignatureUserIdRest.setText("");
String userId = mPgpData.getSignatureUserId();
if (userId == null)
{
userId = mAccount.getCryptoProvider().getUserId(this, mPgpData.getSignatureKeyId());
mPgpData.setSignatureUserId(userId);
}
if (userId != null)
{
String chunks[] = mPgpData.getSignatureUserId().split(" <", 2);
mCryptoSignatureUserId.setText(chunks[0]);
if (chunks.length > 1)
{
mCryptoSignatureUserIdRest.setText("<" + chunks[1]);
}
}
}
}
@Override
public void onResume()
{
super.onResume();
MessagingController.getInstance(getApplication()).addListener(mListener);
}
@Override
public void onPause()
{
super.onPause();
saveIfNeeded();
MessagingController.getInstance(getApplication()).removeListener(mListener);
}
/**
* The framework handles most of the fields, but we need to handle stuff that we
* dynamically show and hide:
* Attachment list,
* Cc field,
* Bcc field,
* Quoted text,
*/
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
saveIfNeeded();
ArrayList<Uri> attachments = new ArrayList<Uri>();
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++)
{
View view = mAttachments.getChildAt(i);
Attachment attachment = (Attachment) view.getTag();
attachments.add(attachment.uri);
}
outState.putParcelableArrayList(STATE_KEY_ATTACHMENTS, attachments);
outState.putBoolean(STATE_KEY_CC_SHOWN, mCcView.getVisibility() == View.VISIBLE);
outState.putBoolean(STATE_KEY_BCC_SHOWN, mBccView.getVisibility() == View.VISIBLE);
outState.putBoolean(STATE_KEY_QUOTED_TEXT_SHOWN, mQuotedTextBar.getVisibility() == View.VISIBLE);
outState.putBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, mSourceMessageProcessed);
outState.putString(STATE_KEY_DRAFT_UID, mDraftUid);
outState.putSerializable(STATE_IDENTITY, mIdentity);
outState.putBoolean(STATE_IDENTITY_CHANGED, mIdentityChanged);
outState.putSerializable(STATE_PGP_DATA, mPgpData);
outState.putString(STATE_IN_REPLY_TO, mInReplyTo);
outState.putString(STATE_REFERENCES, mReferences);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
ArrayList<Parcelable> attachments = (ArrayList<Parcelable>) savedInstanceState.getParcelableArrayList(STATE_KEY_ATTACHMENTS);
mAttachments.removeAllViews();
for (Parcelable p : attachments)
{
Uri uri = (Uri) p;
addAttachment(uri);
}
mCcView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN) ? View.VISIBLE : View.GONE);
mBccView.setVisibility(savedInstanceState.getBoolean(STATE_KEY_BCC_SHOWN) ? View.VISIBLE : View.GONE);
mQuotedTextBar.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? View.VISIBLE : View.GONE);
mQuotedText.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? View.VISIBLE : View.GONE);
mDraftUid = savedInstanceState.getString(STATE_KEY_DRAFT_UID);
mIdentity = (Identity)savedInstanceState.getSerializable(STATE_IDENTITY);
mIdentityChanged = savedInstanceState.getBoolean(STATE_IDENTITY_CHANGED);
mPgpData = (PgpData) savedInstanceState.getSerializable(STATE_PGP_DATA);
mInReplyTo = savedInstanceState.getString(STATE_IN_REPLY_TO);
mReferences = savedInstanceState.getString(STATE_REFERENCES);
initializeCrypto();
updateFrom();
updateSignature();
updateEncryptLayout();
mDraftNeedsSaving = false;
}
private void updateTitle()
{
if (mSubjectView.getText().length() == 0)
{
setTitle(R.string.compose_title);
}
else
{
setTitle(mSubjectView.getText().toString());
}
}
public void onFocusChange(View view, boolean focused)
{
if (!focused)
{
updateTitle();
}
}
private void addAddresses(MultiAutoCompleteTextView view, Address[] addresses)
{
if (addresses == null)
{
return;
}
for (Address address : addresses)
{
addAddress(view, address);
}
}
private void addAddress(MultiAutoCompleteTextView view, Address address)
{
view.append(address + ", ");
}
private Address[] getAddresses(MultiAutoCompleteTextView view)
{
Address[] addresses = Address.parseUnencoded(view.getText().toString().trim());
return addresses;
}
/*
* Build the Body that will contain the text of the message. We'll decide where to
* include it later.
*
* @param appendSig If true, append the user's signature to the message.
*/
private String buildText(boolean appendSig)
{
boolean replyAfterQuote = false;
String action = getIntent().getAction();
if (mAccount.isReplyAfterQuote() &&
(ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action)))
{
replyAfterQuote = true;
}
String text = mMessageContentView.getText().toString();
// Placing the signature before the quoted text does not make sense if replyAfterQuote is true.
if (!replyAfterQuote && appendSig && mAccount.isSignatureBeforeQuotedText())
{
text = appendSignature(text);
}
if (mQuotedTextBar.getVisibility() == View.VISIBLE)
{
if (replyAfterQuote)
{
text = mQuotedText.getText().toString() + "\n" + text;
}
else
{
text += "\n\n" + mQuotedText.getText().toString();
}
}
// Note: If user has selected reply after quote AND signature before quote, ignore the
// latter setting and append the signature at the end.
if (appendSig && (!mAccount.isSignatureBeforeQuotedText() || replyAfterQuote))
{
text = appendSignature(text);
}
return text;
}
private MimeMessage createMessage(boolean appendSig) throws MessagingException
{
MimeMessage message = new MimeMessage();
message.addSentDate(new Date());
Address from = new Address(mIdentity.getEmail(), mIdentity.getName());
message.setFrom(from);
message.setRecipients(RecipientType.TO, getAddresses(mToView));
message.setRecipients(RecipientType.CC, getAddresses(mCcView));
message.setRecipients(RecipientType.BCC, getAddresses(mBccView));
message.setSubject(mSubjectView.getText().toString());
message.setHeader("X-User-Agent", getString(R.string.message_header_mua));
final String replyTo = mIdentity.getReplyTo();
if (replyTo != null)
{
message.setReplyTo(new Address[] { new Address(replyTo) });
}
if (mInReplyTo != null)
{
message.setInReplyTo(mInReplyTo);
}
if (mReferences != null)
{
message.setReferences(mReferences);
}
String text = null;
if (mPgpData.getEncryptedData() != null)
{
text = mPgpData.getEncryptedData();
}
else
{
text = buildText(appendSig);
}
TextBody body = new TextBody(text);
if (mAttachments.getChildCount() > 0)
{
/*
* The message has attachments that need to be included. First we add the part
* containing the text that will be sent and then we include each attachment.
*/
MimeMultipart mp;
mp = new MimeMultipart();
mp.addBodyPart(new MimeBodyPart(body, "text/plain"));
for (int i = 0, count = mAttachments.getChildCount(); i < count; i++)
{
Attachment attachment = (Attachment) mAttachments.getChildAt(i).getTag();
MimeBodyPart bp = new MimeBodyPart(
new LocalStore.LocalAttachmentBody(attachment.uri, getApplication()));
/*
* Correctly encode the filename here. Otherwise the whole
* header value (all parameters at once) will be encoded by
* MimeHeader.writeTo().
*/
bp.addHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n name=\"%s\"",
attachment.contentType,
EncoderUtil.encodeIfNecessary(attachment.name,
EncoderUtil.Usage.WORD_ENTITY, 7)));
bp.addHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
/*
* TODO: Oh the joys of MIME...
*
* From RFC 2183 (The Content-Disposition Header Field):
* "Parameter values longer than 78 characters, or which
* contain non-ASCII characters, MUST be encoded as specified
* in [RFC 2184]."
*
* Example:
*
* Content-Type: application/x-stuff
* title*1*=us-ascii'en'This%20is%20even%20more%20
* title*2*=%2A%2A%2Afun%2A%2A%2A%20
* title*3="isn't it!"
*/
bp.addHeader(MimeHeader.HEADER_CONTENT_DISPOSITION, String.format(
"attachment;\n filename=\"%s\";\n size=%d",
attachment.name, attachment.size));
mp.addBodyPart(bp);
}
message.setBody(mp);
}
else
{
/*
* No attachments to include, just stick the text body in the message and call
* it good.
*/
message.setBody(body);
}
return message;
}
private String appendSignature(String text)
{
if (mIdentity.getSignatureUse())
{
String signature = mSignatureView.getText().toString();
if (signature != null && !signature.contentEquals(""))
{
text += "\n" + signature;
}
}
return text;
}
private void sendMessage()
{
new SendMessageTask().execute();
}
private void saveMessage()
{
new SaveMessageTask().execute();
}
private void saveIfNeeded()
{
if (!mDraftNeedsSaving || mPreventDraftSaving || mPgpData.hasEncryptionKeys())
{
return;
}
mDraftNeedsSaving = false;
saveMessage();
}
public void onEncryptionKeySelectionDone()
{
if (mPgpData.hasEncryptionKeys())
{
onSend();
}
else
{
Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show();
}
}
public void onEncryptDone()
{
if (mPgpData.getEncryptedData() != null)
{
onSend();
}
else
{
Toast.makeText(this, R.string.send_aborted, Toast.LENGTH_SHORT).show();
}
}
private void onSend()
{
if (getAddresses(mToView).length == 0 && getAddresses(mCcView).length == 0 && getAddresses(mBccView).length == 0)
{
mToView.setError(getString(R.string.message_compose_error_no_recipients));
Toast.makeText(this, getString(R.string.message_compose_error_no_recipients), Toast.LENGTH_LONG).show();
return;
}
if (mEncryptCheckbox.isChecked() && !mPgpData.hasEncryptionKeys())
{
// key selection before encryption
String emails = "";
Address[][] addresses = new Address[][] { getAddresses(mToView),
getAddresses(mCcView),
getAddresses(mBccView)
};
for (Address[] addressArray : addresses)
{
for (Address address : addressArray)
{
if (emails.length() != 0)
{
emails += ",";
}
emails += address.getAddress();
}
}
if (emails.length() != 0)
{
emails += ",";
}
emails += mIdentity.getEmail();
mPreventDraftSaving = true;
if (!mAccount.getCryptoProvider().selectEncryptionKeys(MessageCompose.this, emails, mPgpData))
{
mPreventDraftSaving = false;
}
return;
}
if (mPgpData.hasEncryptionKeys() || mPgpData.hasSignatureKey())
{
if (mPgpData.getEncryptedData() == null)
{
String text = buildText(true);
mPreventDraftSaving = true;
if (!mAccount.getCryptoProvider().encrypt(this, text, mPgpData))
{
mPreventDraftSaving = false;
}
return;
}
}
sendMessage();
mDraftNeedsSaving = false;
finish();
}
private void onDiscard()
{
if (mDraftUid != null)
{
MessagingController.getInstance(getApplication()).deleteDraft(mAccount, mDraftUid);
mDraftUid = null;
}
mHandler.sendEmptyMessage(MSG_DISCARDED_DRAFT);
mDraftNeedsSaving = false;
finish();
}
private void onSave()
{
mDraftNeedsSaving = true;
saveIfNeeded();
finish();
}
private void onAddCcBcc()
{
mCcView.setVisibility(View.VISIBLE);
mBccView.setVisibility(View.VISIBLE);
}
/**
* Kick off a picker for whatever kind of MIME types we'll accept and let Android take over.
*/
private void onAddAttachment()
{
if (K9.isGalleryBuggy())
{
if (K9.useGalleryBugWorkaround())
{
Toast.makeText(MessageCompose.this,
getString(R.string.message_compose_use_workaround),
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MessageCompose.this,
getString(R.string.message_compose_buggy_gallery),
Toast.LENGTH_LONG).show();
}
}
onAddAttachment2(K9.ACCEPTABLE_ATTACHMENT_SEND_TYPES[0]);
}
/**
* Kick off a picker for the specified MIME type and let Android take over.
*/
private void onAddAttachment2(final String mime_type)
{
if (mAccount.getCryptoProvider().isAvailable(this))
{
Toast.makeText(this, R.string.attachment_encryption_unsupported, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(mime_type);
startActivityForResult(Intent.createChooser(i, null), ACTIVITY_REQUEST_PICK_ATTACHMENT);
}
private void addAttachment(Uri uri)
{
addAttachment(uri, -1, null);
}
private void addAttachment(Uri uri, int size, String name)
{
ContentResolver contentResolver = getContentResolver();
Attachment attachment = new Attachment();
attachment.name = name;
attachment.size = size;
attachment.uri = uri;
if (attachment.size == -1 || attachment.name == null)
{
Cursor metadataCursor = contentResolver.query(uri, new String[] { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }, null, null, null);
if (metadataCursor != null)
{
try
{
if (metadataCursor.moveToFirst())
{
if (attachment.name == null)
{
attachment.name = metadataCursor.getString(0);
}
if (attachment.size == -1)
{
attachment.size = metadataCursor.getInt(1);
Log.v(K9.LOG_TAG, "size: " + attachment.size);
}
}
}
finally
{
metadataCursor.close();
}
}
}
if (attachment.name == null)
{
attachment.name = uri.getLastPathSegment();
}
String contentType = contentResolver.getType(uri);
if (contentType == null)
{
contentType = MimeUtility.getMimeTypeByExtension(attachment.name);
}
attachment.contentType = contentType;
if (attachment.size<=0)
{
String uriString = uri.toString();
if (uriString.startsWith("file://"))
{
Log.v(K9.LOG_TAG, uriString.substring("file://".length()));
File f = new File(uriString.substring("file://".length()));
attachment.size = f.length();
}
else
{
Log.v(K9.LOG_TAG, "Not a file: " + uriString);
}
}
else
{
Log.v(K9.LOG_TAG, "old attachment.size: " + attachment.size);
}
Log.v(K9.LOG_TAG, "new attachment.size: " + attachment.size);
View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, mAttachments, false);
TextView nameView = (TextView)view.findViewById(R.id.attachment_name);
ImageButton delete = (ImageButton)view.findViewById(R.id.attachment_delete);
nameView.setText(attachment.name);
delete.setOnClickListener(this);
delete.setTag(view);
view.setTag(attachment);
mAttachments.addView(view);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// if a CryptoSystem activity is returning, then mPreventDraftSaving was set to true
mPreventDraftSaving = false;
if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData))
{
return;
}
if (resultCode != RESULT_OK)
return;
if (data == null)
{
return;
}
switch (requestCode)
{
case ACTIVITY_REQUEST_PICK_ATTACHMENT:
addAttachment(data.getData());
mDraftNeedsSaving = true;
break;
case ACTIVITY_CHOOSE_IDENTITY:
onIdentityChosen(data);
break;
case ACTIVITY_CHOOSE_ACCOUNT:
onAccountChosen(data);
break;
}
}
private void onAccountChosen(final Intent intent)
{
final Bundle extras = intent.getExtras();
final String uuid = extras.getString(ChooseAccount.EXTRA_ACCOUNT);
final Identity identity = (Identity) extras.getSerializable(ChooseAccount.EXTRA_IDENTITY);
final Account account = Preferences.getPreferences(this).getAccount(uuid);
if (!mAccount.equals(account))
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Switching account from " + mAccount + " to " + account);
}
// on draft edit, make sure we don't keep previous message UID
if (ACTION_EDIT_DRAFT.equals(getIntent().getAction()))
{
mMessageReference = null;
}
// test whether there is something to save
if (mDraftNeedsSaving || (mDraftUid != null))
{
final String previousDraftUid = mDraftUid;
final Account previousAccount = mAccount;
// make current message appear as new
mDraftUid = null;
// actual account switch
mAccount = account;
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Account switch, saving new draft in new account");
}
saveMessage();
if (previousDraftUid != null)
{
if (K9.DEBUG)
{
Log.v(K9.LOG_TAG, "Account switch, deleting draft from previous account: "
+ previousDraftUid);
}
MessagingController.getInstance(getApplication()).deleteDraft(previousAccount,
previousDraftUid);
}
}
else
{
mAccount = account;
}
// not sure how to handle mFolder, mSourceMessage?
}
switchToIdentity(identity);
}
private void onIdentityChosen(Intent intent)
{
Bundle bundle = intent.getExtras();;
switchToIdentity((Identity)bundle.getSerializable(ChooseIdentity.EXTRA_IDENTITY));
}
private void switchToIdentity(Identity identity)
{
mIdentity = identity;
mIdentityChanged = true;
mDraftNeedsSaving = true;
updateFrom();
updateSignature();
}
private void updateFrom()
{
if (mIdentityChanged)
{
mFromView.setVisibility(View.VISIBLE);
}
mFromView.setText(getString(R.string.message_view_from_format, mIdentity.getName(), mIdentity.getEmail()));
}
private void updateSignature()
{
if (mIdentity.getSignatureUse())
{
mSignatureView.setText(mIdentity.getSignature());
mSignatureView.setVisibility(View.VISIBLE);
}
else
{
mSignatureView.setVisibility(View.GONE);
}
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.attachment_delete:
/*
* The view is the delete button, and we have previously set the tag of
* the delete button to the view that owns it. We don't use parent because the
* view is very complex and could change in the future.
*/
mAttachments.removeView((View) view.getTag());
mDraftNeedsSaving = true;
break;
case R.id.quoted_text_delete:
mQuotedTextBar.setVisibility(View.GONE);
mQuotedText.setVisibility(View.GONE);
mDraftNeedsSaving = true;
break;
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.send:
mPgpData.setEncryptionKeys(null);
onSend();
break;
case R.id.save:
onSave();
break;
case R.id.discard:
onDiscard();
break;
case R.id.add_cc_bcc:
onAddCcBcc();
break;
case R.id.add_attachment:
onAddAttachment();
break;
case R.id.add_attachment_image:
onAddAttachment2("image/*");
break;
case R.id.add_attachment_video:
onAddAttachment2("video/*");
break;
case R.id.choose_identity:
onChooseIdentity();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
private void onChooseIdentity()
{
// keep things simple: trigger account choice only if there are more
// than 1 account
if (Preferences.getPreferences(this).getAccounts().length > 1)
{
final Intent intent = new Intent(this, ChooseAccount.class);
intent.putExtra(ChooseAccount.EXTRA_ACCOUNT, mAccount.getUuid());
intent.putExtra(ChooseAccount.EXTRA_IDENTITY, mIdentity);
startActivityForResult(intent, ACTIVITY_CHOOSE_ACCOUNT);
}
else if (mAccount.getIdentities().size() > 1)
{
Intent intent = new Intent(this, ChooseIdentity.class);
intent.putExtra(ChooseIdentity.EXTRA_ACCOUNT, mAccount.getUuid());
startActivityForResult(intent, ACTIVITY_CHOOSE_IDENTITY);
}
else
{
Toast.makeText(this, getString(R.string.no_identities),
Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.message_compose_option, menu);
/*
* Show the menu items "Add attachment (Image)" and "Add attachment (Video)"
* if the work-around for the Gallery bug is enabled (see Issue 1186).
*/
int found = 0;
for (int i = menu.size() - 1; i >= 0; i--)
{
MenuItem item = menu.getItem(i);
int id = item.getItemId();
if ((id == R.id.add_attachment_image) ||
(id == R.id.add_attachment_video))
{
item.setVisible(K9.useGalleryBugWorkaround());
found++;
}
// We found all the menu items we were looking for. So stop here.
if (found == 2) break;
}
return true;
}
@Override
public void onBackPressed()
{
// This will be called either automatically for you on 2.0
// or later, or by the code above on earlier versions of the
// platform.
if (mDraftNeedsSaving)
{
showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE);
}
else
{
finish();
}
}
@Override
public Dialog onCreateDialog(int id)
{
switch (id)
{
case DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE:
return new AlertDialog.Builder(this)
.setTitle(R.string.save_or_discard_draft_message_dlg_title)
.setMessage(R.string.save_or_discard_draft_message_instructions_fmt)
.setPositiveButton(R.string.save_draft_action, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dismissDialog(1);
onSave();
}
})
.setNegativeButton(R.string.discard_action, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dismissDialog(1);
onDiscard();
}
})
.create();
}
return super.onCreateDialog(id);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (
// TODO - when we move to android 2.0, uncomment this.
// android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR &&
keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0
&& K9.manageBack())
{
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Returns true if all attachments were able to be attached, otherwise returns false.
*/
private boolean loadAttachments(Part part, int depth) throws MessagingException
{
if (part.getBody() instanceof Multipart)
{
Multipart mp = (Multipart) part.getBody();
boolean ret = true;
for (int i = 0, count = mp.getCount(); i < count; i++)
{
if (!loadAttachments(mp.getBodyPart(i), depth + 1))
{
ret = false;
}
}
return ret;
}
else
{
String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
String name = MimeUtility.getHeaderParameter(contentType, "name");
if (name != null)
{
Body body = part.getBody();
if (body != null && body instanceof LocalAttachmentBody)
{
final Uri uri = ((LocalAttachmentBody) body).getContentUri();
mHandler.post(new Runnable()
{
public void run()
{
addAttachment(uri);
}
});
}
else
{
return false;
}
}
return true;
}
}
/**
* Pull out the parts of the now loaded source message and apply them to the new message
* depending on the type of message being composed.
* @param message
*/
private void processSourceMessage(Message message)
{
String action = getIntent().getAction();
if (ACTION_REPLY.equals(action) || ACTION_REPLY_ALL.equals(action))
{
try
{
if (message.getSubject() != null)
{
final String subject = prefix.matcher(message.getSubject()).replaceFirst("");
if (!subject.toLowerCase().startsWith("re:"))
{
mSubjectView.setText("Re: " + subject);
}
else
{
mSubjectView.setText(subject);
}
}
else
{
mSubjectView.setText("");
}
/*
* If a reply-to was included with the message use that, otherwise use the from
* or sender address.
*/
Address[] replyToAddresses;
if (message.getReplyTo().length > 0)
{
addAddresses(mToView, replyToAddresses = message.getReplyTo());
}
else
{
addAddresses(mToView, replyToAddresses = message.getFrom());
}
if (message.getMessageId() != null && message.getMessageId().length() > 0)
{
String messageId = message.getMessageId();
mInReplyTo = messageId;
if (message.getReferences() != null && message.getReferences().length > 0)
{
StringBuffer buffy = new StringBuffer();
for (int i=0; i < message.getReferences().length; i++)
buffy.append(message.getReferences()[i]);
mReferences = buffy.toString() + " " + mInReplyTo;
}
else
{
mReferences = mInReplyTo;
}
}
else
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "could not get Message-ID.");
}
Part part = MimeUtility.findFirstPartByMimeType(mSourceMessage,
"text/plain");
if (part != null || mSourceMessageBody != null)
{
String quotedText = String.format(
getString(R.string.message_compose_reply_header_fmt),
Address.toString(mSourceMessage.getFrom()));
final String prefix = mAccount.getQuotePrefix();
// "$" and "\" in the quote prefix have to be escaped for
// the replaceAll() invocation.
final String escapedPrefix = prefix.replaceAll("(\\\\|\\$)", "\\\\$1");
final String text = (mSourceMessageBody != null) ?
mSourceMessageBody :
MimeUtility.getTextFromPart(part);
final String wrappedText = Utility.wrap(text, REPLY_WRAP_LINE_WIDTH - prefix.length());
quotedText += wrappedText.replaceAll("(?m)^", escapedPrefix);
quotedText = quotedText.replaceAll("\\\r", "");
mQuotedText.setText(quotedText);
mQuotedTextBar.setVisibility(View.VISIBLE);
mQuotedText.setVisibility(View.VISIBLE);
}
if (ACTION_REPLY_ALL.equals(action) || ACTION_REPLY.equals(action))
{
Identity useIdentity = null;
for (Address address : message.getRecipients(RecipientType.TO))
{
Identity identity = mAccount.findIdentity(address);
if (identity != null)
{
useIdentity = identity;
break;
}
}
if (useIdentity == null)
{
if (message.getRecipients(RecipientType.CC).length > 0)
{
for (Address address : message.getRecipients(RecipientType.CC))
{
Identity identity = mAccount.findIdentity(address);
if (identity != null)
{
useIdentity = identity;
break;
}
}
}
}
if (useIdentity != null)
{
Identity defaultIdentity = mAccount.getIdentity(0);
if (useIdentity != defaultIdentity)
{
switchToIdentity(useIdentity);
}
}
}
if (ACTION_REPLY_ALL.equals(action))
{
for (Address address : message.getRecipients(RecipientType.TO))
{
if (!mAccount.isAnIdentity(address))
{
addAddress(mToView, address);
}
}
if (message.getRecipients(RecipientType.CC).length > 0)
{
for (Address address : message.getRecipients(RecipientType.CC))
{
if (!mAccount.isAnIdentity(address) && !Utility.arrayContains(replyToAddresses, address))
{
addAddress(mCcView, address);
}
}
mCcView.setVisibility(View.VISIBLE);
}
}
}
catch (MessagingException me)
{
/*
* This really should not happen at this point but if it does it's okay.
* The user can continue composing their message.
*/
}
}
else if (ACTION_FORWARD.equals(action))
{
try
{
if (message.getSubject() != null && !message.getSubject().toLowerCase().startsWith("fwd:"))
{
mSubjectView.setText("Fwd: " + message.getSubject());
}
else
{
mSubjectView.setText(message.getSubject());
}
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part == null)
{
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null || mSourceMessageBody != null)
{
String quotedText = mSourceMessageBody;
if (quotedText == null)
{
quotedText = MimeUtility.getTextFromPart(part);
}
if (quotedText != null)
{
String text = String.format(
getString(R.string.message_compose_fwd_header_fmt),
mSourceMessage.getSubject(),
Address.toString(mSourceMessage.getFrom()),
Address.toString(
mSourceMessage.getRecipients(RecipientType.TO)),
Address.toString(
mSourceMessage.getRecipients(RecipientType.CC)));
quotedText = quotedText.replaceAll("\\\r", "");
text += quotedText;
mQuotedText.setText(text);
mQuotedTextBar.setVisibility(View.VISIBLE);
mQuotedText.setVisibility(View.VISIBLE);
}
}
if (!mSourceMessageProcessed)
{
if (!loadAttachments(message, 0))
{
mHandler.sendEmptyMessage(MSG_SKIPPED_ATTACHMENTS);
}
}
}
catch (MessagingException me)
{
/*
* This really should not happen at this point but if it does it's okay.
* The user can continue composing their message.
*/
}
}
else if (ACTION_EDIT_DRAFT.equals(action))
{
try
{
mDraftUid = message.getUid();
mSubjectView.setText(message.getSubject());
addAddresses(mToView, message.getRecipients(RecipientType.TO));
if (message.getRecipients(RecipientType.CC).length > 0)
{
addAddresses(mCcView, message.getRecipients(RecipientType.CC));
mCcView.setVisibility(View.VISIBLE);
}
if (message.getRecipients(RecipientType.BCC).length > 0)
{
addAddresses(mBccView, message.getRecipients(RecipientType.BCC));
mBccView.setVisibility(View.VISIBLE);
}
// Read In-Reply-To header from draft
final String[] inReplyTo = message.getHeader("In-Reply-To");
if ((inReplyTo != null) && (inReplyTo.length >= 1))
{
mInReplyTo = inReplyTo[0];
}
// Read References header from draft
final String[] references = message.getHeader("References");
if ((references != null) && (references.length >= 1))
{
mReferences = references[0];
}
if (!mSourceMessageProcessed)
{
loadAttachments(message, 0);
}
Integer bodyLength = null;
String[] k9identities = message.getHeader(K9.K9MAIL_IDENTITY);
if (k9identities != null && k9identities.length > 0)
{
String k9identity = k9identities[0];
if (k9identity != null)
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Got a saved identity: " + k9identity);
StringTokenizer tokens = new StringTokenizer(k9identity, ":", false);
String bodyLengthS = null;
String name = null;
String email = null;
String signature = null;
boolean signatureUse = message.getFolder().getAccount().getSignatureUse();
if (tokens.hasMoreTokens())
{
bodyLengthS = Utility.base64Decode(tokens.nextToken());
try
{
bodyLength = Integer.parseInt(bodyLengthS);
}
catch (Exception e)
{
Log.e(K9.LOG_TAG, "Unable to parse bodyLength '" + bodyLengthS + "'");
}
}
if (tokens.hasMoreTokens())
{
signatureUse = true;
signature = Utility.base64Decode(tokens.nextToken());
}
if (tokens.hasMoreTokens())
{
name = Utility.base64Decode(tokens.nextToken());
}
if (tokens.hasMoreTokens())
{
email = Utility.base64Decode(tokens.nextToken());
}
Identity newIdentity = new Identity();
newIdentity.setSignatureUse(signatureUse);
if (signature != null)
{
newIdentity.setSignature(signature);
mSignatureChanged = true;
}
else
{
newIdentity.setSignature(mIdentity.getSignature());
}
if (name != null)
{
newIdentity.setName(name);
mIdentityChanged = true;
}
else
{
newIdentity.setName(mIdentity.getName());
}
if (email != null)
{
newIdentity.setEmail(email);
mIdentityChanged = true;
}
else
{
newIdentity.setEmail(mIdentity.getEmail());
}
mIdentity = newIdentity;
updateSignature();
updateFrom();
}
}
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part != null)
{
String text = MimeUtility.getTextFromPart(part);
if (bodyLength != null && bodyLength + 1 < text.length()) // + 1 to get rid of the newline we added when saving the draft
{
String bodyText = text.substring(0, bodyLength);
String quotedText = text.substring(bodyLength + 1, text.length());
mMessageContentView.setText(bodyText);
mQuotedText.setText(quotedText);
mQuotedTextBar.setVisibility(View.VISIBLE);
mQuotedText.setVisibility(View.VISIBLE);
}
else
{
mMessageContentView.setText(text);
}
}
}
catch (MessagingException me)
{
// TODO
}
}
mSourceMessageProcessed = true;
mDraftNeedsSaving = false;
}
class Listener extends MessagingListener
{
@Override
public void loadMessageForViewStarted(Account account, String folder, String uid)
{
if ((mMessageReference == null) || !mMessageReference.uid.equals(uid))
{
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_ON);
}
@Override
public void loadMessageForViewFinished(Account account, String folder, String uid, Message message)
{
if ((mMessageReference == null) || !mMessageReference.uid.equals(uid))
{
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_OFF);
}
@Override
public void loadMessageForViewBodyAvailable(Account account, String folder, String uid, final Message message)
{
if ((mMessageReference == null) || !mMessageReference.uid.equals(uid))
{
return;
}
mSourceMessage = message;
runOnUiThread(new Runnable()
{
public void run()
{
processSourceMessage(message);
}
});
}
@Override
public void loadMessageForViewFailed(Account account, String folder, String uid, Throwable t)
{
if ((mMessageReference == null) || !mMessageReference.uid.equals(uid))
{
return;
}
mHandler.sendEmptyMessage(MSG_PROGRESS_OFF);
// TODO show network error
}
@Override
public void messageUidChanged(Account account, String folder, String oldUid, String newUid)
{
//TODO: is this really necessary here? mDraftUid is update after the call to MessagingController.saveDraft()
// Track UID changes of the draft message
if (account.equals(mAccount) &&
folder.equals(mAccount.getDraftsFolderName()) &&
oldUid.equals(mDraftUid))
{
mDraftUid = newUid;
}
// Track UID changes of the source message
if (mMessageReference != null)
{
final Account sourceAccount = Preferences.getPreferences(MessageCompose.this).getAccount(mMessageReference.accountUuid);
final String sourceFolder = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
if (account.equals(sourceAccount) && (folder.equals(sourceFolder)))
{
if (oldUid.equals(sourceMessageUid))
{
mMessageReference.uid = newUid;
}
if ((mSourceMessage != null) && (oldUid.equals(mSourceMessage.getUid())))
{
mSourceMessage.setUid(newUid);
}
}
}
}
}
private String decode(String s)
throws UnsupportedEncodingException
{
return URLDecoder.decode(s, "UTF-8");
}
/**
* When we are launched with an intent that includes a mailto: URI, we can actually
* gather quite a few of our message fields from it.
*
* @mailToString the href (which must start with "mailto:").
*/
private void initializeFromMailTo(String mailToString)
{
// Chop up everything between mailto: and ? to find recipients
int index = mailToString.indexOf("?");
int length = "mailto".length() + 1;
String to;
try
{
// Extract the recipient after mailto:
if (index == -1)
{
to = decode(mailToString.substring(length));
}
else
{
to = decode(mailToString.substring(length, index));
}
mToView.setText(to);
}
catch (UnsupportedEncodingException e)
{
Log.e(K9.LOG_TAG, e.getMessage() + " while decoding '" + mailToString + "'");
}
// Extract the other parameters
// We need to disguise this string as a URI in order to parse it
Uri uri = Uri.parse("foo://" + mailToString);
String addressList;
addressList = "";
List<String> cc = uri.getQueryParameters("cc");
for (String address : cc)
{
addressList += address + ",";
}
mCcView.setText(addressList);
addressList = "";
List<String> bcc = uri.getQueryParameters("bcc");
for (String address : bcc)
{
addressList += address + ",";
}
mBccView.setText(addressList);
List<String> subject = uri.getQueryParameters("subject");
if (subject.size() > 0)
{
mSubjectView.setText(subject.get(0));
}
List<String> body = uri.getQueryParameters("body");
if (body.size() > 0)
{
mMessageContentView.setText(body.get(0));
}
}
private class SendMessageTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
/*
* Create the message from all the data the user has entered.
*/
MimeMessage message;
try
{
message = createMessage(true); // Only append sig on save
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me);
throw new RuntimeException("Failed to create a new message for send or save.", me);
}
MessagingController.getInstance(getApplication()).sendMessage(mAccount, message, null);
if (mDraftUid != null)
{
MessagingController.getInstance(getApplication()).deleteDraft(mAccount, mDraftUid);
mDraftUid = null;
}
return null;
}
}
private class SaveMessageTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
/*
* Create the message from all the data the user has entered.
*/
MimeMessage message;
try
{
message = createMessage(false); // Only append sig on save
}
catch (MessagingException me)
{
Log.e(K9.LOG_TAG, "Failed to create new message for send or save.", me);
throw new RuntimeException("Failed to create a new message for send or save.", me);
}
/*
* Save a draft
*/
if (mDraftUid != null)
{
message.setUid(mDraftUid);
}
else if (ACTION_EDIT_DRAFT.equals(getIntent().getAction()))
{
/*
* We're saving a previously saved draft, so update the new message's uid
* to the old message's uid.
*/
message.setUid(mMessageReference.uid);
}
String k9identity = Utility.base64Encode("" + mMessageContentView.getText().toString().length());
if (mIdentityChanged || mSignatureChanged)
{
String signature = mSignatureView.getText().toString();
k9identity += ":" + Utility.base64Encode(signature);
if (mIdentityChanged)
{
String name = mIdentity.getName();
String email = mIdentity.getEmail();
k9identity += ":" + Utility.base64Encode(name) + ":" + Utility.base64Encode(email);
}
}
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Saving identity: " + k9identity);
message.addHeader(K9.K9MAIL_IDENTITY, k9identity);
Message draftMessage = MessagingController.getInstance(getApplication()).saveDraft(mAccount, message);
mDraftUid = draftMessage.getUid();
// Don't display the toast if the user is just changing the orientation
if ((getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0)
{
mHandler.sendEmptyMessage(MSG_SAVED_DRAFT);
}
return null;
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.message_compose);
final Intent intent = getIntent();
mMessageReference = (MessageReference) intent.getSerializableExtra(EXTRA_MESSAGE_REFERENCE);
mSourceMessageBody = (String) intent.getStringExtra(EXTRA_MESSAGE_BODY);
final String accountUuid = (mMessageReference != null) ?
mMessageReference.accountUuid :
intent.getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
if (mAccount == null)
{
mAccount = Preferences.getPreferences(this).getDefaultAccount();
}
if (mAccount == null)
{
/*
* There are no accounts set up. This should not have happened. Prompt the
* user to set up an account as an acceptable bailout.
*/
startActivity(new Intent(this, Accounts.class));
mDraftNeedsSaving = false;
finish();
return;
}
mAddressAdapter = EmailAddressAdapter.getInstance(this);
mAddressValidator = new EmailAddressValidator();
mFromView = (TextView)findViewById(R.id.from);
mToView = (MultiAutoCompleteTextView)findViewById(R.id.to);
mCcView = (MultiAutoCompleteTextView)findViewById(R.id.cc);
mBccView = (MultiAutoCompleteTextView)findViewById(R.id.bcc);
mSubjectView = (EditText)findViewById(R.id.subject);
EditText upperSignature = (EditText)findViewById(R.id.upper_signature);
EditText lowerSignature = (EditText)findViewById(R.id.lower_signature);
mMessageContentView = (EditText)findViewById(R.id.message_content);
mAttachments = (LinearLayout)findViewById(R.id.attachments);
mQuotedTextBar = findViewById(R.id.quoted_text_bar);
mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete);
mQuotedText = (EditText)findViewById(R.id.quoted_text);
TextWatcher watcher = new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start,
int before, int after) { }
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
mDraftNeedsSaving = true;
}
public void afterTextChanged(android.text.Editable s) { }
};
TextWatcher sigwatcher = new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start,
int before, int after) { }
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
mDraftNeedsSaving = true;
mSignatureChanged = true;
}
public void afterTextChanged(android.text.Editable s) { }
};
mToView.addTextChangedListener(watcher);
mCcView.addTextChangedListener(watcher);
mBccView.addTextChangedListener(watcher);
mSubjectView.addTextChangedListener(watcher);
mMessageContentView.addTextChangedListener(watcher);
mQuotedText.addTextChangedListener(watcher);
/*
* We set this to invisible by default. Other methods will turn it back on if it's
* needed.
*/
mQuotedTextBar.setVisibility(View.GONE);
mQuotedText.setVisibility(View.GONE);
mQuotedTextDelete.setOnClickListener(this);
mFromView.setVisibility(View.GONE);
mToView.setAdapter(mAddressAdapter);
mToView.setTokenizer(new Rfc822Tokenizer());
mToView.setValidator(mAddressValidator);
mCcView.setAdapter(mAddressAdapter);
mCcView.setTokenizer(new Rfc822Tokenizer());
mCcView.setValidator(mAddressValidator);
mBccView.setAdapter(mAddressAdapter);
mBccView.setTokenizer(new Rfc822Tokenizer());
mBccView.setValidator(mAddressValidator);
mSubjectView.setOnFocusChangeListener(this);
if (savedInstanceState != null)
{
/*
* This data gets used in onCreate, so grab it here instead of onRestoreIntstanceState
*/
mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false);
}
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) || Intent.ACTION_SENDTO.equals(action))
{
/*
* Someone has clicked a mailto: link. The address is in the URI.
*/
if (intent.getData() != null)
{
Uri uri = intent.getData();
if ("mailto".equals(uri.getScheme()))
{
initializeFromMailTo(uri.toString());
}
else
{
String toText = uri.getSchemeSpecificPart();
if (toText != null)
{
mToView.setText(toText);
}
}
}
}
//TODO: Use constant Intent.ACTION_SEND_MULTIPLE once we drop Android 1.5 support
else if (Intent.ACTION_SEND.equals(action)
|| Intent.ACTION_SENDTO.equals(action)
|| "android.intent.action.SEND_MULTIPLE".equals(action))
{
/*
* Someone is trying to compose an email with an attachment, probably Pictures.
* The Intent should contain an EXTRA_STREAM with the data to attach.
*/
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
if (text != null)
{
mMessageContentView.setText(text);
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
if (subject != null)
{
mSubjectView.setText(subject);
}
String type = intent.getType();
//TODO: Use constant Intent.ACTION_SEND_MULTIPLE once we drop Android 1.5 support
if ("android.intent.action.SEND_MULTIPLE".equals(action))
{
ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (list != null)
{
for (Parcelable parcelable : list)
{
Uri stream = (Uri) parcelable;
if (stream != null && type != null)
{
if (MimeUtility.mimeTypeMatches(type, K9.ACCEPTABLE_ATTACHMENT_SEND_TYPES))
{
addAttachment(stream);
}
}
}
}
}
else
{
Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (stream != null && type != null)
{
if (MimeUtility.mimeTypeMatches(type, K9.ACCEPTABLE_ATTACHMENT_SEND_TYPES))
{
addAttachment(stream);
}
}
}
/*
* There might be an EXTRA_SUBJECT, EXTRA_TEXT, EXTRA_EMAIL, EXTRA_BCC or EXTRA_CC
*/
String extraSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
String extraText = intent.getStringExtra(Intent.EXTRA_TEXT);
mSubjectView.setText(extraSubject);
mMessageContentView.setText(extraText);
String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC);
String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC);
String addressList;
// Cache array size, as per Google's recommendations.
int arraySize;
int i;
addressList = "";
if (extraEmail != null)
{
arraySize = extraEmail.length;
for (i=0; i < arraySize; i++)
{
addressList += extraEmail[i]+", ";
}
}
mToView.setText(addressList);
addressList = "";
if (extraCc != null)
{
arraySize = extraCc.length;
for (i=0; i < arraySize; i++)
{
addressList += extraCc[i]+", ";
}
}
mCcView.setText(addressList);
addressList = "";
if (extraBcc != null)
{
arraySize = extraBcc.length;
for (i=0; i < arraySize; i++)
{
addressList += extraBcc[i]+", ";
}
}
mBccView.setText(addressList);
}
if (mIdentity == null)
{
mIdentity = mAccount.getIdentity(0);
}
if (mAccount.isSignatureBeforeQuotedText())
{
mSignatureView = upperSignature;
lowerSignature.setVisibility(View.GONE);
}
else
{
mSignatureView = lowerSignature;
upperSignature.setVisibility(View.GONE);
}
mSignatureView.addTextChangedListener(sigwatcher);
if (!mIdentity.getSignatureUse())
{
mSignatureView.setVisibility(View.GONE);
}
if (!mSourceMessageProcessed)
{
updateFrom();
updateSignature();
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action) ||
ACTION_FORWARD.equals(action) ||
ACTION_EDIT_DRAFT.equals(action))
{
/*
* If we need to load the message we add ourself as a message listener here
* so we can kick it off. Normally we add in onResume but we don't
* want to reload the message every time the activity is resumed.
* There is no harm in adding twice.
*/
MessagingController.getInstance(getApplication()).addListener(mListener);
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null);
}
if (!ACTION_EDIT_DRAFT.equals(action))
{
String bccAddress = mAccount.getAlwaysBcc();
if ((bccAddress != null) && !("".equals(bccAddress)))
{
addAddress(mBccView, new Address(bccAddress, ""));
}
}
/*
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "action = " + action + ", account = " + mMessageReference.accountUuid + ", folder = " + mMessageReference.folderName + ", sourceMessageUid = " + mMessageReference.uid);
*/
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Setting message ANSWERED flag to true");
// TODO: Really, we should wait until we send the message, but that would require saving the original
// message info along with a Draft copy, in case it is left in Drafts for a while before being sent
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).setFlag(account, folderName, new String[] { sourceMessageUid }, Flag.ANSWERED, true);
}
updateTitle();
}
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action) ||
ACTION_EDIT_DRAFT.equals(action))
{
//change focus to message body.
mMessageContentView.requestFocus();
}
mEncryptLayout = (View)findViewById(R.id.layout_encrypt);
mCryptoSignatureCheckbox = (CheckBox)findViewById(R.id.cb_crypto_signature);
mCryptoSignatureUserId = (TextView)findViewById(R.id.userId);
mCryptoSignatureUserIdRest = (TextView)findViewById(R.id.userIdRest);
mEncryptCheckbox = (CheckBox)findViewById(R.id.cb_encrypt);
initializeCrypto();
final CryptoProvider crypto = mAccount.getCryptoProvider();
if (crypto.isAvailable(this))
{
mEncryptLayout.setVisibility(View.VISIBLE);
mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked())
{
mPreventDraftSaving = true;
if (!crypto.selectSecretKey(MessageCompose.this, mPgpData))
{
mPreventDraftSaving = false;
}
checkBox.setChecked(false);
}
else
{
mPgpData.setSignatureKeyId(0);
updateEncryptLayout();
}
}
});
if (mAccount.getCryptoAutoSignature())
{
long ids[] = crypto.getSecretKeyIdsFromEmail(this, mIdentity.getEmail());
if (ids != null && ids.length > 0)
{
mPgpData.setSignatureKeyId(ids[0]);
mPgpData.setSignatureUserId(crypto.getUserId(this, ids[0]));
}
else
{
mPgpData.setSignatureKeyId(0);
mPgpData.setSignatureUserId(null);
}
}
updateEncryptLayout();
}
else
{
mEncryptLayout.setVisibility(View.GONE);
}
mDraftNeedsSaving = false;
}
| public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.message_compose);
final Intent intent = getIntent();
mMessageReference = (MessageReference) intent.getSerializableExtra(EXTRA_MESSAGE_REFERENCE);
mSourceMessageBody = (String) intent.getStringExtra(EXTRA_MESSAGE_BODY);
final String accountUuid = (mMessageReference != null) ?
mMessageReference.accountUuid :
intent.getStringExtra(EXTRA_ACCOUNT);
mAccount = Preferences.getPreferences(this).getAccount(accountUuid);
if (mAccount == null)
{
mAccount = Preferences.getPreferences(this).getDefaultAccount();
}
if (mAccount == null)
{
/*
* There are no accounts set up. This should not have happened. Prompt the
* user to set up an account as an acceptable bailout.
*/
startActivity(new Intent(this, Accounts.class));
mDraftNeedsSaving = false;
finish();
return;
}
mAddressAdapter = EmailAddressAdapter.getInstance(this);
mAddressValidator = new EmailAddressValidator();
mFromView = (TextView)findViewById(R.id.from);
mToView = (MultiAutoCompleteTextView)findViewById(R.id.to);
mCcView = (MultiAutoCompleteTextView)findViewById(R.id.cc);
mBccView = (MultiAutoCompleteTextView)findViewById(R.id.bcc);
mSubjectView = (EditText)findViewById(R.id.subject);
EditText upperSignature = (EditText)findViewById(R.id.upper_signature);
EditText lowerSignature = (EditText)findViewById(R.id.lower_signature);
mMessageContentView = (EditText)findViewById(R.id.message_content);
mAttachments = (LinearLayout)findViewById(R.id.attachments);
mQuotedTextBar = findViewById(R.id.quoted_text_bar);
mQuotedTextDelete = (ImageButton)findViewById(R.id.quoted_text_delete);
mQuotedText = (EditText)findViewById(R.id.quoted_text);
TextWatcher watcher = new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start,
int before, int after) { }
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
mDraftNeedsSaving = true;
}
public void afterTextChanged(android.text.Editable s) { }
};
TextWatcher sigwatcher = new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start,
int before, int after) { }
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
mDraftNeedsSaving = true;
mSignatureChanged = true;
}
public void afterTextChanged(android.text.Editable s) { }
};
mToView.addTextChangedListener(watcher);
mCcView.addTextChangedListener(watcher);
mBccView.addTextChangedListener(watcher);
mSubjectView.addTextChangedListener(watcher);
mMessageContentView.addTextChangedListener(watcher);
mQuotedText.addTextChangedListener(watcher);
/*
* We set this to invisible by default. Other methods will turn it back on if it's
* needed.
*/
mQuotedTextBar.setVisibility(View.GONE);
mQuotedText.setVisibility(View.GONE);
mQuotedTextDelete.setOnClickListener(this);
mFromView.setVisibility(View.GONE);
mToView.setAdapter(mAddressAdapter);
mToView.setTokenizer(new Rfc822Tokenizer());
mToView.setValidator(mAddressValidator);
mCcView.setAdapter(mAddressAdapter);
mCcView.setTokenizer(new Rfc822Tokenizer());
mCcView.setValidator(mAddressValidator);
mBccView.setAdapter(mAddressAdapter);
mBccView.setTokenizer(new Rfc822Tokenizer());
mBccView.setValidator(mAddressValidator);
mSubjectView.setOnFocusChangeListener(this);
if (savedInstanceState != null)
{
/*
* This data gets used in onCreate, so grab it here instead of onRestoreIntstanceState
*/
mSourceMessageProcessed = savedInstanceState.getBoolean(STATE_KEY_SOURCE_MESSAGE_PROCED, false);
}
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action))
{
/*
* Someone has clicked a mailto: link. The address is in the URI.
*/
if (intent.getData() != null)
{
Uri uri = intent.getData();
if ("mailto".equals(uri.getScheme()))
{
initializeFromMailTo(uri.toString());
}
else
{
String toText = uri.getSchemeSpecificPart();
if (toText != null)
{
mToView.setText(toText);
}
}
}
}
//TODO: Use constant Intent.ACTION_SEND_MULTIPLE once we drop Android 1.5 support
else if (Intent.ACTION_SEND.equals(action)
|| Intent.ACTION_SENDTO.equals(action)
|| "android.intent.action.SEND_MULTIPLE".equals(action))
{
/*
* Someone is trying to compose an email with an attachment, probably Pictures.
* The Intent should contain an EXTRA_STREAM with the data to attach.
*/
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
if (text != null)
{
mMessageContentView.setText(text);
}
String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
if (subject != null)
{
mSubjectView.setText(subject);
}
String type = intent.getType();
//TODO: Use constant Intent.ACTION_SEND_MULTIPLE once we drop Android 1.5 support
if ("android.intent.action.SEND_MULTIPLE".equals(action))
{
ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (list != null)
{
for (Parcelable parcelable : list)
{
Uri stream = (Uri) parcelable;
if (stream != null && type != null)
{
if (MimeUtility.mimeTypeMatches(type, K9.ACCEPTABLE_ATTACHMENT_SEND_TYPES))
{
addAttachment(stream);
}
}
}
}
}
else
{
Uri stream = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (stream != null && type != null)
{
if (MimeUtility.mimeTypeMatches(type, K9.ACCEPTABLE_ATTACHMENT_SEND_TYPES))
{
addAttachment(stream);
}
}
}
/*
* There might be an EXTRA_SUBJECT, EXTRA_TEXT, EXTRA_EMAIL, EXTRA_BCC or EXTRA_CC
*/
String extraSubject = intent.getStringExtra(Intent.EXTRA_SUBJECT);
String extraText = intent.getStringExtra(Intent.EXTRA_TEXT);
mSubjectView.setText(extraSubject);
mMessageContentView.setText(extraText);
String[] extraEmail = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
String[] extraCc = intent.getStringArrayExtra(Intent.EXTRA_CC);
String[] extraBcc = intent.getStringArrayExtra(Intent.EXTRA_BCC);
String addressList;
// Cache array size, as per Google's recommendations.
int arraySize;
int i;
addressList = "";
if (extraEmail != null)
{
arraySize = extraEmail.length;
for (i=0; i < arraySize; i++)
{
addressList += extraEmail[i]+", ";
}
}
mToView.setText(addressList);
addressList = "";
if (extraCc != null)
{
arraySize = extraCc.length;
for (i=0; i < arraySize; i++)
{
addressList += extraCc[i]+", ";
}
}
mCcView.setText(addressList);
addressList = "";
if (extraBcc != null)
{
arraySize = extraBcc.length;
for (i=0; i < arraySize; i++)
{
addressList += extraBcc[i]+", ";
}
}
mBccView.setText(addressList);
}
if (mIdentity == null)
{
mIdentity = mAccount.getIdentity(0);
}
if (mAccount.isSignatureBeforeQuotedText())
{
mSignatureView = upperSignature;
lowerSignature.setVisibility(View.GONE);
}
else
{
mSignatureView = lowerSignature;
upperSignature.setVisibility(View.GONE);
}
mSignatureView.addTextChangedListener(sigwatcher);
if (!mIdentity.getSignatureUse())
{
mSignatureView.setVisibility(View.GONE);
}
if (!mSourceMessageProcessed)
{
updateFrom();
updateSignature();
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action) ||
ACTION_FORWARD.equals(action) ||
ACTION_EDIT_DRAFT.equals(action))
{
/*
* If we need to load the message we add ourself as a message listener here
* so we can kick it off. Normally we add in onResume but we don't
* want to reload the message every time the activity is resumed.
* There is no harm in adding twice.
*/
MessagingController.getInstance(getApplication()).addListener(mListener);
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).loadMessageForView(account, folderName, sourceMessageUid, null);
}
if (!ACTION_EDIT_DRAFT.equals(action))
{
String bccAddress = mAccount.getAlwaysBcc();
if ((bccAddress != null) && !("".equals(bccAddress)))
{
addAddress(mBccView, new Address(bccAddress, ""));
}
}
/*
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "action = " + action + ", account = " + mMessageReference.accountUuid + ", folder = " + mMessageReference.folderName + ", sourceMessageUid = " + mMessageReference.uid);
*/
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action))
{
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Setting message ANSWERED flag to true");
// TODO: Really, we should wait until we send the message, but that would require saving the original
// message info along with a Draft copy, in case it is left in Drafts for a while before being sent
final Account account = Preferences.getPreferences(this).getAccount(mMessageReference.accountUuid);
final String folderName = mMessageReference.folderName;
final String sourceMessageUid = mMessageReference.uid;
MessagingController.getInstance(getApplication()).setFlag(account, folderName, new String[] { sourceMessageUid }, Flag.ANSWERED, true);
}
updateTitle();
}
if (ACTION_REPLY.equals(action) ||
ACTION_REPLY_ALL.equals(action) ||
ACTION_EDIT_DRAFT.equals(action))
{
//change focus to message body.
mMessageContentView.requestFocus();
}
mEncryptLayout = (View)findViewById(R.id.layout_encrypt);
mCryptoSignatureCheckbox = (CheckBox)findViewById(R.id.cb_crypto_signature);
mCryptoSignatureUserId = (TextView)findViewById(R.id.userId);
mCryptoSignatureUserIdRest = (TextView)findViewById(R.id.userIdRest);
mEncryptCheckbox = (CheckBox)findViewById(R.id.cb_encrypt);
initializeCrypto();
final CryptoProvider crypto = mAccount.getCryptoProvider();
if (crypto.isAvailable(this))
{
mEncryptLayout.setVisibility(View.VISIBLE);
mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked())
{
mPreventDraftSaving = true;
if (!crypto.selectSecretKey(MessageCompose.this, mPgpData))
{
mPreventDraftSaving = false;
}
checkBox.setChecked(false);
}
else
{
mPgpData.setSignatureKeyId(0);
updateEncryptLayout();
}
}
});
if (mAccount.getCryptoAutoSignature())
{
long ids[] = crypto.getSecretKeyIdsFromEmail(this, mIdentity.getEmail());
if (ids != null && ids.length > 0)
{
mPgpData.setSignatureKeyId(ids[0]);
mPgpData.setSignatureUserId(crypto.getUserId(this, ids[0]));
}
else
{
mPgpData.setSignatureKeyId(0);
mPgpData.setSignatureUserId(null);
}
}
updateEncryptLayout();
}
else
{
mEncryptLayout.setVisibility(View.GONE);
}
mDraftNeedsSaving = false;
}
|
diff --git a/src/main/java/org/jboss/modules/ModuleClassLoader.java b/src/main/java/org/jboss/modules/ModuleClassLoader.java
index 4a7abc5a..544a2096 100644
--- a/src/main/java/org/jboss/modules/ModuleClassLoader.java
+++ b/src/main/java/org/jboss/modules/ModuleClassLoader.java
@@ -1,656 +1,656 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* 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.jboss.modules;
import org.jboss.modules.filter.PathFilter;
import org.jboss.modules.log.ModuleLogger;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.net.URL;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* A module classloader. Instances of this class implement the complete view of classes and resources available in a
* module. Contrast with {@link Module}, which has API methods to access the exported view of classes and resources.
*
* @author <a href="mailto:[email protected]">John Bailey</a>
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
* @author [email protected]
*
* @apiviz.landmark
*/
public class ModuleClassLoader extends ConcurrentClassLoader {
static {
try {
ClassLoader.registerAsParallelCapable();
} catch (Throwable ignored) {
}
}
static final ResourceLoaderSpec[] NO_RESOURCE_LOADERS = new ResourceLoaderSpec[0];
private final Module module;
private final ClassFileTransformer transformer;
private volatile Paths<ResourceLoader, ResourceLoaderSpec> paths;
private final LocalLoader localLoader = new LocalLoader() {
public Class<?> loadClassLocal(final String name, final boolean resolve) {
try {
return ModuleClassLoader.this.loadClassLocal(name, resolve);
} catch (ClassNotFoundException e) {
return null;
}
}
public Package loadPackageLocal(final String name) {
return findLoadedPackage(name);
}
public List<Resource> loadResourceLocal(final String name) {
return ModuleClassLoader.this.loadResourceLocal(name);
}
public String toString() {
return "local loader for " + ModuleClassLoader.this.toString();
}
};
private static final AtomicReferenceFieldUpdater<ModuleClassLoader, Paths<ResourceLoader, ResourceLoaderSpec>> pathsUpdater
= unsafeCast(AtomicReferenceFieldUpdater.newUpdater(ModuleClassLoader.class, Paths.class, "paths"));
@SuppressWarnings({ "unchecked" })
private static <A, B> AtomicReferenceFieldUpdater<A, B> unsafeCast(AtomicReferenceFieldUpdater<?, ?> updater) {
return (AtomicReferenceFieldUpdater<A, B>) updater;
}
/**
* Construct a new instance.
*
* @param configuration the module class loader configuration to use
*/
protected ModuleClassLoader(final Configuration configuration) {
module = configuration.getModule();
paths = new Paths<ResourceLoader, ResourceLoaderSpec>(configuration.getResourceLoaders(), Collections.<String, List<ResourceLoader>>emptyMap());
final AssertionSetting setting = configuration.getAssertionSetting();
if (setting != AssertionSetting.INHERIT) {
setDefaultAssertionStatus(setting == AssertionSetting.ENABLED);
}
transformer = configuration.getTransformer();
}
/**
* Recalculate the path maps for this module class loader.
*
* @return {@code true} if the paths were recalculated, or {@code false} if another thread finished recalculating
* before the calling thread
*/
boolean recalculate() {
final Paths<ResourceLoader, ResourceLoaderSpec> paths = this.paths;
return setResourceLoaders(paths, paths.getSourceList(NO_RESOURCE_LOADERS));
}
/**
* Change the set of resource loaders for this module class loader, and recalculate the path maps.
*
* @param resourceLoaders the new resource loaders
* @return {@code true} if the paths were recalculated, or {@code false} if another thread finished recalculating
* before the calling thread
*/
boolean setResourceLoaders(final ResourceLoaderSpec[] resourceLoaders) {
return setResourceLoaders(paths, resourceLoaders);
}
private boolean setResourceLoaders(final Paths<ResourceLoader, ResourceLoaderSpec> paths, final ResourceLoaderSpec[] resourceLoaders) {
final Map<String, List<ResourceLoader>> allPaths = new HashMap<String, List<ResourceLoader>>();
for (ResourceLoaderSpec loaderSpec : resourceLoaders) {
final ResourceLoader loader = loaderSpec.getResourceLoader();
final PathFilter filter = loaderSpec.getPathFilter();
for (String path : loader.getPaths()) {
if (filter.accept(path)) {
final List<ResourceLoader> allLoaders = allPaths.get(path);
if (allLoaders == null) {
ArrayList<ResourceLoader> newList = new ArrayList<ResourceLoader>(16);
newList.add(loader);
allPaths.put(path, newList);
} else {
allLoaders.add(loader);
}
}
}
}
return pathsUpdater.compareAndSet(this, paths, new Paths<ResourceLoader, ResourceLoaderSpec>(resourceLoaders, allPaths));
}
/**
* Get the local loader which refers to this module class loader.
*
* @return the local loader
*/
LocalLoader getLocalLoader() {
return localLoader;
}
/** {@inheritDoc} */
@Override
protected final Class<?> findClass(String className, boolean exportsOnly, final boolean resolve) throws ClassNotFoundException {
// Check if we have already loaded it..
Class<?> loadedClass = findLoadedClass(className);
if (loadedClass != null) {
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
final ModuleLogger log = Module.log;
final Module module = this.module;
log.trace("Finding class %s from %s", className, module);
final Class<?> clazz = module.loadModuleClass(className, resolve);
if (clazz != null) {
return clazz;
}
log.trace("Class %s not found from %s", className, module);
throw new ClassNotFoundException(className + " from [" + module + "]");
}
/**
* Load a class from this class loader.
*
* @param className the class name to load
* @return the loaded class or {@code null} if it was not found
* @throws ClassNotFoundException if an exception occurs while loading the class or its dependencies
*/
public Class<?> loadClassLocal(String className) throws ClassNotFoundException {
return loadClassLocal(className, false);
}
/**
* Load a local class from this class loader.
*
* @param className the class name
* @param resolve {@code true} to resolve the loaded class
* @return the loaded class or {@code null} if it was not found
* @throws ClassNotFoundException if an error occurs while loading the class
*/
public Class<?> loadClassLocal(final String className, final boolean resolve) throws ClassNotFoundException {
final ModuleLogger log = Module.log;
final Module module = this.module;
log.trace("Finding local class %s from %s", className, module);
// Check if we have already loaded it..
Class<?> loadedClass = findLoadedClass(className);
if (loadedClass != null) {
log.trace("Found previously loaded %s from %s", loadedClass, module);
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
final Map<String, List<ResourceLoader>> paths = this.paths.getAllPaths();
log.trace("Loading class %s locally from %s", className, module);
String pathOfClass = Module.pathOfClass(className);
final List<ResourceLoader> loaders = paths.get(pathOfClass);
if (loaders == null) {
// no loaders for this path
return null;
}
// Check to see if we can define it locally it
ClassSpec classSpec;
ResourceLoader resourceLoader;
try {
if (loaders.size() > 0) {
String fileName = Module.fileNameOfClass(className);
for (ResourceLoader loader : loaders) {
classSpec = loader.getClassSpec(fileName);
if (classSpec != null) {
resourceLoader = loader;
try {
preDefine(classSpec, className);
}
catch (Throwable th) {
throw new ClassNotFoundException("Failed to preDefine class: " + className, th);
}
final Class<?> clazz = defineClass(className, classSpec, resourceLoader);
try {
postDefine(classSpec, clazz);
}
catch (Throwable th) {
throw new ClassNotFoundException("Failed to postDefine class: " + className, th);
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
}
}
}
} catch (IOException e) {
throw new ClassNotFoundException(className, e);
} catch (RuntimeException e) {
log.trace(e, "Unexpected runtime exception in module loader");
throw new ClassNotFoundException(className, e);
} catch (Error e) {
log.trace(e, "Unexpected error in module loader");
- throw new ClassNotFoundException(className, e);
+ throw e;
}
log.trace("No local specification found for class %s in %s", className, module);
return null;
}
/**
* Load a local resource from a specific root from this module class loader.
*
* @param root the root name
* @param name the resource name
* @return the resource, or {@code null} if it was not found
*/
Resource loadResourceLocal(final String root, final String name) {
final Map<String, List<ResourceLoader>> paths = this.paths.getAllPaths();
final String path = Module.pathOf(name);
final List<ResourceLoader> loaders = paths.get(path);
if (loaders == null) {
// no loaders for this path
return null;
}
for (ResourceLoader loader : loaders) {
if (root.equals(loader.getRootName())) {
return loader.getResource(name);
}
}
return null;
}
/**
* Load a local resource from this class loader.
*
* @param name the resource name
* @return the list of resources
*/
public List<Resource> loadResourceLocal(final String name) {
final Map<String, List<ResourceLoader>> paths = this.paths.getAllPaths();
final String path = Module.pathOf(name);
final List<ResourceLoader> loaders = paths.get(path);
if (loaders == null) {
// no loaders for this path
return Collections.emptyList();
}
final List<Resource> list = new ArrayList<Resource>(loaders.size());
for (ResourceLoader loader : loaders) {
final Resource resource = loader.getResource(name);
if (resource != null) {
list.add(resource);
}
}
return list.isEmpty() ? Collections.<Resource>emptyList() : list;
}
private Class<?> doDefineOrLoadClass(final String className, final byte[] bytes, int off, int len, CodeSource codeSource) {
try {
final Class<?> definedClass = defineClass(className, bytes, off, len, codeSource);
module.getModuleLoader().incClassCount();
return definedClass;
} catch (LinkageError e) {
final Class<?> loadedClass = findLoadedClass(className);
if (loadedClass != null) {
module.getModuleLoader().incRaceCount();
return loadedClass;
}
throw e;
}
}
/**
* Define a class from a class name and class spec. Also defines any enclosing {@link Package} instances,
* and performs any sealed-package checks.
*
* @param name the class name
* @param classSpec the class spec
* @param resourceLoader the resource loader of the class spec
* @return the new class
*/
private Class<?> defineClass(final String name, final ClassSpec classSpec, final ResourceLoader resourceLoader) {
final ModuleLogger log = Module.log;
final Module module = this.module;
log.trace("Attempting to define class %s in %s", name, module);
// Ensure that the package is loaded
final int lastIdx = name.lastIndexOf('.');
if (lastIdx != -1) {
// there's a package name; get the Package for it
final String packageName = name.substring(0, lastIdx);
synchronized (this) {
Package pkg = findLoadedPackage(packageName);
if (pkg == null) {
try {
pkg = definePackage(packageName, resourceLoader.getPackageSpec(packageName));
} catch (IOException e) {
pkg = definePackage(packageName, null);
}
}
// Check sealing
if (pkg.isSealed() && ! pkg.isSealed(classSpec.getCodeSource().getLocation())) {
log.trace("Detected a sealing violation (attempt to define class %s in sealed package %s in %s)", name, packageName, module);
// use the same message as the JDK
throw new SecurityException("sealing violation: package " + packageName + " is sealed");
}
}
}
final Class<?> newClass;
try {
byte[] bytes = classSpec.getBytes();
try {
if (transformer != null) {
try {
// todo: support protection domain
bytes = transformer.transform(this, name.replace('.', '/'), null, null, bytes);
} catch (Exception e) {
ClassFormatError error = new ClassFormatError(e.getMessage());
error.initCause(e);
throw error;
}
}
final long start = Metrics.getCurrentCPUTime();
newClass = doDefineOrLoadClass(name, bytes, 0, bytes.length, classSpec.getCodeSource());
module.getModuleLoader().addClassLoadTime(Metrics.getCurrentCPUTime() - start);
log.classDefined(name, module);
} catch (NoClassDefFoundError e) {
// Prepend the current class name, so that transitive class definition issues are clearly expressed
final LinkageError ne = new LinkageError("Failed to link " + name.replace('.', '/') + " (" + module + ")");
ne.initCause(e);
throw ne;
}
} catch (Error e) {
log.classDefineFailed(e, name, module);
throw e;
} catch (RuntimeException e) {
log.classDefineFailed(e, name, module);
throw e;
}
final AssertionSetting setting = classSpec.getAssertionSetting();
if (setting != AssertionSetting.INHERIT) {
setClassAssertionStatus(name, setting == AssertionSetting.ENABLED);
}
return newClass;
}
/**
* A hook which is invoked before a class is defined.
*
* @param classSpec the class spec of the defined class
* @param className the class to be defined
*/
@SuppressWarnings("unused")
protected void preDefine(ClassSpec classSpec, String className) {
}
/**
* A hook which is invoked after a class is defined.
*
* @param classSpec the class spec of the defined class
* @param definedClass the class that was defined
*/
@SuppressWarnings("unused")
protected void postDefine(ClassSpec classSpec, Class<?> definedClass) {
}
/**
* Define a package from a package spec.
*
* @param name the package name
* @param spec the package specification
* @return the new package
*/
private Package definePackage(final String name, final PackageSpec spec) {
final Module module = this.module;
final ModuleLogger log = Module.log;
log.trace("Attempting to define package %s in %s", name, module);
final Package pkg;
if (spec == null) {
pkg = definePackage(name, null, null, null, null, null, null, null);
} else {
pkg = definePackage(name, spec.getSpecTitle(), spec.getSpecVersion(), spec.getSpecVendor(), spec.getImplTitle(), spec.getImplVersion(), spec.getImplVendor(), spec.getSealBase());
final AssertionSetting setting = spec.getAssertionSetting();
if (setting != AssertionSetting.INHERIT) {
setPackageAssertionStatus(name, setting == AssertionSetting.ENABLED);
}
}
log.trace("Defined package %s in %s", name, module);
return pkg;
}
/**
* Find a library from one of the resource loaders.
*
* @param libname the library name
* @return the full absolute path to the library
*/
@Override
protected final String findLibrary(final String libname) {
final ModuleLogger log = Module.log;
log.trace("Attempting to load native library %s from %s", libname, module);
for (ResourceLoaderSpec loader : paths.getSourceList(NO_RESOURCE_LOADERS)) {
final String library = loader.getResourceLoader().getLibrary(libname);
if (library != null) {
return library;
}
}
return null;
}
/** {@inheritDoc} */
@Override
public final URL findResource(final String name, final boolean exportsOnly) {
return module.getResource(name);
}
/** {@inheritDoc} */
@Override
public final Enumeration<URL> findResources(final String name, final boolean exportsOnly) throws IOException {
return module.getResources(name);
}
/** {@inheritDoc} */
@Override
public final InputStream findResourceAsStream(final String name, boolean exportsOnly) {
try {
final URL resource = findResource(name, exportsOnly);
return resource == null ? null : resource.openStream();
} catch (IOException e) {
return null;
}
}
/**
* Get the module for this class loader.
*
* @return the module
*/
public final Module getModule() {
return module;
}
/**
* Get a string representation of this class loader.
*
* @return the string
*/
@Override
public final String toString() {
return getClass().getSimpleName() + " for " + module;
}
Set<String> getPaths() {
return paths.getAllPaths().keySet();
}
/** {@inheritDoc} */
@Override
protected final PermissionCollection getPermissions(final CodeSource codesource) {
return super.getPermissions(codesource);
}
/** {@inheritDoc} */
@Override
protected final Package definePackage(final String name, final String specTitle, final String specVersion, final String specVendor, final String implTitle, final String implVersion, final String implVendor, final URL sealBase) throws IllegalArgumentException {
return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor, sealBase);
}
/** {@inheritDoc} */
@Override
protected final Package getPackageByName(final String name) {
Package loaded = findLoadedPackage(name);
if (loaded != null) {
return loaded;
}
return module.getPackage(name);
}
/** {@inheritDoc} */
@Override
protected final Package[] getPackages() {
return module.getPackages();
}
/** {@inheritDoc} */
@Override
public final void setDefaultAssertionStatus(final boolean enabled) {
super.setDefaultAssertionStatus(enabled);
}
/** {@inheritDoc} */
@Override
public final void setPackageAssertionStatus(final String packageName, final boolean enabled) {
super.setPackageAssertionStatus(packageName, enabled);
}
/** {@inheritDoc} */
@Override
public final void setClassAssertionStatus(final String className, final boolean enabled) {
super.setClassAssertionStatus(className, enabled);
}
/** {@inheritDoc} */
@Override
public final void clearAssertionStatus() {
super.clearAssertionStatus();
}
/** {@inheritDoc} */
@Override
public final int hashCode() {
return super.hashCode();
}
/** {@inheritDoc} */
@Override
public final boolean equals(final Object obj) {
return super.equals(obj);
}
/** {@inheritDoc} */
@Override
protected final Object clone() throws CloneNotSupportedException {
return super.clone();
}
/** {@inheritDoc} */
@Override
protected final void finalize() throws Throwable {
super.finalize();
}
ResourceLoader[] getResourceLoaders() {
final ResourceLoaderSpec[] specs = paths.getSourceList(NO_RESOURCE_LOADERS);
final int length = specs.length;
final ResourceLoader[] loaders = new ResourceLoader[length];
for (int i = 0; i < length; i++) {
loaders[i] = specs[i].getResourceLoader();
}
return loaders;
}
/**
* An opaque configuration used internally to create a module class loader.
*
* @apiviz.exclude
*/
protected static final class Configuration {
private final Module module;
private final AssertionSetting assertionSetting;
private final ResourceLoaderSpec[] resourceLoaders;
private final ClassFileTransformer transformer;
Configuration(final Module module, final AssertionSetting assertionSetting, final ResourceLoaderSpec[] resourceLoaders, final ClassFileTransformer transformer) {
this.module = module;
this.assertionSetting = assertionSetting;
this.resourceLoaders = resourceLoaders;
this.transformer = transformer;
}
Module getModule() {
return module;
}
AssertionSetting getAssertionSetting() {
return assertionSetting;
}
ResourceLoaderSpec[] getResourceLoaders() {
return resourceLoaders;
}
ClassFileTransformer getTransformer() {
return transformer;
}
}
}
| true | true | public Class<?> loadClassLocal(final String className, final boolean resolve) throws ClassNotFoundException {
final ModuleLogger log = Module.log;
final Module module = this.module;
log.trace("Finding local class %s from %s", className, module);
// Check if we have already loaded it..
Class<?> loadedClass = findLoadedClass(className);
if (loadedClass != null) {
log.trace("Found previously loaded %s from %s", loadedClass, module);
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
final Map<String, List<ResourceLoader>> paths = this.paths.getAllPaths();
log.trace("Loading class %s locally from %s", className, module);
String pathOfClass = Module.pathOfClass(className);
final List<ResourceLoader> loaders = paths.get(pathOfClass);
if (loaders == null) {
// no loaders for this path
return null;
}
// Check to see if we can define it locally it
ClassSpec classSpec;
ResourceLoader resourceLoader;
try {
if (loaders.size() > 0) {
String fileName = Module.fileNameOfClass(className);
for (ResourceLoader loader : loaders) {
classSpec = loader.getClassSpec(fileName);
if (classSpec != null) {
resourceLoader = loader;
try {
preDefine(classSpec, className);
}
catch (Throwable th) {
throw new ClassNotFoundException("Failed to preDefine class: " + className, th);
}
final Class<?> clazz = defineClass(className, classSpec, resourceLoader);
try {
postDefine(classSpec, clazz);
}
catch (Throwable th) {
throw new ClassNotFoundException("Failed to postDefine class: " + className, th);
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
}
}
}
} catch (IOException e) {
throw new ClassNotFoundException(className, e);
} catch (RuntimeException e) {
log.trace(e, "Unexpected runtime exception in module loader");
throw new ClassNotFoundException(className, e);
} catch (Error e) {
log.trace(e, "Unexpected error in module loader");
throw new ClassNotFoundException(className, e);
}
log.trace("No local specification found for class %s in %s", className, module);
return null;
}
| public Class<?> loadClassLocal(final String className, final boolean resolve) throws ClassNotFoundException {
final ModuleLogger log = Module.log;
final Module module = this.module;
log.trace("Finding local class %s from %s", className, module);
// Check if we have already loaded it..
Class<?> loadedClass = findLoadedClass(className);
if (loadedClass != null) {
log.trace("Found previously loaded %s from %s", loadedClass, module);
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
final Map<String, List<ResourceLoader>> paths = this.paths.getAllPaths();
log.trace("Loading class %s locally from %s", className, module);
String pathOfClass = Module.pathOfClass(className);
final List<ResourceLoader> loaders = paths.get(pathOfClass);
if (loaders == null) {
// no loaders for this path
return null;
}
// Check to see if we can define it locally it
ClassSpec classSpec;
ResourceLoader resourceLoader;
try {
if (loaders.size() > 0) {
String fileName = Module.fileNameOfClass(className);
for (ResourceLoader loader : loaders) {
classSpec = loader.getClassSpec(fileName);
if (classSpec != null) {
resourceLoader = loader;
try {
preDefine(classSpec, className);
}
catch (Throwable th) {
throw new ClassNotFoundException("Failed to preDefine class: " + className, th);
}
final Class<?> clazz = defineClass(className, classSpec, resourceLoader);
try {
postDefine(classSpec, clazz);
}
catch (Throwable th) {
throw new ClassNotFoundException("Failed to postDefine class: " + className, th);
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
}
}
}
} catch (IOException e) {
throw new ClassNotFoundException(className, e);
} catch (RuntimeException e) {
log.trace(e, "Unexpected runtime exception in module loader");
throw new ClassNotFoundException(className, e);
} catch (Error e) {
log.trace(e, "Unexpected error in module loader");
throw e;
}
log.trace("No local specification found for class %s in %s", className, module);
return null;
}
|
diff --git a/modules/ota-library/src/test/java/com/sap/prd/mobile/ios/ota/lib/OtaBuildHtmlGeneratorTest.java b/modules/ota-library/src/test/java/com/sap/prd/mobile/ios/ota/lib/OtaBuildHtmlGeneratorTest.java
index f6e90bf..486d36d 100644
--- a/modules/ota-library/src/test/java/com/sap/prd/mobile/ios/ota/lib/OtaBuildHtmlGeneratorTest.java
+++ b/modules/ota-library/src/test/java/com/sap/prd/mobile/ios/ota/lib/OtaBuildHtmlGeneratorTest.java
@@ -1,165 +1,165 @@
/*
* #%L
* Over-the-air deployment library
* %%
* Copyright (C) 2012 SAP AG
* %%
* 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.
* #L%
*/
package com.sap.prd.mobile.ios.ota.lib;
import static com.sap.prd.mobile.ios.ota.lib.OtaBuildHtmlGenerator.BUNDLE_IDENTIFIER;
import static com.sap.prd.mobile.ios.ota.lib.OtaBuildHtmlGenerator.BUNDLE_VERSION;
import static com.sap.prd.mobile.ios.ota.lib.OtaBuildHtmlGenerator.IPA_CLASSIFIER;
import static com.sap.prd.mobile.ios.ota.lib.OtaBuildHtmlGenerator.OTA_CLASSIFIER;
import static com.sap.prd.mobile.ios.ota.lib.OtaBuildHtmlGenerator.TITLE;
import static com.sap.prd.mobile.ios.ota.lib.TestUtils.assertContains;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.junit.Test;
import com.sap.prd.mobile.ios.ota.lib.OtaBuildHtmlGenerator.Parameters;
public class OtaBuildHtmlGeneratorTest
{
private final static String HTML_SERVICE = "http://apple-ota.wdf.sap.corp:8080/ota-service/HTML";
private final static String title = "MyApp";
private final static String bundleIdentifier = "com.sap.xyz.MyApp";
private final static String bundleVersion = "1.0.2";
private final static String ipaClassifier = "ipaClassifier";
private final static String otaClassifier = "otaClassifier";
private final static String googleAnalyticsId = "googleAnalyticsId";
@Test
public void testCorrectValues() throws IOException
{
URL htmlServiceUrl = new URL(HTML_SERVICE);
String generated = OtaBuildHtmlGenerator.getInstance().generate(
new Parameters(htmlServiceUrl, title, bundleIdentifier, bundleVersion, ipaClassifier, otaClassifier,
googleAnalyticsId));
assertContains(TITLE + "=" + title, generated);
assertContains(BUNDLE_IDENTIFIER + "=" + bundleIdentifier, generated);
assertContains(BUNDLE_VERSION + "=" + bundleVersion, generated);
assertContains(IPA_CLASSIFIER + "=" + ipaClassifier, generated);
assertContains(OTA_CLASSIFIER + "=" + otaClassifier, generated);
assertContains(
- "<iframe src=\""
+ "<iframe id=\"iframe\" src=\""
+ HTML_SERVICE
+ "?title=MyApp&bundleIdentifier=com.sap.xyz.MyApp&bundleVersion=1.0.2&ipaClassifier=ipaClassifier&otaClassifier=otaClassifier\"",
generated);
assertContains("<form action=\"" + HTML_SERVICE + "\"", generated);
assertContains("<input type=\"hidden\" name=\"title\" value=\"MyApp\">", generated);
assertContains("<input type=\"hidden\" name=\"bundleIdentifier\" value=\"com.sap.xyz.MyApp\">", generated);
assertContains("<input type=\"hidden\" name=\"bundleVersion\" value=\"1.0.2\">", generated);
assertContains("<input type=\"hidden\" name=\"ipaClassifier\" value=\"ipaClassifier\">", generated);
assertContains("<input type=\"hidden\" name=\"otaClassifier\" value=\"otaClassifier\">", generated);
}
@Test
public void testAlternativeTemplateByResource() throws IOException
{
URL htmlServiceUrl = new URL(HTML_SERVICE);
String generated = OtaBuildHtmlGenerator.getNewInstance("alternativeBuildTemplate.html").generate(
new Parameters(htmlServiceUrl, title, bundleIdentifier, bundleVersion, ipaClassifier, otaClassifier,
googleAnalyticsId));
checkAlternativeResult(generated);
}
@Test
public void testAlternativeTemplateByFile() throws IOException
{
URL htmlServiceUrl = new URL(HTML_SERVICE);
String generated = OtaBuildHtmlGenerator.getNewInstance("./src/test/resources/alternativeBuildTemplate.html")
.generate(
new Parameters(htmlServiceUrl, title, bundleIdentifier, bundleVersion, ipaClassifier, otaClassifier,
googleAnalyticsId));
checkAlternativeResult(generated);
}
private void checkAlternativeResult(String generated)
{
assertContains(TITLE + "=" + title, generated);
assertContains("ALTERNATIVE HTML BUILD TEMPLATE", generated);
assertContains(BUNDLE_IDENTIFIER + "=" + bundleIdentifier, generated);
assertContains(BUNDLE_VERSION + "=" + bundleVersion, generated);
assertContains(IPA_CLASSIFIER + "=" + ipaClassifier, generated);
assertContains(OTA_CLASSIFIER + "=" + otaClassifier, generated);
assertContains(
"<a href=\""
+ HTML_SERVICE
+ "?title=MyApp&bundleIdentifier=com.sap.xyz.MyApp&bundleVersion=1.0.2&ipaClassifier=ipaClassifier&otaClassifier=otaClassifier\"",
generated);
}
@Test
public void testProject() throws MalformedURLException, IOException
{
URL htmlServiceUrl = new URL(HTML_SERVICE);
String generated = OtaBuildHtmlGenerator.getInstance().generate(
new Parameters(htmlServiceUrl, "MyApp", "com.sap.tip.production.ios.ota.test", "1.0", "Production-iphoneos",
"OTA-Installer", googleAnalyticsId));
System.out.println(generated);
}
public void getNewInstanceCorrectResource() throws FileNotFoundException
{
assertEquals(OtaBuildHtmlGenerator.DEFAULT_TEMPLATE,
OtaBuildHtmlGenerator.getNewInstance(OtaBuildHtmlGenerator.DEFAULT_TEMPLATE).template.getName());
}
@Test
public void getNewInstanceNull() throws FileNotFoundException
{
assertEquals(OtaBuildHtmlGenerator.DEFAULT_TEMPLATE,
OtaBuildHtmlGenerator.getNewInstance(null).template.getName());
}
@Test
public void getNewInstanceEmpty() throws FileNotFoundException
{
assertEquals(OtaBuildHtmlGenerator.DEFAULT_TEMPLATE,
OtaBuildHtmlGenerator.getNewInstance("").template.getName());
}
@Test(expected = ResourceNotFoundException.class)
public void getNewInstanceWrongResource() throws FileNotFoundException
{
assertEquals(OtaBuildHtmlGenerator.DEFAULT_TEMPLATE,
OtaBuildHtmlGenerator.getNewInstance("doesnotexist.htm").template.getName());
}
@Test
public void getNewInstanceCorrectFile() throws FileNotFoundException
{
assertEquals("alternativeBuildTemplate.html",
OtaBuildHtmlGenerator.getNewInstance(new File("./src/test/resources/alternativeBuildTemplate.html").getAbsolutePath()).template.getName());
}
@Test(expected = ResourceNotFoundException.class)
public void getNewInstanceWrongFile() throws FileNotFoundException
{
assertEquals(OtaBuildHtmlGenerator.DEFAULT_TEMPLATE,
OtaBuildHtmlGenerator.getNewInstance(new File("./doesnotexist.htm").getAbsolutePath()).template.getName());
}
}
| true | true | public void testCorrectValues() throws IOException
{
URL htmlServiceUrl = new URL(HTML_SERVICE);
String generated = OtaBuildHtmlGenerator.getInstance().generate(
new Parameters(htmlServiceUrl, title, bundleIdentifier, bundleVersion, ipaClassifier, otaClassifier,
googleAnalyticsId));
assertContains(TITLE + "=" + title, generated);
assertContains(BUNDLE_IDENTIFIER + "=" + bundleIdentifier, generated);
assertContains(BUNDLE_VERSION + "=" + bundleVersion, generated);
assertContains(IPA_CLASSIFIER + "=" + ipaClassifier, generated);
assertContains(OTA_CLASSIFIER + "=" + otaClassifier, generated);
assertContains(
"<iframe src=\""
+ HTML_SERVICE
+ "?title=MyApp&bundleIdentifier=com.sap.xyz.MyApp&bundleVersion=1.0.2&ipaClassifier=ipaClassifier&otaClassifier=otaClassifier\"",
generated);
assertContains("<form action=\"" + HTML_SERVICE + "\"", generated);
assertContains("<input type=\"hidden\" name=\"title\" value=\"MyApp\">", generated);
assertContains("<input type=\"hidden\" name=\"bundleIdentifier\" value=\"com.sap.xyz.MyApp\">", generated);
assertContains("<input type=\"hidden\" name=\"bundleVersion\" value=\"1.0.2\">", generated);
assertContains("<input type=\"hidden\" name=\"ipaClassifier\" value=\"ipaClassifier\">", generated);
assertContains("<input type=\"hidden\" name=\"otaClassifier\" value=\"otaClassifier\">", generated);
}
| public void testCorrectValues() throws IOException
{
URL htmlServiceUrl = new URL(HTML_SERVICE);
String generated = OtaBuildHtmlGenerator.getInstance().generate(
new Parameters(htmlServiceUrl, title, bundleIdentifier, bundleVersion, ipaClassifier, otaClassifier,
googleAnalyticsId));
assertContains(TITLE + "=" + title, generated);
assertContains(BUNDLE_IDENTIFIER + "=" + bundleIdentifier, generated);
assertContains(BUNDLE_VERSION + "=" + bundleVersion, generated);
assertContains(IPA_CLASSIFIER + "=" + ipaClassifier, generated);
assertContains(OTA_CLASSIFIER + "=" + otaClassifier, generated);
assertContains(
"<iframe id=\"iframe\" src=\""
+ HTML_SERVICE
+ "?title=MyApp&bundleIdentifier=com.sap.xyz.MyApp&bundleVersion=1.0.2&ipaClassifier=ipaClassifier&otaClassifier=otaClassifier\"",
generated);
assertContains("<form action=\"" + HTML_SERVICE + "\"", generated);
assertContains("<input type=\"hidden\" name=\"title\" value=\"MyApp\">", generated);
assertContains("<input type=\"hidden\" name=\"bundleIdentifier\" value=\"com.sap.xyz.MyApp\">", generated);
assertContains("<input type=\"hidden\" name=\"bundleVersion\" value=\"1.0.2\">", generated);
assertContains("<input type=\"hidden\" name=\"ipaClassifier\" value=\"ipaClassifier\">", generated);
assertContains("<input type=\"hidden\" name=\"otaClassifier\" value=\"otaClassifier\">", generated);
}
|
diff --git a/trunk/src/Background/Background.java b/trunk/src/Background/Background.java
index 9a5bef2..7264009 100644
--- a/trunk/src/Background/Background.java
+++ b/trunk/src/Background/Background.java
@@ -1,61 +1,61 @@
package Background;
import GUIComponents.BaseFrame;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Random;
/**
*
* @author Jere
*/
public class Background {
private ArrayList stars;
int amount, height, width;
public Background(int amount) {
this.amount = amount;
stars = new ArrayList();
width = BaseFrame.getWindowSize().width;
height = BaseFrame.getWindowSize().height;
addRandomStars(amount);
}
private void addRandomStars(int amount) {
for (int i = 0; i < amount; i++)
{
stars.add(new Star(new Point2D.Double(getRandom(width),getRandom(height))));
}
}
private int getRandom(int max)
{
Random r = new Random();
return r.nextInt(max);
}
public void draw(Graphics2D g2)
{
for (int j = 0; j < stars.size(); j++)
{
Star star = (Star)stars.get(j);
g2.setColor(star.getColor());
g2.fill(star.getShape());
}
}
public void tick()
{
for (int k = 0; k < stars.size(); k++)
{
Star star = (Star)stars.get(k);
- star.setCoords(new Point2D.Double(star.getCoords().getX(),star.getCoords().getY()-3));
- if (star.getCoords().getY() < 0)
+ star.setCoords(new Point2D.Double(star.getCoords().getX(),star.getCoords().getY()+5));
+ if (star.getCoords().getY() > height)
{
- star.setCoords(new Point2D.Double(getRandom(width),height));
+ star.setCoords(new Point2D.Double(getRandom(width),0));
}
}
}
}
| false | true | public void tick()
{
for (int k = 0; k < stars.size(); k++)
{
Star star = (Star)stars.get(k);
star.setCoords(new Point2D.Double(star.getCoords().getX(),star.getCoords().getY()-3));
if (star.getCoords().getY() < 0)
{
star.setCoords(new Point2D.Double(getRandom(width),height));
}
}
}
| public void tick()
{
for (int k = 0; k < stars.size(); k++)
{
Star star = (Star)stars.get(k);
star.setCoords(new Point2D.Double(star.getCoords().getX(),star.getCoords().getY()+5));
if (star.getCoords().getY() > height)
{
star.setCoords(new Point2D.Double(getRandom(width),0));
}
}
}
|
diff --git a/src/net/sf/freecol/server/generator/TerrainGenerator.java b/src/net/sf/freecol/server/generator/TerrainGenerator.java
index b5d28c989..70636c8db 100644
--- a/src/net/sf/freecol/server/generator/TerrainGenerator.java
+++ b/src/net/sf/freecol/server/generator/TerrainGenerator.java
@@ -1,536 +1,542 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.server.generator;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
import net.sf.freecol.FreeCol;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Map.Direction;
import net.sf.freecol.common.model.Region;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileType;
import net.sf.freecol.common.model.Map.Position;
/**
* Class for making a <code>Map</code> based upon a land map.
*/
public class TerrainGenerator {
private static final Logger logger = Logger.getLogger(TerrainGenerator.class.getName());
private static final Direction[] directions = Map.getDirectionArray();
private final MapGeneratorOptions mapGeneratorOptions;
private final Random random = new Random();
private TileType ocean = FreeCol.getSpecification().getTileType("model.tile.ocean");
public ArrayList<ArrayList<TileType>> latTileTypes = new ArrayList<ArrayList<TileType>>();
/**
* Creates a new <code>TerrainGenerator</code>.
*
* @see #createMap
*/
public TerrainGenerator(MapGeneratorOptions mapGeneratorOptions) {
this.mapGeneratorOptions = mapGeneratorOptions;
}
/**
* Creates a <code>Map</code> for the given <code>Game</code>.
*
* The <code>Map</code> is added to the <code>Game</code> after
* it is created.
*
* @param game The game.
* @param landMap Determines whether there should be land
* or ocean on a given tile. This array also
* specifies the size of the map that is going
* to be created.
* @see Map
*/
public void createMap(Game game, boolean[][] landMap) {
createMap(game, null, landMap);
}
/**
* Creates a <code>Map</code> for the given <code>Game</code>.
*
* The <code>Map</code> is added to the <code>Game</code> after
* it is created.
*
* @param game The game.
* @param importGame The game to import information form.
* @param landMap Determines whether there should be land
* or ocean on a given tile. This array also
* specifies the size of the map that is going
* to be created.
* @see Map
*/
public void createMap(Game game, Game importGame, boolean[][] landMap) {
final int width = landMap.length;
final int height = landMap[0].length;
final boolean importTerrain = (importGame != null) && getMapGeneratorOptions().getBoolean(MapGeneratorOptions.IMPORT_TERRAIN);
final boolean importBonuses = (importGame != null) && getMapGeneratorOptions().getBoolean(MapGeneratorOptions.IMPORT_BONUSES);
final boolean importLandMap = (importGame != null) && getMapGeneratorOptions().getBoolean(MapGeneratorOptions.IMPORT_LAND_MAP);
int forestChance = getMapGeneratorOptions().getPercentageOfForests();
Tile[][] tiles = new Tile[width][height];
for (int y = 0; y < height; y++) {
int latitude = (Math.min(y, (height-1) - y) * 200) / height; // lat=0 for poles; lat=100 for equator
for (int x = 0; x < width; x++) {
Tile t;
if (importTerrain && importGame.getMap().isValid(x, y)) {
Tile importTile = importGame.getMap().getTile(x, y);
if (importLandMap || importTile.isLand() == landMap[x][y]) {
t = new Tile(game, importTile.getType(), x, y);
// TileItemContainer copies everything including Resource unless importBonuses == false
t.getTileItemContainer().copyFrom(importTile.getTileItemContainer(), importBonuses);
if (!importBonuses) {
// In which case, we may add a Bonus Resource
perhapsAddBonus(t, landMap);
}
} else {
t = createTile(game, x, y, landMap, latitude, forestChance);
}
} else {
t = createTile(game, x, y, landMap, latitude, forestChance);
}
tiles[x][y] = t;
}
}
Map map = new Map(game, tiles);
game.setMap(map);
if (!importTerrain) {
createHighSeas(map);
createMountains(map);
createRivers(map);
}
}
private Tile createTile(Game game, int x, int y, boolean[][] landMap, int latitude, int forestChance) {
Tile t;
if (landMap[x][y]) {
t = new Tile(game, getRandomLandTileType(latitude, forestChance), x, y);
} else {
t = new Tile(game, ocean, x, y);
}
perhapsAddBonus(t, landMap);
return t;
}
/**
* Adds a terrain bonus with a probability determined by the
* <code>MapGeneratorOptions</code>.
*
* @param t The Tile.
* @param landMap The landMap.
*/
private void perhapsAddBonus(Tile t, boolean[][] landMap) {
if (t.isLand()) {
if (random.nextInt(100) < getMapGeneratorOptions().getPercentageOfBonusTiles()) {
// Create random Bonus Resource
t.setResource(t.getType().getRandomResourceType());
}
} else {
int adjacentLand = 0;
for (Direction direction : Direction.values()) {
Position mp = Map.getAdjacent(t.getPosition(), direction);
final boolean valid = Map.isValid(mp, landMap.length, landMap[0].length);
if (valid && landMap[mp.getX()][mp.getY()]) {
adjacentLand++;
}
}
if (adjacentLand > 1 && random.nextInt(10 - adjacentLand) == 0) {
t.setResource(t.getType().getRandomResourceType());
}
}
}
/**
* Gets the <code>MapGeneratorOptions</code>.
* @return The <code>MapGeneratorOptions</code> being used
* when creating terrain.
*/
private MapGeneratorOptions getMapGeneratorOptions() {
return mapGeneratorOptions;
}
/**
* Gets a random land tile type based on the given percentage.
*
* @param latitude The location of the tile relative to the north/south poles and equator,
* 100% is the mid-section of the map (equator)
* 0% is on the top/bottom of the map (poles).
* @param forestChance The percentage chance of forests in this area
*/
private TileType getRandomLandTileType(int latitudePercent, int forestChance) {
// latRanges correspond to 0,1,2,3 from TileType.latitude (100-0)
int[] latRanges = { 75, 50, 25, 0 };
// altRanges correspond to 1,2,3 from TileType.altitude (1-10)
int[] altRanges = { 6, 8, 10};
// Create the lists of TileType the first time you use it
while (latTileTypes.size() < latRanges.length) {
latTileTypes.add(new ArrayList<TileType>());
}
// convert the latitude percentage into a classification index
// latitudeIndex = 0 is for the equator
// latitudeIndex = 3 is for the poles
int latitudeIndex = latRanges.length - 1;
for (int i = 0; i < latRanges.length; i++) {
if (latRanges[i] < latitudePercent) {
latitudeIndex = i;
break;
}
}
// Fill the list of latitude TileTypes the first time you use it
if (latTileTypes.get(latitudeIndex).size() == 0) {
for (TileType tileType : FreeCol.getSpecification().getTileTypeList()) {
+ if (tileType.getId().equals("model.tile.hills") ||
+ tileType.getId().equals("model.tile.mountains")) {
+ // do not generate hills or mountains at this time
+ // they will be created explicitly later
+ continue;
+ }
if (!tileType.isWater() && tileType.withinRange(TileType.LATITUDE, latitudeIndex)) {
// Within range, add it
latTileTypes.get(latitudeIndex).add(tileType);
}
}
if (latTileTypes.get(latitudeIndex).size() == 0) {
// If it is still 0 after adding all relevant types, throw error
throw new RuntimeException("No TileType within latitude == " + latitudeIndex);
}
}
// Scope the type of tiles to be used and choose one
TileType chosen = null;
//List<TileType> acceptable = latTileTypes.get(latitudeIndex).clone();
List<TileType> acceptable = new ArrayList<TileType>();
acceptable.addAll(latTileTypes.get(latitudeIndex));
// Choose based on altitude
int altitude = random.nextInt(10);
for (int i = 0; i < 3; i++) {
if (altRanges[i] > altitude) {
altitude = i;
break;
}
}
Iterator<TileType> it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (t.withinRange(TileType.ALTITUDE, altitude)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
// Choose based on forested/unforested
if (chosen == null) {
boolean forested = random.nextInt(100) < forestChance;
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (t.isForested() != forested) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// Choose based on humidity - later use MapGeneratorOptions to help define these
if (chosen == null) {
int humidity = random.nextInt(7) - 3; // To get -3 to 3, 0 inclusive
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (!t.withinRange(TileType.HUMIDITY, humidity)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// Choose based on temperature - later use MapGeneratorOptions to help define these
if (chosen == null) {
int temperature = random.nextInt(7) - 3; // To get -3 to 3, 0 inclusive
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (!t.withinRange(TileType.TEMPERATURE, temperature)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// All scoped, if none have been selected by elimination, randomly choose one
if (chosen == null) {
chosen = acceptable.get(random.nextInt(acceptable.size()));
}
return chosen;
}
/**
* Places "high seas"-tiles on the border of the given map.
* @param map The <code>Map</code> to create high seas on.
*/
private void createHighSeas(Map map) {
createHighSeas(map,
getMapGeneratorOptions().getDistLandHighSea(),
getMapGeneratorOptions().getMaxDistToEdge()
);
}
/**
* Places "high seas"-tiles on the border of the given map.
*
* All other tiles previously of type {@link Tile#HIGH_SEAS}
* will be set to {@link Tile#OCEAN}.
*
* @param map The <code>Map</code> to create high seas on.
* @param distToLandFromHighSeas The distance between the land
* and the high seas (given in tiles).
* @param maxDistanceToEdge The maximum distance a high sea tile
* can have from the edge of the map.
*/
public static void determineHighSeas(Map map,
int distToLandFromHighSeas,
int maxDistanceToEdge) {
TileType ocean = null, highSeas = null;
for (TileType t : FreeCol.getSpecification().getTileTypeList()) {
if (t.isWater()) {
if (t.canSailToEurope()) {
if (highSeas == null) {
highSeas = t;
if (ocean != null) {
break;
}
}
} else {
if (ocean == null) {
ocean = t;
if (highSeas != null) {
break;
}
}
}
}
}
if (highSeas == null || ocean == null) {
throw new RuntimeException("Both Ocean and HighSeas TileTypes must be defined");
}
for (Tile t : map.getAllTiles()) {
if (t.getType() == highSeas) {
t.setType(ocean);
}
}
createHighSeas(map, distToLandFromHighSeas, maxDistanceToEdge);
}
/**
* Places "high seas"-tiles on the border of the given map.
*
* @param map The <code>Map</code> to create high seas on.
* @param distToLandFromHighSeas The distance between the land
* and the high seas (given in tiles).
* @param maxDistanceToEdge The maximum distance a high sea tile
* can have from the edge of the map.
*/
private static void createHighSeas(Map map,
int distToLandFromHighSeas,
int maxDistanceToEdge) {
if (distToLandFromHighSeas < 0
|| maxDistanceToEdge < 0) {
throw new IllegalArgumentException("The integer arguments cannot be negative.");
}
TileType highSeas = null;
for (TileType t : FreeCol.getSpecification().getTileTypeList()) {
if (t.isWater()) {
if (t.canSailToEurope()) {
highSeas = t;
break;
}
}
}
if (highSeas == null) {
throw new RuntimeException("HighSeas TileType is defined by the 'sail-to-europe' attribute");
}
Region pacific = map.getRegion("model.region.pacific");
Region northPacific = map.getRegion("model.region.northPacific");
northPacific.setParent(pacific);
Region southPacific = map.getRegion("model.region.southPacific");
southPacific.setParent(pacific);
Region atlantic = map.getRegion("model.region.atlantic");
Region northAtlantic = map.getRegion("model.region.northAtlantic");
northAtlantic.setParent(atlantic);
Region southAtlantic = map.getRegion("model.region.southAtlantic");
southAtlantic.setParent(atlantic);
for (int y = 0; y < map.getHeight(); y++) {
for (int x=0; x<maxDistanceToEdge &&
x<map.getWidth() &&
!map.isLandWithinDistance(x, y, distToLandFromHighSeas); x++) {
if (map.isValid(x, y)) {
map.getTile(x, y).setType(highSeas);
if (y < map.getHeight() / 2) {
map.getTile(x, y).setRegion(northPacific);
} else {
map.getTile(x, y).setRegion(southPacific);
}
}
}
for (int x=1; x<=maxDistanceToEdge &&
x<=map.getWidth()-1 &&
!map.isLandWithinDistance(map.getWidth()-x, y, distToLandFromHighSeas); x++) {
if (map.isValid(map.getWidth()-x, y)) {
map.getTile(map.getWidth()-x, y).setType(highSeas);
if (y < map.getHeight() / 2) {
map.getTile(map.getWidth()-x, y).setRegion(northAtlantic);
} else {
map.getTile(map.getWidth()-x, y).setRegion(southAtlantic);
}
}
}
}
}
/**
* Creates mountain ranges on the given map. The number and size
* of mountain ranges depends on the map size.
*
* @param map The map to use.
*/
private void createMountains(Map map) {
int maximumLength = Math.max(getMapGeneratorOptions().getWidth(), getMapGeneratorOptions().getHeight()) / 10;
int number = getMapGeneratorOptions().getNumberOfMountainTiles();
int counter = 0;
logger.info("Number of land tiles is " + getMapGeneratorOptions().getLand() +
", number of mountain tiles is " + number);
logger.fine("Maximum length of mountain ranges is " + maximumLength);
TileType hills = null, mountains = null;
for (TileType t : FreeCol.getSpecification().getTileTypeList()) {
if (t.getId().equals("model.tile.hills") && hills == null) {
hills = t;
if (mountains != null)
break;
} else if (t.getId().equals("model.tile.mountains") && mountains == null) {
mountains = t;
if (hills != null)
break;
}
}
if (hills == null || mountains == null) {
throw new RuntimeException("Both Hills and Mountains TileTypes must be defined");
}
for (int tries = 0; tries < 100; tries++) {
if (counter < number) {
Position p = map.getRandomLandPosition();
if (p != null && map.getTile(p).isLand()) {
Direction direction = directions[random.nextInt(8)];
int length = maximumLength - random.nextInt(maximumLength/2);
logger.info("Direction of mountain range is " + direction +
", length of mountain range is " + length);
for (int index = 0; index < length; index++) {
p = Map.getAdjacent(p, direction);
Tile t = map.getTile(p);
if (t != null && t.isLand()) {
t.setType(mountains);
counter++;
Iterator<Position> it = map.getCircleIterator(p, false, 1);
while (it.hasNext()) {
t = map.getTile(it.next());
if (t.isLand() &&
t.getType() != mountains) {
int r = random.nextInt(8);
if (r == 0) {
t.setType(mountains);
counter++;
} else if (r > 2) {
t.setType(hills);
}
}
}
}
}
// break;
}
}
}
logger.info("Added " + counter + " mountain tiles.");
}
/**
* Creates rivers on the given map. The number of rivers depends
* on the map size.
*
* @param map The map to create rivers on.
*/
private void createRivers(Map map) {
int number = getMapGeneratorOptions().getNumberOfRivers();
int counter = 0;
Hashtable<Position, River> riverMap = new Hashtable<Position, River>();
for (int i = 0; i < number; i++) {
River river = new River(map, riverMap);
for (int tries = 0; tries < 100; tries++) {
Position position = new Position(random.nextInt(map.getWidth()),
random.nextInt(map.getHeight()));
if (position.getY()==0 || position.getY()==map.getHeight()-1 ||
position.getY()==1 || position.getY()==map.getHeight()-2) {
// please no rivers in polar regions
continue;
}
if (riverMap.get(position) == null) {
// no river here yet
if (river.flowFromSource(position)) {
logger.fine("Created new river with length " + river.getLength());
counter++;
break;
} else {
logger.fine("Failed to generate river.");
}
}
}
}
logger.info("Created " + counter + " rivers of maximum " + number + ".");
}
}
| true | true | private TileType getRandomLandTileType(int latitudePercent, int forestChance) {
// latRanges correspond to 0,1,2,3 from TileType.latitude (100-0)
int[] latRanges = { 75, 50, 25, 0 };
// altRanges correspond to 1,2,3 from TileType.altitude (1-10)
int[] altRanges = { 6, 8, 10};
// Create the lists of TileType the first time you use it
while (latTileTypes.size() < latRanges.length) {
latTileTypes.add(new ArrayList<TileType>());
}
// convert the latitude percentage into a classification index
// latitudeIndex = 0 is for the equator
// latitudeIndex = 3 is for the poles
int latitudeIndex = latRanges.length - 1;
for (int i = 0; i < latRanges.length; i++) {
if (latRanges[i] < latitudePercent) {
latitudeIndex = i;
break;
}
}
// Fill the list of latitude TileTypes the first time you use it
if (latTileTypes.get(latitudeIndex).size() == 0) {
for (TileType tileType : FreeCol.getSpecification().getTileTypeList()) {
if (!tileType.isWater() && tileType.withinRange(TileType.LATITUDE, latitudeIndex)) {
// Within range, add it
latTileTypes.get(latitudeIndex).add(tileType);
}
}
if (latTileTypes.get(latitudeIndex).size() == 0) {
// If it is still 0 after adding all relevant types, throw error
throw new RuntimeException("No TileType within latitude == " + latitudeIndex);
}
}
// Scope the type of tiles to be used and choose one
TileType chosen = null;
//List<TileType> acceptable = latTileTypes.get(latitudeIndex).clone();
List<TileType> acceptable = new ArrayList<TileType>();
acceptable.addAll(latTileTypes.get(latitudeIndex));
// Choose based on altitude
int altitude = random.nextInt(10);
for (int i = 0; i < 3; i++) {
if (altRanges[i] > altitude) {
altitude = i;
break;
}
}
Iterator<TileType> it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (t.withinRange(TileType.ALTITUDE, altitude)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
// Choose based on forested/unforested
if (chosen == null) {
boolean forested = random.nextInt(100) < forestChance;
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (t.isForested() != forested) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// Choose based on humidity - later use MapGeneratorOptions to help define these
if (chosen == null) {
int humidity = random.nextInt(7) - 3; // To get -3 to 3, 0 inclusive
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (!t.withinRange(TileType.HUMIDITY, humidity)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// Choose based on temperature - later use MapGeneratorOptions to help define these
if (chosen == null) {
int temperature = random.nextInt(7) - 3; // To get -3 to 3, 0 inclusive
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (!t.withinRange(TileType.TEMPERATURE, temperature)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// All scoped, if none have been selected by elimination, randomly choose one
if (chosen == null) {
chosen = acceptable.get(random.nextInt(acceptable.size()));
}
return chosen;
}
| private TileType getRandomLandTileType(int latitudePercent, int forestChance) {
// latRanges correspond to 0,1,2,3 from TileType.latitude (100-0)
int[] latRanges = { 75, 50, 25, 0 };
// altRanges correspond to 1,2,3 from TileType.altitude (1-10)
int[] altRanges = { 6, 8, 10};
// Create the lists of TileType the first time you use it
while (latTileTypes.size() < latRanges.length) {
latTileTypes.add(new ArrayList<TileType>());
}
// convert the latitude percentage into a classification index
// latitudeIndex = 0 is for the equator
// latitudeIndex = 3 is for the poles
int latitudeIndex = latRanges.length - 1;
for (int i = 0; i < latRanges.length; i++) {
if (latRanges[i] < latitudePercent) {
latitudeIndex = i;
break;
}
}
// Fill the list of latitude TileTypes the first time you use it
if (latTileTypes.get(latitudeIndex).size() == 0) {
for (TileType tileType : FreeCol.getSpecification().getTileTypeList()) {
if (tileType.getId().equals("model.tile.hills") ||
tileType.getId().equals("model.tile.mountains")) {
// do not generate hills or mountains at this time
// they will be created explicitly later
continue;
}
if (!tileType.isWater() && tileType.withinRange(TileType.LATITUDE, latitudeIndex)) {
// Within range, add it
latTileTypes.get(latitudeIndex).add(tileType);
}
}
if (latTileTypes.get(latitudeIndex).size() == 0) {
// If it is still 0 after adding all relevant types, throw error
throw new RuntimeException("No TileType within latitude == " + latitudeIndex);
}
}
// Scope the type of tiles to be used and choose one
TileType chosen = null;
//List<TileType> acceptable = latTileTypes.get(latitudeIndex).clone();
List<TileType> acceptable = new ArrayList<TileType>();
acceptable.addAll(latTileTypes.get(latitudeIndex));
// Choose based on altitude
int altitude = random.nextInt(10);
for (int i = 0; i < 3; i++) {
if (altRanges[i] > altitude) {
altitude = i;
break;
}
}
Iterator<TileType> it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (t.withinRange(TileType.ALTITUDE, altitude)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
// Choose based on forested/unforested
if (chosen == null) {
boolean forested = random.nextInt(100) < forestChance;
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (t.isForested() != forested) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// Choose based on humidity - later use MapGeneratorOptions to help define these
if (chosen == null) {
int humidity = random.nextInt(7) - 3; // To get -3 to 3, 0 inclusive
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (!t.withinRange(TileType.HUMIDITY, humidity)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// Choose based on temperature - later use MapGeneratorOptions to help define these
if (chosen == null) {
int temperature = random.nextInt(7) - 3; // To get -3 to 3, 0 inclusive
it = acceptable.iterator();
while (it.hasNext()) {
TileType t = it.next();
if (!t.withinRange(TileType.TEMPERATURE, temperature)) {
if (acceptable.size() == 1) {
chosen = t;
break;
}
it.remove();
}
}
}
// All scoped, if none have been selected by elimination, randomly choose one
if (chosen == null) {
chosen = acceptable.get(random.nextInt(acceptable.size()));
}
return chosen;
}
|
diff --git a/src/org/servalproject/maps/services/BatteryLevelReceiver.java b/src/org/servalproject/maps/services/BatteryLevelReceiver.java
index 8d80618..1e04d68 100644
--- a/src/org/servalproject/maps/services/BatteryLevelReceiver.java
+++ b/src/org/servalproject/maps/services/BatteryLevelReceiver.java
@@ -1,99 +1,99 @@
/*
* Copyright (C) 2012 The Serval Project
*
* This file is part of the Serval Maps Software
*
* Serval Maps Software 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.
*
* This source code 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 source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.servalproject.maps.services;
import org.servalproject.maps.R;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
/**
* receives broadcasts about the battery level
*/
public class BatteryLevelReceiver extends BroadcastReceiver {
/*
* private class level constants
*/
private final boolean V_LOG = true;
private final String TAG = "BatteryLevelReceiver";
/*
* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
// check to see what level we're being informed about
if(V_LOG) {
Log.v(TAG, "onReceive method called");
}
// check on the action associated with the intent
if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW) == true) {
// notification that the battery is low
if(V_LOG) {
Log.v(TAG, "received notification that battery is low");
}
// shutdown the service
context.stopService(new Intent(context, org.servalproject.maps.services.CoreService.class));
// inform the user
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
mBuilder.setMessage(R.string.system_battery_status_low)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
} else if(intent.getAction().equals(Intent.ACTION_BATTERY_OKAY) == true) {
// notification that the battery is ok after being low
// restart the GPS
if(V_LOG) {
Log.v(TAG, "received notification that battery is ok");
}
- // shutdown the service
+ // start the service
context.startService(new Intent(context, org.servalproject.maps.services.CoreService.class));
// inform the user
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
mBuilder.setMessage(R.string.system_battery_status_ok)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
// check to see what level we're being informed about
if(V_LOG) {
Log.v(TAG, "onReceive method called");
}
// check on the action associated with the intent
if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW) == true) {
// notification that the battery is low
if(V_LOG) {
Log.v(TAG, "received notification that battery is low");
}
// shutdown the service
context.stopService(new Intent(context, org.servalproject.maps.services.CoreService.class));
// inform the user
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
mBuilder.setMessage(R.string.system_battery_status_low)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
} else if(intent.getAction().equals(Intent.ACTION_BATTERY_OKAY) == true) {
// notification that the battery is ok after being low
// restart the GPS
if(V_LOG) {
Log.v(TAG, "received notification that battery is ok");
}
// shutdown the service
context.startService(new Intent(context, org.servalproject.maps.services.CoreService.class));
// inform the user
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
mBuilder.setMessage(R.string.system_battery_status_ok)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
}
}
| public void onReceive(Context context, Intent intent) {
// check to see what level we're being informed about
if(V_LOG) {
Log.v(TAG, "onReceive method called");
}
// check on the action associated with the intent
if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW) == true) {
// notification that the battery is low
if(V_LOG) {
Log.v(TAG, "received notification that battery is low");
}
// shutdown the service
context.stopService(new Intent(context, org.servalproject.maps.services.CoreService.class));
// inform the user
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
mBuilder.setMessage(R.string.system_battery_status_low)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
} else if(intent.getAction().equals(Intent.ACTION_BATTERY_OKAY) == true) {
// notification that the battery is ok after being low
// restart the GPS
if(V_LOG) {
Log.v(TAG, "received notification that battery is ok");
}
// start the service
context.startService(new Intent(context, org.servalproject.maps.services.CoreService.class));
// inform the user
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
mBuilder.setMessage(R.string.system_battery_status_ok)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mAlert = mBuilder.create();
mAlert.show();
}
}
|
diff --git a/src/com/codedemigod/services/CDUSSDService.java b/src/com/codedemigod/services/CDUSSDService.java
index 7942acb..17c7c37 100644
--- a/src/com/codedemigod/services/CDUSSDService.java
+++ b/src/com/codedemigod/services/CDUSSDService.java
@@ -1,96 +1,96 @@
package com.codedemigod.services;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;
import android.os.PatternMatcher;
import android.os.RemoteException;
import android.util.Log;
import com.android.internal.telephony.IExtendedNetworkService;
import com.codedemigod.ussdinterceptor.R;
public class CDUSSDService extends Service{
private String TAG = CDUSSDService.class.getSimpleName();
private boolean mActive = false; //we will only activate this "USSD listener" when we want it
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_INSERT)){
//activity wishes to listen to USSD returns, so activate this
mActive = true;
Log.d(TAG, "activate ussd listener");
}
else if(intent.getAction().equals(Intent.ACTION_DELETE)){
mActive = false;
Log.d(TAG, "deactivate ussd listener");
}
}
};
private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub () {
public void clearMmiString() throws RemoteException {
Log.d(TAG, "called clear");
}
public void setMmiString(String number) throws RemoteException {
Log.d (TAG, "setMmiString:" + number);
}
public CharSequence getMmiRunningText() throws RemoteException {
if(mActive == true){
return null;
}
return "USSD Running";
}
public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
- Log.d(TAG, "get user messagedss " + text);
+ Log.d(TAG, "get user message " + text);
if(mActive == false){
//listener is still inactive, so return whatever we got
Log.d(TAG, "inactive " + text);
return text;
}
//listener is active, so broadcast data and suppress it from default behavior
//build data to send with intent for activity, format URI as per RFC 2396
Uri ussdDataUri = new Uri.Builder()
.scheme(getBaseContext().getString(R.string.uri_scheme))
.authority(getBaseContext().getString(R.string.uri_authority))
.path(getBaseContext().getString(R.string.uri_path))
.appendQueryParameter(getBaseContext().getString(R.string.uri_param_name), text.toString())
.build();
sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));
mActive = false;
return null;
}
};
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "called onbind");
//the insert/delete intents will be fired by activity to activate/deactivate listener since service cannot be stopped
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_INSERT);
filter.addAction(Intent.ACTION_DELETE);
filter.addDataScheme(getBaseContext().getString(R.string.uri_scheme));
filter.addDataAuthority(getBaseContext().getString(R.string.uri_authority), null);
filter.addDataPath(getBaseContext().getString(R.string.uri_path), PatternMatcher.PATTERN_LITERAL);
registerReceiver(receiver, filter);
return mBinder;
}
}
| true | true | public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
Log.d(TAG, "get user messagedss " + text);
if(mActive == false){
//listener is still inactive, so return whatever we got
Log.d(TAG, "inactive " + text);
return text;
}
//listener is active, so broadcast data and suppress it from default behavior
//build data to send with intent for activity, format URI as per RFC 2396
Uri ussdDataUri = new Uri.Builder()
.scheme(getBaseContext().getString(R.string.uri_scheme))
.authority(getBaseContext().getString(R.string.uri_authority))
.path(getBaseContext().getString(R.string.uri_path))
.appendQueryParameter(getBaseContext().getString(R.string.uri_param_name), text.toString())
.build();
sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));
mActive = false;
return null;
}
| public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
Log.d(TAG, "get user message " + text);
if(mActive == false){
//listener is still inactive, so return whatever we got
Log.d(TAG, "inactive " + text);
return text;
}
//listener is active, so broadcast data and suppress it from default behavior
//build data to send with intent for activity, format URI as per RFC 2396
Uri ussdDataUri = new Uri.Builder()
.scheme(getBaseContext().getString(R.string.uri_scheme))
.authority(getBaseContext().getString(R.string.uri_authority))
.path(getBaseContext().getString(R.string.uri_path))
.appendQueryParameter(getBaseContext().getString(R.string.uri_param_name), text.toString())
.build();
sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));
mActive = false;
return null;
}
|
diff --git a/hazelcast-heartattack/src/main/java/com/hazelcast/heartattack/Coach.java b/hazelcast-heartattack/src/main/java/com/hazelcast/heartattack/Coach.java
index 9a9971f..393d39e 100644
--- a/hazelcast-heartattack/src/main/java/com/hazelcast/heartattack/Coach.java
+++ b/hazelcast-heartattack/src/main/java/com/hazelcast/heartattack/Coach.java
@@ -1,283 +1,285 @@
package com.hazelcast.heartattack;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.XmlConfigBuilder;
import com.hazelcast.core.*;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import static com.hazelcast.heartattack.Utils.closeQuietly;
import static com.hazelcast.heartattack.Utils.getHeartAttackHome;
import static java.lang.String.format;
public abstract class Coach {
final static ILogger log = Logger.getLogger(Coach.class.getName());
public static final String KEY_COACH = "Coach";
public static final String COACH_HEART_ATTACK_QUEUE = "Coach:headCoachCount";
public final static File userDir = new File(System.getProperty("user.dir"));
public final static String classpath = System.getProperty("java.class.path");
public final static File heartAttackHome = getHeartAttackHome();
public final static File traineesHome = new File(getHeartAttackHome(), "trainees");
protected File coachHzFile;
protected volatile HazelcastInstance coachHz;
protected volatile HazelcastInstance traineeClient;
protected volatile IExecutorService traineeExecutor;
protected volatile IQueue<HeartAttack> heartAttackQueue;
protected volatile Exercise exercise;
private final List<TraineeJvm> traineeJvms = Collections.synchronizedList(new LinkedList<TraineeJvm>());
public Exercise getExercise() {
return exercise;
}
public void setExercise(Exercise exercise) {
this.exercise = exercise;
}
public void setCoachHzFile(File coachHzFile) {
this.coachHzFile = coachHzFile;
}
public File getCoachHzFile() {
return coachHzFile;
}
protected HazelcastInstance initCoachHazelcastInstance() {
FileInputStream in;
try {
in = new FileInputStream(coachHzFile);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
Config config;
try {
config = new XmlConfigBuilder(in).build();
} finally {
closeQuietly(in);
}
config.getUserContext().put(KEY_COACH, this);
coachHz = Hazelcast.newHazelcastInstance(config);
heartAttackQueue = coachHz.getQueue(COACH_HEART_ATTACK_QUEUE);
new Thread(new HeartAttackMonitor()).start();
return coachHz;
}
private class HeartAttackMonitor implements Runnable {
public void run() {
for (; ; ) {
for (TraineeJvm jvm : traineeJvms) {
HeartAttack heartAttack = null;
if (heartAttack == null) {
heartAttack = detectHeartAttackFile(jvm);
}
if (heartAttack == null) {
heartAttack = detectUnexpectedExit(jvm);
}
if (heartAttack == null) {
heartAttack = detectMembershipFailure(jvm);
}
if (heartAttack != null) {
traineeJvms.remove(jvm);
heartAttackQueue.add(heartAttack);
}
}
Utils.sleepSeconds(1);
}
}
private HeartAttack detectMembershipFailure(TraineeJvm jvm) {
//if the jvm is not assigned a hazelcast address yet.
if (jvm.getAddress() == null) {
return null;
}
Member member = findMember(jvm);
if (member == null) {
jvm.getProcess().destroy();
return new HeartAttack("Hazelcast membership failure (member missing)",
coachHz.getCluster().getLocalMember().getInetSocketAddress(),
jvm.getAddress(),
jvm.getId(),
exercise);
}
return null;
}
private Member findMember(TraineeJvm jvm) {
if (traineeClient == null) return null;
for (Member member : traineeClient.getCluster().getMembers()) {
if (member.getInetSocketAddress().equals(jvm.getAddress())) {
return member;
}
}
return null;
}
private HeartAttack detectHeartAttackFile(TraineeJvm jvm) {
File file = new File(traineesHome, jvm.getId() + ".heartattack");
if (!file.exists()) {
return null;
}
HeartAttack heartAttack = new HeartAttack(
"out of memory",
coachHz.getCluster().getLocalMember().getInetSocketAddress(),
jvm.getAddress(),
jvm.getId(),
exercise);
jvm.getProcess().destroy();
return heartAttack;
}
private HeartAttack detectUnexpectedExit(TraineeJvm jvm) {
Process process = jvm.getProcess();
try {
if (process.exitValue() != 0) {
return new HeartAttack(
"exit code not 0",
coachHz.getCluster().getLocalMember().getInetSocketAddress(),
jvm.getAddress(),
jvm.getId(),
exercise);
}
} catch (IllegalThreadStateException ignore) {
}
return null;
}
}
public void spawnTrainees(TraineeSettings settings) throws Exception {
File traineeHzFile = File.createTempFile("trainee-hazelcast", "xml");
traineeHzFile.deleteOnExit();
Utils.write(traineeHzFile, settings.getHzConfig());
List<TraineeJvm> trainees = new LinkedList<TraineeJvm>();
for (int k = 0; k < settings.getTraineeCount(); k++) {
TraineeJvm trainee = startTraineeJvm(settings.getVmOptions(), traineeHzFile);
Process process = trainee.getProcess();
String traineeId = trainee.getId();
trainees.add(trainee);
new TraineeLogger(traineeId, process.getInputStream(), settings.isTrackLogging()).start();
}
Config config = new XmlConfigBuilder(traineeHzFile.getAbsolutePath()).build();
ClientConfig clientConfig = new ClientConfig().addAddress("localhost:" + config.getNetworkConfig().getPort());
clientConfig.getGroupConfig()
.setName(config.getGroupConfig().getName())
.setPassword(config.getGroupConfig().getPassword());
traineeClient = HazelcastClient.newHazelcastClient(clientConfig);
traineeExecutor = traineeClient.getExecutorService(Trainee.TRAINEE_EXECUTOR);
for (TraineeJvm trainee : trainees) {
waitForTraineeStartup(trainee);
}
}
private TraineeJvm startTraineeJvm(String traineeVmOptions, File traineeHzFile) throws IOException {
String traineeId = "" + System.currentTimeMillis();
String[] clientVmOptionsArray = new String[]{};
if (traineeVmOptions != null && !traineeVmOptions.trim().isEmpty()) {
clientVmOptionsArray = traineeVmOptions.split("\\s+");
}
- File java = new File(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
+ String javaHome = System.getProperty("java.home");
+ log.log(Level.INFO,"java.home="+javaHome);
+ File java = new File(javaHome + File.separator + "bin" + File.separator + "java");
if (!java.exists()) {
- java = new File(System.getProperty("java.home") + File.separator + "java");
+ java = new File(javaHome + File.separator + "java");
}
List<String> args = new LinkedList<String>();
args.add(java.getAbsolutePath());
args.add(format("-XX:OnOutOfMemoryError=\"\"touch %s.heartattack\"\"", traineeId));
args.add("-DHEART_ATTACK_HOME=" + getHeartAttackHome());
args.add("-Dhazelcast.logging.type=log4j");
args.add("-Dlog4j.configuration=file:" + heartAttackHome + File.separator + "conf" + File.separator + "trainee-log4j.xml");
args.add("-cp");
args.add(classpath);
args.addAll(Arrays.asList(clientVmOptionsArray));
args.add(Trainee.class.getName());
args.add(traineeId);
args.add(traineeHzFile.getAbsolutePath());
ProcessBuilder processBuilder = new ProcessBuilder(args.toArray(new String[args.size()]))
.directory(traineesHome)
.redirectErrorStream(true);
Process process = processBuilder.start();
final TraineeJvm traineeJvm = new TraineeJvm(traineeId, process);
traineeJvms.add(traineeJvm);
return traineeJvm;
}
private void waitForTraineeStartup(TraineeJvm jvm) throws InterruptedException {
IMap<String, InetSocketAddress> traineeParticipantMap = traineeClient.getMap(Trainee.TRAINEE_PARTICIPANT_MAP);
boolean found = false;
for (int l = 0; l < 300; l++) {
if (traineeParticipantMap.containsKey(jvm.getId())) {
InetSocketAddress address = traineeParticipantMap.remove(jvm.getId());
jvm.setAddress(address);
found = true;
break;
} else {
Utils.sleepSeconds(1);
}
}
if (!found) {
throw new RuntimeException(format("Trainee %s didn't start up in time", jvm.getId()));
}
log.log(Level.INFO, "Trainee: " + jvm.getId() + " Started");
}
public void destroyTrainees() {
if (traineeClient != null) {
traineeClient.getLifecycleService().shutdown();
}
for (TraineeJvm jvm : traineeJvms) {
jvm.getProcess().destroy();
}
for (TraineeJvm jvm : traineeJvms) {
int exitCode = 0;
try {
exitCode = jvm.getProcess().waitFor();
} catch (InterruptedException e) {
}
if (exitCode != 0) {
log.log(Level.INFO, format("trainee process exited with exit code: %s", exitCode));
}
}
traineeJvms.clear();
}
}
| false | true | private TraineeJvm startTraineeJvm(String traineeVmOptions, File traineeHzFile) throws IOException {
String traineeId = "" + System.currentTimeMillis();
String[] clientVmOptionsArray = new String[]{};
if (traineeVmOptions != null && !traineeVmOptions.trim().isEmpty()) {
clientVmOptionsArray = traineeVmOptions.split("\\s+");
}
File java = new File(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java");
if (!java.exists()) {
java = new File(System.getProperty("java.home") + File.separator + "java");
}
List<String> args = new LinkedList<String>();
args.add(java.getAbsolutePath());
args.add(format("-XX:OnOutOfMemoryError=\"\"touch %s.heartattack\"\"", traineeId));
args.add("-DHEART_ATTACK_HOME=" + getHeartAttackHome());
args.add("-Dhazelcast.logging.type=log4j");
args.add("-Dlog4j.configuration=file:" + heartAttackHome + File.separator + "conf" + File.separator + "trainee-log4j.xml");
args.add("-cp");
args.add(classpath);
args.addAll(Arrays.asList(clientVmOptionsArray));
args.add(Trainee.class.getName());
args.add(traineeId);
args.add(traineeHzFile.getAbsolutePath());
ProcessBuilder processBuilder = new ProcessBuilder(args.toArray(new String[args.size()]))
.directory(traineesHome)
.redirectErrorStream(true);
Process process = processBuilder.start();
final TraineeJvm traineeJvm = new TraineeJvm(traineeId, process);
traineeJvms.add(traineeJvm);
return traineeJvm;
}
| private TraineeJvm startTraineeJvm(String traineeVmOptions, File traineeHzFile) throws IOException {
String traineeId = "" + System.currentTimeMillis();
String[] clientVmOptionsArray = new String[]{};
if (traineeVmOptions != null && !traineeVmOptions.trim().isEmpty()) {
clientVmOptionsArray = traineeVmOptions.split("\\s+");
}
String javaHome = System.getProperty("java.home");
log.log(Level.INFO,"java.home="+javaHome);
File java = new File(javaHome + File.separator + "bin" + File.separator + "java");
if (!java.exists()) {
java = new File(javaHome + File.separator + "java");
}
List<String> args = new LinkedList<String>();
args.add(java.getAbsolutePath());
args.add(format("-XX:OnOutOfMemoryError=\"\"touch %s.heartattack\"\"", traineeId));
args.add("-DHEART_ATTACK_HOME=" + getHeartAttackHome());
args.add("-Dhazelcast.logging.type=log4j");
args.add("-Dlog4j.configuration=file:" + heartAttackHome + File.separator + "conf" + File.separator + "trainee-log4j.xml");
args.add("-cp");
args.add(classpath);
args.addAll(Arrays.asList(clientVmOptionsArray));
args.add(Trainee.class.getName());
args.add(traineeId);
args.add(traineeHzFile.getAbsolutePath());
ProcessBuilder processBuilder = new ProcessBuilder(args.toArray(new String[args.size()]))
.directory(traineesHome)
.redirectErrorStream(true);
Process process = processBuilder.start();
final TraineeJvm traineeJvm = new TraineeJvm(traineeId, process);
traineeJvms.add(traineeJvm);
return traineeJvm;
}
|
diff --git a/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/raw/DebugInfoItem.java b/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/raw/DebugInfoItem.java
index 1d3f4afd..1ddd4ac0 100644
--- a/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/raw/DebugInfoItem.java
+++ b/dexlib2/src/main/java/org/jf/dexlib2/dexbacked/raw/DebugInfoItem.java
@@ -1,183 +1,183 @@
/*
* Copyright 2013, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE COPYRIGHT
* OWNER 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.
*/
package org.jf.dexlib2.dexbacked.raw;
import org.jf.dexlib2.DebugItemType;
import org.jf.dexlib2.dexbacked.DexReader;
import org.jf.dexlib2.dexbacked.raw.util.DexAnnotator;
import org.jf.dexlib2.util.AnnotatedBytes;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class DebugInfoItem {
@Nonnull
public static SectionAnnotator makeAnnotator(@Nonnull DexAnnotator annotator, @Nonnull MapItem mapItem) {
return new SectionAnnotator(annotator, mapItem) {
@Nonnull @Override public String getItemName() {
return "debug_info_item";
}
@Override
public void annotateItem(@Nonnull AnnotatedBytes out, int itemIndex, @Nullable String itemIdentity) {
DexReader reader = dexFile.readerAt(out.getCursor());
int lineStart = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "line_start = %d", lineStart);
int parametersSize = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "parameters_size = %d", parametersSize);
if (parametersSize > 0) {
out.annotate(0, "parameters:");
out.indent();
for (int i=0; i<parametersSize; i++) {
int paramaterIndex = reader.readSmallUleb128() - 1;
- out.annotateTo(reader.getOffset(),
+ out.annotateTo(reader.getOffset(), "%s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, paramaterIndex, true));
}
out.deindent();
}
out.annotate(0, "debug opcodes:");
out.indent();
int codeAddress = 0;
int lineNumber = lineStart;
loop: while (true) {
int opcode = reader.readUbyte();
switch (opcode) {
case DebugItemType.END_SEQUENCE: {
out.annotateTo(reader.getOffset(), "DBG_END_SEQUENCE");
break loop;
}
case DebugItemType.ADVANCE_PC: {
out.annotateTo(reader.getOffset(), "DBG_ADVANCE_PC");
out.indent();
int addressDiff = reader.readSmallUleb128();
codeAddress += addressDiff;
out.annotateTo(reader.getOffset(), "addr_diff = +0x%x: 0x%x", addressDiff,
codeAddress);
out.deindent();
break;
}
case DebugItemType.ADVANCE_LINE: {
out.annotateTo(reader.getOffset(), "DBG_ADVANCE_LINE");
out.indent();
int lineDiff = reader.readSleb128();
lineNumber += lineDiff;
out.annotateTo(reader.getOffset(), "line_diff = +%d: %d", Math.abs(lineDiff), lineNumber);
out.deindent();
break;
}
case DebugItemType.START_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_START_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
int nameIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIndex, true));
int typeIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "type_idx = %s",
TypeIdItem.getOptionalReferenceAnnotation(dexFile, typeIndex));
out.deindent();
break;
}
case DebugItemType.START_LOCAL_EXTENDED: {
out.annotateTo(reader.getOffset(), "DBG_START_LOCAL_EXTENDED");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
int nameIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIndex, true));
int typeIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "type_idx = %s",
TypeIdItem.getOptionalReferenceAnnotation(dexFile, typeIndex));
int sigIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "sig_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, sigIndex, true));
out.deindent();
break;
}
case DebugItemType.END_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_END_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
out.deindent();
break;
}
case DebugItemType.RESTART_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_RESTART_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
out.deindent();
break;
}
case DebugItemType.PROLOGUE_END: {
out.annotateTo(reader.getOffset(), "DBG_SET_PROLOGUE_END");
break;
}
case DebugItemType.EPILOGUE_BEGIN: {
out.annotateTo(reader.getOffset(), "DBG_SET_EPILOGUE_BEGIN");
break;
}
case DebugItemType.SET_SOURCE_FILE: {
out.annotateTo(reader.getOffset(), "DBG_SET_FILE");
out.indent();
int nameIdx = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIdx));
out.deindent();
break;
}
default:
int adjusted = opcode - 0x0A;
int addressDiff = adjusted / 15;
int lineDiff = (adjusted % 15) - 4;
codeAddress += addressDiff;
lineNumber += lineDiff;
out.annotateTo(reader.getOffset(), "address_diff = +0x%x:0x%x, line_diff = +%d:%d, ",
addressDiff, codeAddress, lineDiff, lineNumber);
break;
}
}
out.deindent();
}
};
}
}
| true | true | public static SectionAnnotator makeAnnotator(@Nonnull DexAnnotator annotator, @Nonnull MapItem mapItem) {
return new SectionAnnotator(annotator, mapItem) {
@Nonnull @Override public String getItemName() {
return "debug_info_item";
}
@Override
public void annotateItem(@Nonnull AnnotatedBytes out, int itemIndex, @Nullable String itemIdentity) {
DexReader reader = dexFile.readerAt(out.getCursor());
int lineStart = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "line_start = %d", lineStart);
int parametersSize = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "parameters_size = %d", parametersSize);
if (parametersSize > 0) {
out.annotate(0, "parameters:");
out.indent();
for (int i=0; i<parametersSize; i++) {
int paramaterIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(),
StringIdItem.getOptionalReferenceAnnotation(dexFile, paramaterIndex, true));
}
out.deindent();
}
out.annotate(0, "debug opcodes:");
out.indent();
int codeAddress = 0;
int lineNumber = lineStart;
loop: while (true) {
int opcode = reader.readUbyte();
switch (opcode) {
case DebugItemType.END_SEQUENCE: {
out.annotateTo(reader.getOffset(), "DBG_END_SEQUENCE");
break loop;
}
case DebugItemType.ADVANCE_PC: {
out.annotateTo(reader.getOffset(), "DBG_ADVANCE_PC");
out.indent();
int addressDiff = reader.readSmallUleb128();
codeAddress += addressDiff;
out.annotateTo(reader.getOffset(), "addr_diff = +0x%x: 0x%x", addressDiff,
codeAddress);
out.deindent();
break;
}
case DebugItemType.ADVANCE_LINE: {
out.annotateTo(reader.getOffset(), "DBG_ADVANCE_LINE");
out.indent();
int lineDiff = reader.readSleb128();
lineNumber += lineDiff;
out.annotateTo(reader.getOffset(), "line_diff = +%d: %d", Math.abs(lineDiff), lineNumber);
out.deindent();
break;
}
case DebugItemType.START_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_START_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
int nameIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIndex, true));
int typeIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "type_idx = %s",
TypeIdItem.getOptionalReferenceAnnotation(dexFile, typeIndex));
out.deindent();
break;
}
case DebugItemType.START_LOCAL_EXTENDED: {
out.annotateTo(reader.getOffset(), "DBG_START_LOCAL_EXTENDED");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
int nameIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIndex, true));
int typeIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "type_idx = %s",
TypeIdItem.getOptionalReferenceAnnotation(dexFile, typeIndex));
int sigIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "sig_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, sigIndex, true));
out.deindent();
break;
}
case DebugItemType.END_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_END_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
out.deindent();
break;
}
case DebugItemType.RESTART_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_RESTART_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
out.deindent();
break;
}
case DebugItemType.PROLOGUE_END: {
out.annotateTo(reader.getOffset(), "DBG_SET_PROLOGUE_END");
break;
}
case DebugItemType.EPILOGUE_BEGIN: {
out.annotateTo(reader.getOffset(), "DBG_SET_EPILOGUE_BEGIN");
break;
}
case DebugItemType.SET_SOURCE_FILE: {
out.annotateTo(reader.getOffset(), "DBG_SET_FILE");
out.indent();
int nameIdx = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIdx));
out.deindent();
break;
}
default:
int adjusted = opcode - 0x0A;
int addressDiff = adjusted / 15;
int lineDiff = (adjusted % 15) - 4;
codeAddress += addressDiff;
lineNumber += lineDiff;
out.annotateTo(reader.getOffset(), "address_diff = +0x%x:0x%x, line_diff = +%d:%d, ",
addressDiff, codeAddress, lineDiff, lineNumber);
break;
}
}
out.deindent();
}
};
}
| public static SectionAnnotator makeAnnotator(@Nonnull DexAnnotator annotator, @Nonnull MapItem mapItem) {
return new SectionAnnotator(annotator, mapItem) {
@Nonnull @Override public String getItemName() {
return "debug_info_item";
}
@Override
public void annotateItem(@Nonnull AnnotatedBytes out, int itemIndex, @Nullable String itemIdentity) {
DexReader reader = dexFile.readerAt(out.getCursor());
int lineStart = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "line_start = %d", lineStart);
int parametersSize = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "parameters_size = %d", parametersSize);
if (parametersSize > 0) {
out.annotate(0, "parameters:");
out.indent();
for (int i=0; i<parametersSize; i++) {
int paramaterIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "%s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, paramaterIndex, true));
}
out.deindent();
}
out.annotate(0, "debug opcodes:");
out.indent();
int codeAddress = 0;
int lineNumber = lineStart;
loop: while (true) {
int opcode = reader.readUbyte();
switch (opcode) {
case DebugItemType.END_SEQUENCE: {
out.annotateTo(reader.getOffset(), "DBG_END_SEQUENCE");
break loop;
}
case DebugItemType.ADVANCE_PC: {
out.annotateTo(reader.getOffset(), "DBG_ADVANCE_PC");
out.indent();
int addressDiff = reader.readSmallUleb128();
codeAddress += addressDiff;
out.annotateTo(reader.getOffset(), "addr_diff = +0x%x: 0x%x", addressDiff,
codeAddress);
out.deindent();
break;
}
case DebugItemType.ADVANCE_LINE: {
out.annotateTo(reader.getOffset(), "DBG_ADVANCE_LINE");
out.indent();
int lineDiff = reader.readSleb128();
lineNumber += lineDiff;
out.annotateTo(reader.getOffset(), "line_diff = +%d: %d", Math.abs(lineDiff), lineNumber);
out.deindent();
break;
}
case DebugItemType.START_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_START_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
int nameIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIndex, true));
int typeIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "type_idx = %s",
TypeIdItem.getOptionalReferenceAnnotation(dexFile, typeIndex));
out.deindent();
break;
}
case DebugItemType.START_LOCAL_EXTENDED: {
out.annotateTo(reader.getOffset(), "DBG_START_LOCAL_EXTENDED");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
int nameIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIndex, true));
int typeIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "type_idx = %s",
TypeIdItem.getOptionalReferenceAnnotation(dexFile, typeIndex));
int sigIndex = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "sig_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, sigIndex, true));
out.deindent();
break;
}
case DebugItemType.END_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_END_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
out.deindent();
break;
}
case DebugItemType.RESTART_LOCAL: {
out.annotateTo(reader.getOffset(), "DBG_RESTART_LOCAL");
out.indent();
int registerNum = reader.readSmallUleb128();
out.annotateTo(reader.getOffset(), "register_num = v%d", registerNum);
out.deindent();
break;
}
case DebugItemType.PROLOGUE_END: {
out.annotateTo(reader.getOffset(), "DBG_SET_PROLOGUE_END");
break;
}
case DebugItemType.EPILOGUE_BEGIN: {
out.annotateTo(reader.getOffset(), "DBG_SET_EPILOGUE_BEGIN");
break;
}
case DebugItemType.SET_SOURCE_FILE: {
out.annotateTo(reader.getOffset(), "DBG_SET_FILE");
out.indent();
int nameIdx = reader.readSmallUleb128() - 1;
out.annotateTo(reader.getOffset(), "name_idx = %s",
StringIdItem.getOptionalReferenceAnnotation(dexFile, nameIdx));
out.deindent();
break;
}
default:
int adjusted = opcode - 0x0A;
int addressDiff = adjusted / 15;
int lineDiff = (adjusted % 15) - 4;
codeAddress += addressDiff;
lineNumber += lineDiff;
out.annotateTo(reader.getOffset(), "address_diff = +0x%x:0x%x, line_diff = +%d:%d, ",
addressDiff, codeAddress, lineDiff, lineNumber);
break;
}
}
out.deindent();
}
};
}
|
diff --git a/java/src/main/java/com/nedap/retail/api/v1/tester/App.java b/java/src/main/java/com/nedap/retail/api/v1/tester/App.java
index 5acb530..16da80a 100644
--- a/java/src/main/java/com/nedap/retail/api/v1/tester/App.java
+++ b/java/src/main/java/com/nedap/retail/api/v1/tester/App.java
@@ -1,648 +1,648 @@
package com.nedap.retail.api.v1.tester;
import com.nedap.retail.api.v1.model.*;
import com.nedap.retail.api.v1.tester.EventsServer.MODE;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Timer;
/**
* Store !D API tester for !D Top and !D Gate
*
*/
public class App {
public static void main(String[] args) {
System.out.println("Store !D API tester for !D Top and !D Gate version 1.17 Java");
if (args.length==0)
{
System.out.println("Please use URL of device as parameter, for example: http://localhost:8081");
- System.out.println("Optionally, you can use the hostname of of this computer as second parameter to start automatic testing.");
+ System.out.println("Optionally, you can use the hostname of this computer as second parameter to start automatic testing.");
System.out.println("Optionally, you can use the \"count\" as third parameter to count unique EPCs.");
System.exit(0);
}
// instantiate API wrapper
ApiWrapper api = new ApiWrapper(args[0]);
// if third argument is given, start epc counting
if (args.length==3) {
countEpc(api, args[1]);
System.exit(0);
}
// if second argument is given, start automatic testing
if (args.length==2) {
testApi(api, args[1]);
System.exit(0);
}
boolean running = true;
while(running) {
// show menu
System.out.println();
System.out.println("------------------------------------------------------");
System.out.println("0. Test connection 1. Show status");
System.out.println("c. Send action g. Send heartbeat");
System.out.println("d. Create spec, subscription and receive incoming events");
System.out.println("e. Get settings f. Update settings");
System.out.println("h. Show number of unique EPCs and write them to file");
System.out.println("-- SPECS -- -- SUBSCRIPTIONS --");
System.out.println("2. Show all specs 7. Show all subscriptions");
System.out.println("3. Create new spec 8. Create new subscription");
System.out.println("4. Show a spec 9. Show a subscription");
System.out.println("5. Update a spec a. Update a subscription");
System.out.println("6. Delete a spec b. Delete a subscription");
System.out.println("Please enter your choice and press Enter, or just Enter to exit.");
// get choice
BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(System.in));
String input = "";
try {
input = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
// exit if no choice made
if (input.length()==0) {
System.exit(0);
}
// print line
System.out.println("------------------------------------------------------");
// check what choice has been made
int keycode = input.codePointAt(0);
switch(keycode) {
case 48: // 0
System.out.println("Test connection");
api.testConnection();
break;
case 49: // 1
System.out.println("Show status");
try {
System.out.println(api.getStatus().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 50: // 2
System.out.println("Show specs");
try {
System.out.println(api.getSpecs().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 51: // 3
System.out.println("Create new spec");
System.out.print("Enter a name: ");
String createSpecName = "Test";
try {
createSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.println("Which events?");
System.out.println("1 = rfid.tag.arrive");
System.out.println("2 = rfid.tag.move");
System.out.println("3 = rfid.tag.arrive AND rfid.tag.move");
String createSpecOptions = "3";
try {
createSpecOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
String[] createSpecEvents;
if (createSpecOptions.equals("1")) {
createSpecEvents = new String[1];
createSpecEvents[0] = "rfid.tag.arrive";
} else if (createSpecOptions.equals("2")) {
createSpecEvents = new String[1];
createSpecEvents[0] = "rfid.tag.move";
} else {
createSpecEvents = new String[2];
createSpecEvents[0] = "rfid.tag.arrive";
createSpecEvents[1] = "rfid.tag.move";
}
Spec createSpec = new Spec(0, createSpecName, createSpecEvents);
try {
System.out.println(api.createSpec(createSpec).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 52: // 4
System.out.println("Show a spec");
System.out.print("Enter an ID: ");
String showSpecId = "";
try {
showSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
System.out.println(api.getSpec(Integer.parseInt(showSpecId)).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 53: // 5
System.out.println("Update a spec");
System.out.print("Enter ID of spec to update: ");
String updateSpecId = "";
try {
updateSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Enter a name: ");
String updateSpecName = "Test";
try {
updateSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.println("Which events?");
System.out.println("1 = rfid.tag.arrive");
System.out.println("2 = rfid.tag.move");
System.out.println("3 = rfid.tag.arrive AND rfid.tag.move");
String updateSpecOptions = "3";
try {
updateSpecOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
String[] updateSpecEvents;
if (updateSpecOptions.equals("1")) {
updateSpecEvents = new String[1];
updateSpecEvents[0] = "rfid.tag.arrive";
} else if (updateSpecOptions.equals("2")) {
updateSpecEvents = new String[1];
updateSpecEvents[0] = "rfid.tag.move";
} else {
updateSpecEvents = new String[2];
updateSpecEvents[0] = "rfid.tag.arrive";
updateSpecEvents[1] = "rfid.tag.move";
}
Spec updateSpec = new Spec(Integer.parseInt(updateSpecId), updateSpecName, updateSpecEvents);
try {
System.out.println(api.updateSpec(updateSpec).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 54: // 6
System.out.println("Delete a spec");
System.out.print("Enter an ID: ");
String deleteSpecId = "";
try {
deleteSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
api.deleteSpec(Integer.parseInt(deleteSpecId));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 55: // 7
System.out.println("Show subscriptions");
try {
System.out.println(api.getSubscriptions().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 56: // 8
System.out.println("Create new subscription");
System.out.print("Enter name of a spec: ");
String createSubscriptionSpecName = "";
try {
createSubscriptionSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("URI to send events to: ");
String createSubscriptionUri = "";
try {
createSubscriptionUri = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("External reference (optional): ");
String createSubscriptionExternRef = "";
try {
createSubscriptionExternRef = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Requested lease time in minutes: ");
String createSubscriptionLease = "";
try {
createSubscriptionLease = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
Integer createSubscriptionLeaseTime = 0;
if (createSubscriptionLease.length()>0) {
createSubscriptionLeaseTime = Integer.parseInt(createSubscriptionLease);
}
Subscription createSubscription = new Subscription(0, createSubscriptionSpecName, createSubscriptionUri, createSubscriptionExternRef, createSubscriptionLeaseTime);
try {
System.out.println(api.createSubscription(createSubscription).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 57: // 9
System.out.println("Show a subscription");
System.out.print("Enter an ID: ");
String showSubscriptionId = "";
try {
showSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
System.out.println(api.getSubscription(Integer.parseInt(showSubscriptionId)).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 97: // a
System.out.println("Update a subscription");
System.out.print("Enter ID of subscription to update: ");
String updateSubscriptionId = "";
try {
updateSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Enter name of a spec: ");
String updateSubscriptionSpecName = "";
try {
updateSubscriptionSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("URI to send events to: ");
String updateSubscriptionUri = "";
try {
updateSubscriptionUri = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("External reference (optional): ");
String updateSubscriptionExternRef = "";
try {
updateSubscriptionExternRef = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Requested lease time in minutes: ");
String updateSubscriptionLease = "";
try {
updateSubscriptionLease = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
Integer updateSubscriptionLeaseTime = 0;
if (updateSubscriptionLease.length()>0) {
updateSubscriptionLeaseTime = Integer.parseInt(updateSubscriptionLease);
}
Subscription updateSubscription = new Subscription(Integer.parseInt(updateSubscriptionId), updateSubscriptionSpecName, updateSubscriptionUri, updateSubscriptionExternRef, updateSubscriptionLeaseTime);
try {
System.out.println(api.updateSubscription(updateSubscription).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 98: // b
System.out.println("Delete a subscription");
System.out.print("Enter an ID: ");
String deleteSubscriptionId = "";
try {
deleteSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
api.deleteSubscription(Integer.parseInt(deleteSubscriptionId));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 99: // c
System.out.println("Send an action");
System.out.println("Which action?");
System.out.println("1 = blink");
System.out.println("2 = beep");
System.out.println("3 = blink and beep");
String sendActionOptions = "3";
try {
sendActionOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("How many times: ");
String sendActionTimes = "";
try {
sendActionTimes = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp/buzzer is on (in milliseconds): ");
String sendActionOnTime = "";
try {
sendActionOnTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp/buzzer is off (in milliseconds): ");
String sendActionOffTime = "";
try {
sendActionOffTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp is on afterwards (in milliseconds): ");
String sendActionHoldTime = "";
try {
sendActionHoldTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
String sendActionAction = "";
if (sendActionOptions.equals("1")) {
sendActionAction = "blink";
} else if (sendActionOptions.equals("2")) {
sendActionAction = "beep";
} else if (sendActionOptions.equals("3")) {
sendActionAction = "blinkAndBeep";
}
Action[] actions = new Action[1];
actions[0] = new Action(sendActionAction, Integer.parseInt(sendActionTimes), Integer.parseInt(sendActionOnTime), Integer.parseInt(sendActionOffTime), Integer.parseInt(sendActionHoldTime));
api.sendActions(new Actions(actions));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 100: // d
System.out.print("On what hostname or IP address is this system reachable by the !D Top or !D Gate: ");
String testApiHostname = "";
try {
testApiHostname = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
testApi(api, testApiHostname);
break;
case 101: // e
System.out.println("Show settings");
try {
System.out.println(api.getSettings().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 102: // f
System.out.println("Update settings");
Settings settings = new Settings();
System.out.print("Enable RFID reader (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableReader = "";
try {
updateSettingsEnableReader = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableReader.equalsIgnoreCase("y")) {
settings.setReaderEnabled(true);
} else if (updateSettingsEnableReader.equalsIgnoreCase("n")) {
settings.setReaderEnabled(false);
}
System.out.print("Enable lights (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableLights = "";
try {
updateSettingsEnableLights = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableLights.equalsIgnoreCase("y")) {
settings.setLightsEnabled(true);
} else if (updateSettingsEnableLights.equalsIgnoreCase("n")) {
settings.setLightsEnabled(false);
}
System.out.print("Enable buzzer (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableBuzzer = "";
try {
updateSettingsEnableBuzzer = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableBuzzer.equalsIgnoreCase("y")) {
settings.setBuzzerEnabled(true);
} else if (updateSettingsEnableBuzzer.equalsIgnoreCase("n")) {
settings.setBuzzerEnabled(false);
}
System.out.print("Buzzer volume (0-100, Enter for no change): ");
String updateSettingsBuzzerVolume = "";
try {
updateSettingsBuzzerVolume = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (!updateSettingsBuzzerVolume.equals("")) {
settings.setBuzzerVolume(Integer.parseInt(updateSettingsBuzzerVolume));
}
System.out.print("Set a new alarm pattern? (y for yes, n for no): ");
String updateSettingsAlarmPattern = "";
try {
updateSettingsAlarmPattern = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsAlarmPattern.equalsIgnoreCase("y")) {
AlarmPattern alarmPattern = new AlarmPattern();
System.out.print("Time lights/buzzer are on (in milliseconds, default=400): ");
String updateSettingsInput = "";
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setOnTime(Integer.parseInt(updateSettingsInput));
System.out.print("Time lights/buzzer are off (in milliseconds, default=50): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setOffTime(Integer.parseInt(updateSettingsInput));
System.out.print("Time lights are on after last cycle (in milliseconds, default=7000): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setLightsHoldTime(Integer.parseInt(updateSettingsInput));
System.out.print("Number of cycles (default=5): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setCount(Integer.parseInt(updateSettingsInput));
settings.setAlarmPattern(alarmPattern);
}
try {
api.updateSettings(settings);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 103: // g
System.out.println("Send heartbeat");
try {
api.heartbeat();
} catch (Exception e) {
e.printStackTrace();
}
break;
case 104: // h
System.out.print("On what hostname or IP address is this system reachable by the !D Top or !D Gate: ");
String countEpcHostname = "";
try {
countEpcHostname = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
countEpc(api, countEpcHostname);
System.exit(0);
break;
}
}
}
public static void testApi(ApiWrapper api, String ownHostname) {
BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(System.in));
int testApiPortnr = 8088;
System.out.println("Starting webserver...");
Thread t = new Thread(new EventsServer(testApiPortnr));
t.start();
String[] testApiSpecEvents = new String[2];
testApiSpecEvents[0] = "rfid.tag.arrive";
testApiSpecEvents[1] = "rfid.tag.move";
System.out.println("Creating spec...");
Spec testApiSpec = new Spec(0, "tester", testApiSpecEvents);
try {
testApiSpec = api.createSpec(testApiSpec);
} catch (Exception e) {
}
System.out.println("Creating subscription...");
Subscription testApiSubscription = new Subscription(0, "tester", "http://" + ownHostname+ ":" + testApiPortnr + "/", "tester", 30);
try {
testApiSubscription = api.createSubscription(testApiSubscription);
} catch (Exception e) {
}
// set timer to renew subscription every 29 minutes
RenewSubscriptionTask task = new RenewSubscriptionTask(api, testApiSubscription);
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 29*60*1000, 29*60*1000);
System.out.println("Press x and Enter to exit");
String key = "";
while(!key.equals("x")) {
try {
key = inputBuffer.readLine();
} catch (IOException e) {
}
}
System.out.println("Deleting spec and subscription");
try {
api.deleteSpec(testApiSpec.getId());
} catch (Exception e) {
}
try {
api.deleteSubscription(testApiSubscription.getId());
} catch (Exception e) {
}
try {
inputBuffer.close();
} catch (Exception e) {
}
timer.cancel();
}
public static void countEpc(ApiWrapper api, String ownHostname) {
BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a description for the log file: ");
String description = "";
try {
description = inputBuffer.readLine();
} catch (IOException e) {
}
int testApiPortnr = 8088;
System.out.println("Starting webserver...");
EventsServer server = new EventsServer(testApiPortnr);
server.setMode(MODE.EPCCOUNT);
Thread t = new Thread(server);
t.start();
String[] testApiSpecEvents = new String[1];
testApiSpecEvents[0] = "rfid.tag.arrive";
System.out.println("Creating spec...");
Spec testApiSpec = new Spec(0, "epccount", testApiSpecEvents);
try {
testApiSpec = api.createSpec(testApiSpec);
} catch (Exception e) {
}
System.out.println("Creating subscription...");
Subscription testApiSubscription = new Subscription(0, "epccount", "http://" + ownHostname+ ":" + testApiPortnr + "/", "tester", 30);
try {
testApiSubscription = api.createSubscription(testApiSubscription);
} catch (Exception e) {
}
// set timer to renew subscription every 29 minutes
RenewSubscriptionTask task = new RenewSubscriptionTask(api, testApiSubscription);
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 29*60*1000, 29*60*1000);
System.out.println("Press x and Enter to exit");
String key = "";
while(!key.equals("x")) {
try {
key = inputBuffer.readLine();
} catch (IOException e) {
}
}
System.out.println("Deleting spec and subscription");
try {
api.deleteSpec(testApiSpec.getId());
} catch (Exception e) {
}
try {
api.deleteSubscription(testApiSubscription.getId());
} catch (Exception e) {
}
try {
inputBuffer.close();
} catch (Exception e) {
}
timer.cancel();
LogFile.write(description);
for (Object epc : EpcCounter.getEpcs().keySet()) {
LogFile.write(epc.toString());
}
System.out.println("EPCs written to " + LogFile.filename);
}
}
| true | true | public static void main(String[] args) {
System.out.println("Store !D API tester for !D Top and !D Gate version 1.17 Java");
if (args.length==0)
{
System.out.println("Please use URL of device as parameter, for example: http://localhost:8081");
System.out.println("Optionally, you can use the hostname of of this computer as second parameter to start automatic testing.");
System.out.println("Optionally, you can use the \"count\" as third parameter to count unique EPCs.");
System.exit(0);
}
// instantiate API wrapper
ApiWrapper api = new ApiWrapper(args[0]);
// if third argument is given, start epc counting
if (args.length==3) {
countEpc(api, args[1]);
System.exit(0);
}
// if second argument is given, start automatic testing
if (args.length==2) {
testApi(api, args[1]);
System.exit(0);
}
boolean running = true;
while(running) {
// show menu
System.out.println();
System.out.println("------------------------------------------------------");
System.out.println("0. Test connection 1. Show status");
System.out.println("c. Send action g. Send heartbeat");
System.out.println("d. Create spec, subscription and receive incoming events");
System.out.println("e. Get settings f. Update settings");
System.out.println("h. Show number of unique EPCs and write them to file");
System.out.println("-- SPECS -- -- SUBSCRIPTIONS --");
System.out.println("2. Show all specs 7. Show all subscriptions");
System.out.println("3. Create new spec 8. Create new subscription");
System.out.println("4. Show a spec 9. Show a subscription");
System.out.println("5. Update a spec a. Update a subscription");
System.out.println("6. Delete a spec b. Delete a subscription");
System.out.println("Please enter your choice and press Enter, or just Enter to exit.");
// get choice
BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(System.in));
String input = "";
try {
input = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
// exit if no choice made
if (input.length()==0) {
System.exit(0);
}
// print line
System.out.println("------------------------------------------------------");
// check what choice has been made
int keycode = input.codePointAt(0);
switch(keycode) {
case 48: // 0
System.out.println("Test connection");
api.testConnection();
break;
case 49: // 1
System.out.println("Show status");
try {
System.out.println(api.getStatus().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 50: // 2
System.out.println("Show specs");
try {
System.out.println(api.getSpecs().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 51: // 3
System.out.println("Create new spec");
System.out.print("Enter a name: ");
String createSpecName = "Test";
try {
createSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.println("Which events?");
System.out.println("1 = rfid.tag.arrive");
System.out.println("2 = rfid.tag.move");
System.out.println("3 = rfid.tag.arrive AND rfid.tag.move");
String createSpecOptions = "3";
try {
createSpecOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
String[] createSpecEvents;
if (createSpecOptions.equals("1")) {
createSpecEvents = new String[1];
createSpecEvents[0] = "rfid.tag.arrive";
} else if (createSpecOptions.equals("2")) {
createSpecEvents = new String[1];
createSpecEvents[0] = "rfid.tag.move";
} else {
createSpecEvents = new String[2];
createSpecEvents[0] = "rfid.tag.arrive";
createSpecEvents[1] = "rfid.tag.move";
}
Spec createSpec = new Spec(0, createSpecName, createSpecEvents);
try {
System.out.println(api.createSpec(createSpec).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 52: // 4
System.out.println("Show a spec");
System.out.print("Enter an ID: ");
String showSpecId = "";
try {
showSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
System.out.println(api.getSpec(Integer.parseInt(showSpecId)).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 53: // 5
System.out.println("Update a spec");
System.out.print("Enter ID of spec to update: ");
String updateSpecId = "";
try {
updateSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Enter a name: ");
String updateSpecName = "Test";
try {
updateSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.println("Which events?");
System.out.println("1 = rfid.tag.arrive");
System.out.println("2 = rfid.tag.move");
System.out.println("3 = rfid.tag.arrive AND rfid.tag.move");
String updateSpecOptions = "3";
try {
updateSpecOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
String[] updateSpecEvents;
if (updateSpecOptions.equals("1")) {
updateSpecEvents = new String[1];
updateSpecEvents[0] = "rfid.tag.arrive";
} else if (updateSpecOptions.equals("2")) {
updateSpecEvents = new String[1];
updateSpecEvents[0] = "rfid.tag.move";
} else {
updateSpecEvents = new String[2];
updateSpecEvents[0] = "rfid.tag.arrive";
updateSpecEvents[1] = "rfid.tag.move";
}
Spec updateSpec = new Spec(Integer.parseInt(updateSpecId), updateSpecName, updateSpecEvents);
try {
System.out.println(api.updateSpec(updateSpec).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 54: // 6
System.out.println("Delete a spec");
System.out.print("Enter an ID: ");
String deleteSpecId = "";
try {
deleteSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
api.deleteSpec(Integer.parseInt(deleteSpecId));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 55: // 7
System.out.println("Show subscriptions");
try {
System.out.println(api.getSubscriptions().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 56: // 8
System.out.println("Create new subscription");
System.out.print("Enter name of a spec: ");
String createSubscriptionSpecName = "";
try {
createSubscriptionSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("URI to send events to: ");
String createSubscriptionUri = "";
try {
createSubscriptionUri = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("External reference (optional): ");
String createSubscriptionExternRef = "";
try {
createSubscriptionExternRef = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Requested lease time in minutes: ");
String createSubscriptionLease = "";
try {
createSubscriptionLease = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
Integer createSubscriptionLeaseTime = 0;
if (createSubscriptionLease.length()>0) {
createSubscriptionLeaseTime = Integer.parseInt(createSubscriptionLease);
}
Subscription createSubscription = new Subscription(0, createSubscriptionSpecName, createSubscriptionUri, createSubscriptionExternRef, createSubscriptionLeaseTime);
try {
System.out.println(api.createSubscription(createSubscription).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 57: // 9
System.out.println("Show a subscription");
System.out.print("Enter an ID: ");
String showSubscriptionId = "";
try {
showSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
System.out.println(api.getSubscription(Integer.parseInt(showSubscriptionId)).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 97: // a
System.out.println("Update a subscription");
System.out.print("Enter ID of subscription to update: ");
String updateSubscriptionId = "";
try {
updateSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Enter name of a spec: ");
String updateSubscriptionSpecName = "";
try {
updateSubscriptionSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("URI to send events to: ");
String updateSubscriptionUri = "";
try {
updateSubscriptionUri = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("External reference (optional): ");
String updateSubscriptionExternRef = "";
try {
updateSubscriptionExternRef = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Requested lease time in minutes: ");
String updateSubscriptionLease = "";
try {
updateSubscriptionLease = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
Integer updateSubscriptionLeaseTime = 0;
if (updateSubscriptionLease.length()>0) {
updateSubscriptionLeaseTime = Integer.parseInt(updateSubscriptionLease);
}
Subscription updateSubscription = new Subscription(Integer.parseInt(updateSubscriptionId), updateSubscriptionSpecName, updateSubscriptionUri, updateSubscriptionExternRef, updateSubscriptionLeaseTime);
try {
System.out.println(api.updateSubscription(updateSubscription).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 98: // b
System.out.println("Delete a subscription");
System.out.print("Enter an ID: ");
String deleteSubscriptionId = "";
try {
deleteSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
api.deleteSubscription(Integer.parseInt(deleteSubscriptionId));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 99: // c
System.out.println("Send an action");
System.out.println("Which action?");
System.out.println("1 = blink");
System.out.println("2 = beep");
System.out.println("3 = blink and beep");
String sendActionOptions = "3";
try {
sendActionOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("How many times: ");
String sendActionTimes = "";
try {
sendActionTimes = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp/buzzer is on (in milliseconds): ");
String sendActionOnTime = "";
try {
sendActionOnTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp/buzzer is off (in milliseconds): ");
String sendActionOffTime = "";
try {
sendActionOffTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp is on afterwards (in milliseconds): ");
String sendActionHoldTime = "";
try {
sendActionHoldTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
String sendActionAction = "";
if (sendActionOptions.equals("1")) {
sendActionAction = "blink";
} else if (sendActionOptions.equals("2")) {
sendActionAction = "beep";
} else if (sendActionOptions.equals("3")) {
sendActionAction = "blinkAndBeep";
}
Action[] actions = new Action[1];
actions[0] = new Action(sendActionAction, Integer.parseInt(sendActionTimes), Integer.parseInt(sendActionOnTime), Integer.parseInt(sendActionOffTime), Integer.parseInt(sendActionHoldTime));
api.sendActions(new Actions(actions));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 100: // d
System.out.print("On what hostname or IP address is this system reachable by the !D Top or !D Gate: ");
String testApiHostname = "";
try {
testApiHostname = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
testApi(api, testApiHostname);
break;
case 101: // e
System.out.println("Show settings");
try {
System.out.println(api.getSettings().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 102: // f
System.out.println("Update settings");
Settings settings = new Settings();
System.out.print("Enable RFID reader (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableReader = "";
try {
updateSettingsEnableReader = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableReader.equalsIgnoreCase("y")) {
settings.setReaderEnabled(true);
} else if (updateSettingsEnableReader.equalsIgnoreCase("n")) {
settings.setReaderEnabled(false);
}
System.out.print("Enable lights (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableLights = "";
try {
updateSettingsEnableLights = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableLights.equalsIgnoreCase("y")) {
settings.setLightsEnabled(true);
} else if (updateSettingsEnableLights.equalsIgnoreCase("n")) {
settings.setLightsEnabled(false);
}
System.out.print("Enable buzzer (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableBuzzer = "";
try {
updateSettingsEnableBuzzer = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableBuzzer.equalsIgnoreCase("y")) {
settings.setBuzzerEnabled(true);
} else if (updateSettingsEnableBuzzer.equalsIgnoreCase("n")) {
settings.setBuzzerEnabled(false);
}
System.out.print("Buzzer volume (0-100, Enter for no change): ");
String updateSettingsBuzzerVolume = "";
try {
updateSettingsBuzzerVolume = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (!updateSettingsBuzzerVolume.equals("")) {
settings.setBuzzerVolume(Integer.parseInt(updateSettingsBuzzerVolume));
}
System.out.print("Set a new alarm pattern? (y for yes, n for no): ");
String updateSettingsAlarmPattern = "";
try {
updateSettingsAlarmPattern = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsAlarmPattern.equalsIgnoreCase("y")) {
AlarmPattern alarmPattern = new AlarmPattern();
System.out.print("Time lights/buzzer are on (in milliseconds, default=400): ");
String updateSettingsInput = "";
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setOnTime(Integer.parseInt(updateSettingsInput));
System.out.print("Time lights/buzzer are off (in milliseconds, default=50): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setOffTime(Integer.parseInt(updateSettingsInput));
System.out.print("Time lights are on after last cycle (in milliseconds, default=7000): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setLightsHoldTime(Integer.parseInt(updateSettingsInput));
System.out.print("Number of cycles (default=5): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setCount(Integer.parseInt(updateSettingsInput));
settings.setAlarmPattern(alarmPattern);
}
try {
api.updateSettings(settings);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 103: // g
System.out.println("Send heartbeat");
try {
api.heartbeat();
} catch (Exception e) {
e.printStackTrace();
}
break;
case 104: // h
System.out.print("On what hostname or IP address is this system reachable by the !D Top or !D Gate: ");
String countEpcHostname = "";
try {
countEpcHostname = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
countEpc(api, countEpcHostname);
System.exit(0);
break;
}
}
}
| public static void main(String[] args) {
System.out.println("Store !D API tester for !D Top and !D Gate version 1.17 Java");
if (args.length==0)
{
System.out.println("Please use URL of device as parameter, for example: http://localhost:8081");
System.out.println("Optionally, you can use the hostname of this computer as second parameter to start automatic testing.");
System.out.println("Optionally, you can use the \"count\" as third parameter to count unique EPCs.");
System.exit(0);
}
// instantiate API wrapper
ApiWrapper api = new ApiWrapper(args[0]);
// if third argument is given, start epc counting
if (args.length==3) {
countEpc(api, args[1]);
System.exit(0);
}
// if second argument is given, start automatic testing
if (args.length==2) {
testApi(api, args[1]);
System.exit(0);
}
boolean running = true;
while(running) {
// show menu
System.out.println();
System.out.println("------------------------------------------------------");
System.out.println("0. Test connection 1. Show status");
System.out.println("c. Send action g. Send heartbeat");
System.out.println("d. Create spec, subscription and receive incoming events");
System.out.println("e. Get settings f. Update settings");
System.out.println("h. Show number of unique EPCs and write them to file");
System.out.println("-- SPECS -- -- SUBSCRIPTIONS --");
System.out.println("2. Show all specs 7. Show all subscriptions");
System.out.println("3. Create new spec 8. Create new subscription");
System.out.println("4. Show a spec 9. Show a subscription");
System.out.println("5. Update a spec a. Update a subscription");
System.out.println("6. Delete a spec b. Delete a subscription");
System.out.println("Please enter your choice and press Enter, or just Enter to exit.");
// get choice
BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(System.in));
String input = "";
try {
input = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
// exit if no choice made
if (input.length()==0) {
System.exit(0);
}
// print line
System.out.println("------------------------------------------------------");
// check what choice has been made
int keycode = input.codePointAt(0);
switch(keycode) {
case 48: // 0
System.out.println("Test connection");
api.testConnection();
break;
case 49: // 1
System.out.println("Show status");
try {
System.out.println(api.getStatus().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 50: // 2
System.out.println("Show specs");
try {
System.out.println(api.getSpecs().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 51: // 3
System.out.println("Create new spec");
System.out.print("Enter a name: ");
String createSpecName = "Test";
try {
createSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.println("Which events?");
System.out.println("1 = rfid.tag.arrive");
System.out.println("2 = rfid.tag.move");
System.out.println("3 = rfid.tag.arrive AND rfid.tag.move");
String createSpecOptions = "3";
try {
createSpecOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
String[] createSpecEvents;
if (createSpecOptions.equals("1")) {
createSpecEvents = new String[1];
createSpecEvents[0] = "rfid.tag.arrive";
} else if (createSpecOptions.equals("2")) {
createSpecEvents = new String[1];
createSpecEvents[0] = "rfid.tag.move";
} else {
createSpecEvents = new String[2];
createSpecEvents[0] = "rfid.tag.arrive";
createSpecEvents[1] = "rfid.tag.move";
}
Spec createSpec = new Spec(0, createSpecName, createSpecEvents);
try {
System.out.println(api.createSpec(createSpec).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 52: // 4
System.out.println("Show a spec");
System.out.print("Enter an ID: ");
String showSpecId = "";
try {
showSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
System.out.println(api.getSpec(Integer.parseInt(showSpecId)).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 53: // 5
System.out.println("Update a spec");
System.out.print("Enter ID of spec to update: ");
String updateSpecId = "";
try {
updateSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Enter a name: ");
String updateSpecName = "Test";
try {
updateSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.println("Which events?");
System.out.println("1 = rfid.tag.arrive");
System.out.println("2 = rfid.tag.move");
System.out.println("3 = rfid.tag.arrive AND rfid.tag.move");
String updateSpecOptions = "3";
try {
updateSpecOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
String[] updateSpecEvents;
if (updateSpecOptions.equals("1")) {
updateSpecEvents = new String[1];
updateSpecEvents[0] = "rfid.tag.arrive";
} else if (updateSpecOptions.equals("2")) {
updateSpecEvents = new String[1];
updateSpecEvents[0] = "rfid.tag.move";
} else {
updateSpecEvents = new String[2];
updateSpecEvents[0] = "rfid.tag.arrive";
updateSpecEvents[1] = "rfid.tag.move";
}
Spec updateSpec = new Spec(Integer.parseInt(updateSpecId), updateSpecName, updateSpecEvents);
try {
System.out.println(api.updateSpec(updateSpec).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 54: // 6
System.out.println("Delete a spec");
System.out.print("Enter an ID: ");
String deleteSpecId = "";
try {
deleteSpecId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
api.deleteSpec(Integer.parseInt(deleteSpecId));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 55: // 7
System.out.println("Show subscriptions");
try {
System.out.println(api.getSubscriptions().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 56: // 8
System.out.println("Create new subscription");
System.out.print("Enter name of a spec: ");
String createSubscriptionSpecName = "";
try {
createSubscriptionSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("URI to send events to: ");
String createSubscriptionUri = "";
try {
createSubscriptionUri = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("External reference (optional): ");
String createSubscriptionExternRef = "";
try {
createSubscriptionExternRef = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Requested lease time in minutes: ");
String createSubscriptionLease = "";
try {
createSubscriptionLease = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
Integer createSubscriptionLeaseTime = 0;
if (createSubscriptionLease.length()>0) {
createSubscriptionLeaseTime = Integer.parseInt(createSubscriptionLease);
}
Subscription createSubscription = new Subscription(0, createSubscriptionSpecName, createSubscriptionUri, createSubscriptionExternRef, createSubscriptionLeaseTime);
try {
System.out.println(api.createSubscription(createSubscription).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 57: // 9
System.out.println("Show a subscription");
System.out.print("Enter an ID: ");
String showSubscriptionId = "";
try {
showSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
System.out.println(api.getSubscription(Integer.parseInt(showSubscriptionId)).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 97: // a
System.out.println("Update a subscription");
System.out.print("Enter ID of subscription to update: ");
String updateSubscriptionId = "";
try {
updateSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Enter name of a spec: ");
String updateSubscriptionSpecName = "";
try {
updateSubscriptionSpecName = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("URI to send events to: ");
String updateSubscriptionUri = "";
try {
updateSubscriptionUri = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("External reference (optional): ");
String updateSubscriptionExternRef = "";
try {
updateSubscriptionExternRef = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Requested lease time in minutes: ");
String updateSubscriptionLease = "";
try {
updateSubscriptionLease = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
Integer updateSubscriptionLeaseTime = 0;
if (updateSubscriptionLease.length()>0) {
updateSubscriptionLeaseTime = Integer.parseInt(updateSubscriptionLease);
}
Subscription updateSubscription = new Subscription(Integer.parseInt(updateSubscriptionId), updateSubscriptionSpecName, updateSubscriptionUri, updateSubscriptionExternRef, updateSubscriptionLeaseTime);
try {
System.out.println(api.updateSubscription(updateSubscription).toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 98: // b
System.out.println("Delete a subscription");
System.out.print("Enter an ID: ");
String deleteSubscriptionId = "";
try {
deleteSubscriptionId = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
api.deleteSubscription(Integer.parseInt(deleteSubscriptionId));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 99: // c
System.out.println("Send an action");
System.out.println("Which action?");
System.out.println("1 = blink");
System.out.println("2 = beep");
System.out.println("3 = blink and beep");
String sendActionOptions = "3";
try {
sendActionOptions = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("How many times: ");
String sendActionTimes = "";
try {
sendActionTimes = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp/buzzer is on (in milliseconds): ");
String sendActionOnTime = "";
try {
sendActionOnTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp/buzzer is off (in milliseconds): ");
String sendActionOffTime = "";
try {
sendActionOffTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
System.out.print("Time the lamp is on afterwards (in milliseconds): ");
String sendActionHoldTime = "";
try {
sendActionHoldTime = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
try {
String sendActionAction = "";
if (sendActionOptions.equals("1")) {
sendActionAction = "blink";
} else if (sendActionOptions.equals("2")) {
sendActionAction = "beep";
} else if (sendActionOptions.equals("3")) {
sendActionAction = "blinkAndBeep";
}
Action[] actions = new Action[1];
actions[0] = new Action(sendActionAction, Integer.parseInt(sendActionTimes), Integer.parseInt(sendActionOnTime), Integer.parseInt(sendActionOffTime), Integer.parseInt(sendActionHoldTime));
api.sendActions(new Actions(actions));
} catch (Exception e) {
e.printStackTrace();
}
break;
case 100: // d
System.out.print("On what hostname or IP address is this system reachable by the !D Top or !D Gate: ");
String testApiHostname = "";
try {
testApiHostname = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
testApi(api, testApiHostname);
break;
case 101: // e
System.out.println("Show settings");
try {
System.out.println(api.getSettings().toString());
} catch (Exception e) {
e.printStackTrace();
}
break;
case 102: // f
System.out.println("Update settings");
Settings settings = new Settings();
System.out.print("Enable RFID reader (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableReader = "";
try {
updateSettingsEnableReader = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableReader.equalsIgnoreCase("y")) {
settings.setReaderEnabled(true);
} else if (updateSettingsEnableReader.equalsIgnoreCase("n")) {
settings.setReaderEnabled(false);
}
System.out.print("Enable lights (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableLights = "";
try {
updateSettingsEnableLights = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableLights.equalsIgnoreCase("y")) {
settings.setLightsEnabled(true);
} else if (updateSettingsEnableLights.equalsIgnoreCase("n")) {
settings.setLightsEnabled(false);
}
System.out.print("Enable buzzer (y for yes, n for no, anything else for no change): ");
String updateSettingsEnableBuzzer = "";
try {
updateSettingsEnableBuzzer = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsEnableBuzzer.equalsIgnoreCase("y")) {
settings.setBuzzerEnabled(true);
} else if (updateSettingsEnableBuzzer.equalsIgnoreCase("n")) {
settings.setBuzzerEnabled(false);
}
System.out.print("Buzzer volume (0-100, Enter for no change): ");
String updateSettingsBuzzerVolume = "";
try {
updateSettingsBuzzerVolume = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (!updateSettingsBuzzerVolume.equals("")) {
settings.setBuzzerVolume(Integer.parseInt(updateSettingsBuzzerVolume));
}
System.out.print("Set a new alarm pattern? (y for yes, n for no): ");
String updateSettingsAlarmPattern = "";
try {
updateSettingsAlarmPattern = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
if (updateSettingsAlarmPattern.equalsIgnoreCase("y")) {
AlarmPattern alarmPattern = new AlarmPattern();
System.out.print("Time lights/buzzer are on (in milliseconds, default=400): ");
String updateSettingsInput = "";
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setOnTime(Integer.parseInt(updateSettingsInput));
System.out.print("Time lights/buzzer are off (in milliseconds, default=50): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setOffTime(Integer.parseInt(updateSettingsInput));
System.out.print("Time lights are on after last cycle (in milliseconds, default=7000): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setLightsHoldTime(Integer.parseInt(updateSettingsInput));
System.out.print("Number of cycles (default=5): ");
try {
updateSettingsInput = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
alarmPattern.setCount(Integer.parseInt(updateSettingsInput));
settings.setAlarmPattern(alarmPattern);
}
try {
api.updateSettings(settings);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 103: // g
System.out.println("Send heartbeat");
try {
api.heartbeat();
} catch (Exception e) {
e.printStackTrace();
}
break;
case 104: // h
System.out.print("On what hostname or IP address is this system reachable by the !D Top or !D Gate: ");
String countEpcHostname = "";
try {
countEpcHostname = inputBuffer.readLine();
} catch (IOException e) {
System.exit(0);
}
countEpc(api, countEpcHostname);
System.exit(0);
break;
}
}
}
|
diff --git a/src/logic/searches/localSearch.java b/src/logic/searches/localSearch.java
index b20bd65..da7316d 100644
--- a/src/logic/searches/localSearch.java
+++ b/src/logic/searches/localSearch.java
@@ -1,34 +1,34 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package logic.searches;
import data.Solution;
import logic.searches.neighborhoods.INeighborhood;
import logic.searches.stepfunctions.IStepFunction;
/**
* @author Christian
*/
public class LocalSearch {
public Solution search(IStepFunction fs, INeighborhood n) {
GraspSearch gs = new GraspSearch("", "", "");
Solution s = gs.run();
do {
- Solution tmp = fs.run(s, n);
+ Solution tmp = fs.select(s, n);
if (s.calculate_costs() > tmp.calculate_costs())
s = tmp;
- } while (fs.breakup());
+ } while (false);
return s;
}
}
| false | true | public Solution search(IStepFunction fs, INeighborhood n) {
GraspSearch gs = new GraspSearch("", "", "");
Solution s = gs.run();
do {
Solution tmp = fs.run(s, n);
if (s.calculate_costs() > tmp.calculate_costs())
s = tmp;
} while (fs.breakup());
return s;
}
| public Solution search(IStepFunction fs, INeighborhood n) {
GraspSearch gs = new GraspSearch("", "", "");
Solution s = gs.run();
do {
Solution tmp = fs.select(s, n);
if (s.calculate_costs() > tmp.calculate_costs())
s = tmp;
} while (false);
return s;
}
|
diff --git a/scm-webapp/src/main/java/sonia/scm/security/ConfigurableLoginAttemptHandler.java b/scm-webapp/src/main/java/sonia/scm/security/ConfigurableLoginAttemptHandler.java
index 8cd9b843f..18bfbf375 100644
--- a/scm-webapp/src/main/java/sonia/scm/security/ConfigurableLoginAttemptHandler.java
+++ b/scm-webapp/src/main/java/sonia/scm/security/ConfigurableLoginAttemptHandler.java
@@ -1,331 +1,331 @@
/**
* Copyright (c) 2010, Sebastian Sdorra
* 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. 3. Neither the name of SCM-Manager;
* nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE REGENTS 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.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.security;
//~--- non-JDK imports --------------------------------------------------------
import com.google.common.base.Objects;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.config.ScmConfiguration;
import sonia.scm.web.security.AuthenticationResult;
//~--- JDK imports ------------------------------------------------------------
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
*
* @author Sebastian Sdorra
*/
@Singleton
public class ConfigurableLoginAttemptHandler implements LoginAttemptHandler
{
/**
* the logger for ConfigurableLoginAttemptHandler
*/
private static final Logger logger =
LoggerFactory.getLogger(ConfigurableLoginAttemptHandler.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
* @param configuration
*/
@Inject
public ConfigurableLoginAttemptHandler(ScmConfiguration configuration)
{
this.configuration = configuration;
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param token
*
* @throws AuthenticationException
*/
@Override
public void beforeAuthentication(AuthenticationToken token)
throws AuthenticationException
{
if (isEnabled())
{
handleBeforeAuthentication(token);
}
else
{
logger.trace("LoginAttemptHandler is disabled");
}
}
/**
* Method description
*
*
* @param token
* @param result
*
* @throws AuthenticationException
*/
@Override
public void onSuccessfulAuthentication(AuthenticationToken token,
AuthenticationResult result)
throws AuthenticationException
{
if (isEnabled())
{
handleOnSuccessfulAuthentication(token);
}
else
{
logger.trace("LoginAttemptHandler is disabled");
}
}
/**
* Method description
*
*
* @param token
* @param result
*
* @throws AuthenticationException
*/
@Override
public void onUnsuccessfulAuthentication(AuthenticationToken token,
AuthenticationResult result)
throws AuthenticationException
{
if (isEnabled())
{
handleOnUnsuccessfulAuthentication(token);
}
else
{
logger.trace("LoginAttemptHandler is disabled");
}
}
/**
* Method description
*
*
* @param token
*/
private void handleBeforeAuthentication(AuthenticationToken token)
{
LoginAttempt attempt = getAttempt(token);
long time = System.currentTimeMillis() - attempt.lastAttempt;
if (time > getLoginAttemptLimitTimeout())
{
logger.debug("reset login attempts for {}, because of time",
token.getPrincipal());
attempt.reset();
}
else if (attempt.counter >= configuration.getLoginAttemptLimit())
{
logger.warn("account {} is temporary locked, because of {}",
token.getPrincipal(), attempt);
attempt.increase();
- throw new ExcessiveAttemptsException("account is temporarly locked");
+ throw new ExcessiveAttemptsException("account is temporary locked");
}
}
/**
* Method description
*
*
* @param token
* @param result
*
* @throws AuthenticationException
*/
private void handleOnSuccessfulAuthentication(AuthenticationToken token)
throws AuthenticationException
{
logger.debug("reset login attempts for {}, because of successful login",
token.getPrincipal());
getAttempt(token).reset();
}
/**
* Method description
*
*
* @param token
* @param result
*
* @throws AuthenticationException
*/
private void handleOnUnsuccessfulAuthentication(AuthenticationToken token)
throws AuthenticationException
{
logger.debug("increase failed login attempts for {}", token.getPrincipal());
LoginAttempt attempt = getAttempt(token);
attempt.increase();
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @param token
*
* @return
*/
private LoginAttempt getAttempt(AuthenticationToken token)
{
LoginAttempt freshAttempt = new LoginAttempt();
LoginAttempt attempt = attempts.putIfAbsent(token.getPrincipal(),
freshAttempt);
if (attempt == null)
{
attempt = freshAttempt;
}
return attempt;
}
/**
* Method description
*
*
* @return
*/
private long getLoginAttemptLimitTimeout()
{
return TimeUnit.SECONDS.toMillis(
configuration.getLoginAttemptLimitTimeout());
}
/**
* Method description
*
*
* @return
*/
private boolean isEnabled()
{
return (configuration.getLoginAttemptLimit() > 0)
&& (configuration.getLoginAttemptLimitTimeout() > 0l);
}
//~--- inner classes --------------------------------------------------------
/**
* Login attempt
*/
private static class LoginAttempt
{
/**
* Method description
*
*
* @return
*/
@Override
public String toString()
{
//J-
return Objects.toStringHelper(this)
.add("counter", counter)
.add("lastAttempt", lastAttempt)
.toString();
//J+
}
/**
* Method description
*
*/
synchronized void increase()
{
counter++;
lastAttempt = System.currentTimeMillis();
}
/**
* Method description
*
*/
synchronized void reset()
{
lastAttempt = -1l;
counter = 0;
}
//~--- fields -------------------------------------------------------------
/** Field description */
private int counter = 0;
/** Field description */
private long lastAttempt = -1l;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private final ConcurrentMap<Object, LoginAttempt> attempts =
new ConcurrentHashMap<Object, LoginAttempt>();
/** Field description */
private final ScmConfiguration configuration;
}
| true | true | private void handleBeforeAuthentication(AuthenticationToken token)
{
LoginAttempt attempt = getAttempt(token);
long time = System.currentTimeMillis() - attempt.lastAttempt;
if (time > getLoginAttemptLimitTimeout())
{
logger.debug("reset login attempts for {}, because of time",
token.getPrincipal());
attempt.reset();
}
else if (attempt.counter >= configuration.getLoginAttemptLimit())
{
logger.warn("account {} is temporary locked, because of {}",
token.getPrincipal(), attempt);
attempt.increase();
throw new ExcessiveAttemptsException("account is temporarly locked");
}
}
| private void handleBeforeAuthentication(AuthenticationToken token)
{
LoginAttempt attempt = getAttempt(token);
long time = System.currentTimeMillis() - attempt.lastAttempt;
if (time > getLoginAttemptLimitTimeout())
{
logger.debug("reset login attempts for {}, because of time",
token.getPrincipal());
attempt.reset();
}
else if (attempt.counter >= configuration.getLoginAttemptLimit())
{
logger.warn("account {} is temporary locked, because of {}",
token.getPrincipal(), attempt);
attempt.increase();
throw new ExcessiveAttemptsException("account is temporary locked");
}
}
|
diff --git a/xbean-finder/src/main/java/org/apache/xbean/finder/ClassLoaders.java b/xbean-finder/src/main/java/org/apache/xbean/finder/ClassLoaders.java
index b7d82219..8b7a4285 100644
--- a/xbean-finder/src/main/java/org/apache/xbean/finder/ClassLoaders.java
+++ b/xbean-finder/src/main/java/org/apache/xbean/finder/ClassLoaders.java
@@ -1,90 +1,90 @@
/**
* 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.xbean.finder;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public final class ClassLoaders {
private static final boolean DONT_USE_GET_URLS = Boolean.getBoolean("xbean.finder.use.get-resources");
private static final ClassLoader SYSTEM = ClassLoader.getSystemClassLoader();
public static Set<URL> findUrls(final ClassLoader classLoader) throws IOException {
- if (classLoader == null) {
+ if (classLoader == null || classLoader.getClass().getName().equals("sun.misc.Launcher$ExtClassLoader")) {
return Collections.emptySet();
}
final Set<URL> urls;
if (URLClassLoader.class.isInstance(classLoader) && !DONT_USE_GET_URLS) {
urls = new HashSet<URL>();
if (!isSurefire(classLoader)) {
urls.addAll(Arrays.asList(URLClassLoader.class.cast(classLoader).getURLs()));
urls.addAll(findUrls(classLoader.getParent()));
} else { // http://jira.codehaus.org/browse/SUREFIRE-928 - we could reuse findUrlFromResources but this seems faster
urls.addAll(fromClassPath());
}
} else {
urls = findUrlFromResources(classLoader);
}
return urls;
}
private static boolean isSurefire(ClassLoader classLoader) {
return System.getProperty("surefire.real.class.path") != null && classLoader == SYSTEM;
}
private static Collection<URL> fromClassPath() {
final String[] cp = System.getProperty("java.class.path").split(System.getProperty("path.separator", ":"));
final Set<URL> urls = new HashSet<URL>();
for (final String path : cp) {
try {
if (path.endsWith(".jar")) {
urls.add(new URL("jar:file://" + path + "!/"));
} else {
urls.add(new URL("file://" + path));
}
} catch (final MalformedURLException e) {
// ignore
}
}
return urls;
}
public static Set<URL> findUrlFromResources(final ClassLoader classLoader) throws IOException {
final Set<URL> set = new HashSet<URL>();
for (final URL url : Collections.list(classLoader.getResources("META-INF"))) {
final String externalForm = url.toExternalForm();
set.add(new URL(externalForm.substring(0, externalForm.lastIndexOf("META-INF"))));
}
set.addAll(Collections.list(classLoader.getResources("")));
return set;
}
private ClassLoaders() {
// no-op
}
}
| true | true | public static Set<URL> findUrls(final ClassLoader classLoader) throws IOException {
if (classLoader == null) {
return Collections.emptySet();
}
final Set<URL> urls;
if (URLClassLoader.class.isInstance(classLoader) && !DONT_USE_GET_URLS) {
urls = new HashSet<URL>();
if (!isSurefire(classLoader)) {
urls.addAll(Arrays.asList(URLClassLoader.class.cast(classLoader).getURLs()));
urls.addAll(findUrls(classLoader.getParent()));
} else { // http://jira.codehaus.org/browse/SUREFIRE-928 - we could reuse findUrlFromResources but this seems faster
urls.addAll(fromClassPath());
}
} else {
urls = findUrlFromResources(classLoader);
}
return urls;
}
| public static Set<URL> findUrls(final ClassLoader classLoader) throws IOException {
if (classLoader == null || classLoader.getClass().getName().equals("sun.misc.Launcher$ExtClassLoader")) {
return Collections.emptySet();
}
final Set<URL> urls;
if (URLClassLoader.class.isInstance(classLoader) && !DONT_USE_GET_URLS) {
urls = new HashSet<URL>();
if (!isSurefire(classLoader)) {
urls.addAll(Arrays.asList(URLClassLoader.class.cast(classLoader).getURLs()));
urls.addAll(findUrls(classLoader.getParent()));
} else { // http://jira.codehaus.org/browse/SUREFIRE-928 - we could reuse findUrlFromResources but this seems faster
urls.addAll(fromClassPath());
}
} else {
urls = findUrlFromResources(classLoader);
}
return urls;
}
|
diff --git a/trunk/xmlvm/src/xmlvm/org/xmlvm/proc/out/DEXmlvmOutputProcess.java b/trunk/xmlvm/src/xmlvm/org/xmlvm/proc/out/DEXmlvmOutputProcess.java
index 4e566962..b126d404 100644
--- a/trunk/xmlvm/src/xmlvm/org/xmlvm/proc/out/DEXmlvmOutputProcess.java
+++ b/trunk/xmlvm/src/xmlvm/org/xmlvm/proc/out/DEXmlvmOutputProcess.java
@@ -1,838 +1,838 @@
/*
* Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language
*
* 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., 675 Mass
* Ave, Cambridge, MA 02139, USA.
*
* For more information, visit the XMLVM Home Page at http://www.xmlvm.org
*/
package org.xmlvm.proc.out;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.RuntimeErrorException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xmlvm.Log;
import org.xmlvm.main.Arguments;
import org.xmlvm.proc.XmlvmProcess;
import org.xmlvm.proc.XmlvmProcessImpl;
import org.xmlvm.proc.XmlvmResource;
import org.xmlvm.proc.XmlvmResourceProvider;
import org.xmlvm.proc.XmlvmResource.Type;
import org.xmlvm.proc.in.InputProcess.ClassInputProcess;
import com.android.dx.cf.code.ConcreteMethod;
import com.android.dx.cf.code.Ropper;
import com.android.dx.cf.direct.DirectClassFile;
import com.android.dx.cf.direct.StdAttributeFactory;
import com.android.dx.cf.iface.Field;
import com.android.dx.cf.iface.FieldList;
import com.android.dx.cf.iface.Method;
import com.android.dx.cf.iface.MethodList;
import com.android.dx.dex.cf.CfTranslator;
import com.android.dx.dex.code.CatchHandlerList;
import com.android.dx.dex.code.CatchTable;
import com.android.dx.dex.code.CodeAddress;
import com.android.dx.dex.code.CstInsn;
import com.android.dx.dex.code.DalvCode;
import com.android.dx.dex.code.DalvInsn;
import com.android.dx.dex.code.DalvInsnList;
import com.android.dx.dex.code.Dop;
import com.android.dx.dex.code.Dops;
import com.android.dx.dex.code.HighRegisterPrefix;
import com.android.dx.dex.code.LocalList;
import com.android.dx.dex.code.LocalSnapshot;
import com.android.dx.dex.code.LocalStart;
import com.android.dx.dex.code.OddSpacer;
import com.android.dx.dex.code.PositionList;
import com.android.dx.dex.code.RopTranslator;
import com.android.dx.dex.code.SimpleInsn;
import com.android.dx.dex.code.SwitchData;
import com.android.dx.dex.code.TargetInsn;
import com.android.dx.dex.code.CatchTable.Entry;
import com.android.dx.rop.code.AccessFlags;
import com.android.dx.rop.code.DexTranslationAdvice;
import com.android.dx.rop.code.LocalVariableExtractor;
import com.android.dx.rop.code.LocalVariableInfo;
import com.android.dx.rop.code.RegisterSpec;
import com.android.dx.rop.code.RegisterSpecList;
import com.android.dx.rop.code.RopMethod;
import com.android.dx.rop.code.TranslationAdvice;
import com.android.dx.rop.cst.Constant;
import com.android.dx.rop.cst.CstMemberRef;
import com.android.dx.rop.cst.CstMethodRef;
import com.android.dx.rop.cst.CstNat;
import com.android.dx.rop.cst.CstString;
import com.android.dx.rop.cst.CstType;
import com.android.dx.rop.type.Prototype;
import com.android.dx.rop.type.StdTypeList;
import com.android.dx.rop.type.TypeList;
import com.android.dx.ssa.Optimizer;
import com.android.dx.util.ExceptionWithContext;
import com.android.dx.util.IntList;
/**
* This OutputProcess emits XMLVM code containing register-based DEX
* instructions (XMLVM-DEX).
* <p>
* Android's own DX compiler tool is used to parse class files and to create the
* register-based DEX code in-memory which is then converted to XML.
* <p>
* TODO(Sascha): Work in progress!
*/
public class DEXmlvmOutputProcess extends XmlvmProcessImpl<XmlvmProcess<?>> implements
XmlvmResourceProvider {
/**
* A little helper class that contains package- and class name.
*/
private static class PackagePlusClassName {
public String packageName = "";
public String className = "";
public PackagePlusClassName(String className) {
this.className = className;
}
public PackagePlusClassName(String packageName, String className) {
this.packageName = packageName;
this.className = className;
}
@Override
public String toString() {
if (packageName.isEmpty()) {
return className;
} else {
return packageName + "." + className;
}
}
}
private static final boolean LOTS_OF_DEBUG = false;
private static final String DEXMLVM_ENDING = ".dexmlvm";
private static final Namespace NS_XMLVM = XmlvmResource.xmlvmNamespace;
private static final Namespace NS_DEX = Namespace.getNamespace("dex",
"http://xmlvm.org/dex");
private List<OutputFile> outputFiles = new ArrayList<OutputFile>();
private List<XmlvmResource> generatedResources = new ArrayList<XmlvmResource>();
private static Element lastInvokeInstruction = null;
public DEXmlvmOutputProcess(Arguments arguments) {
super(arguments);
// We can either read class files directly or use the
// JavaByteCodeOutputProcess to use generated bytecode as the input.
addSupportedInput(ClassInputProcess.class);
addSupportedInput(JavaByteCodeOutputProcess.class);
}
@Override
public List<OutputFile> getOutputFiles() {
return outputFiles;
}
@Override
public boolean process() {
generatedResources.clear();
List<XmlvmProcess<?>> preprocesses = preprocess();
for (XmlvmProcess<?> process : preprocesses) {
for (OutputFile preOutputFile : process.getOutputFiles()) {
OutputFile outputFile = generateDEXmlvmFile(preOutputFile);
if (outputFile == null) {
return false;
}
outputFiles.add(outputFile);
}
}
return true;
}
@Override
public List<XmlvmResource> getXmlvmResources() {
return generatedResources;
}
private OutputFile generateDEXmlvmFile(OutputFile classFile) {
Log.debug("DExing:" + classFile.getFileName());
DirectClassFile directClassFile = new DirectClassFile(classFile.getDataAsBytes(), classFile
.getFileName(), false);
Document document = createDocument();
String className = process(directClassFile, document.getRootElement()).replace('.', '_');
generatedResources.add(new XmlvmResource(className, Type.DEX, document));
String fileName = className + DEXMLVM_ENDING;
OutputFile result = new OutputFile();
result.setLocation(arguments.option_out());
result.setFileName(fileName);
result.setData(documentToString(document));
return result;
}
/**
* Converts a class name in the form of a/b/C into a
* {@link PackagePlusClassName} object.
*
*/
private static PackagePlusClassName parseClassName(String packagePlusClassName) {
int lastSlash = packagePlusClassName.lastIndexOf('/');
if (lastSlash == -1) {
return new PackagePlusClassName(packagePlusClassName);
}
String className = packagePlusClassName.substring(lastSlash + 1);
String packageName = packagePlusClassName.substring(0, lastSlash).replace('/', '.');
return new PackagePlusClassName(packageName, className);
}
/**
* Creates a basic XMLVM document.
*/
private static Document createDocument() {
Element root = new Element("xmlvm", NS_XMLVM);
root.addNamespaceDeclaration(NS_DEX);
Document document = new Document();
document.addContent(root);
return document;
}
/**
* Process the given Java Class file and add the classes to the given root.
*
* @param cf
* the class file to process
* @param root
* the root element to append the classes to
* @return the class name for the DEXMLVM file
*/
private String process(DirectClassFile cf, Element root) {
cf.setAttributeFactory(StdAttributeFactory.THE_ONE);
cf.getMagic();
Element classElement = processClass(cf, root);
processFields(cf.getFields(), classElement);
MethodList methods = cf.getMethods();
int sz = methods.size();
for (int i = 0; i < sz; i++) {
Method one = methods.get(i);
try {
processMethod(one, cf, classElement);
} catch (RuntimeException ex) {
String msg = "...while processing " + one.getName().toHuman() + " "
+ one.getDescriptor().toHuman();
throw ExceptionWithContext.withContext(ex, msg);
}
}
CstType thisClass = cf.getThisClass();
return thisClass.getClassType().toHuman();
}
/**
* Creates an XMLVM element for the given type and appends it to the given
* root element.
*
* @param cf
* the {@link DirectClassFile} instance of this class
* @param root
* the root element to append the generated element to
* @return the generated element
*/
private static Element processClass(DirectClassFile cf, Element root) {
Element classElement = new Element("class", NS_XMLVM);
CstType type = cf.getThisClass();
PackagePlusClassName parsedClassName = parseClassName(type.getClassType().getClassName());
classElement.setAttribute("name", parsedClassName.className);
classElement.setAttribute("package", parsedClassName.packageName);
classElement.setAttribute("extends", parseClassName(
cf.getSuperclass().getClassType().getClassName()).toString());
processAccessFlags(cf.getAccessFlags(), classElement);
TypeList interfaces = cf.getInterfaces();
if (interfaces.size() > 0) {
String interfaceList = "";
for (int i = 0; i < interfaces.size(); ++i) {
if (i > 0) {
interfaceList += ",";
}
interfaceList += parseClassName(interfaces.getType(i).getClassName());
}
classElement.setAttribute("interfaces", interfaceList);
}
root.addContent(classElement);
return classElement;
}
/**
* Processes the fields and adds corresponding elements to the class
* element.
*/
private static void processFields(FieldList fieldList, Element classElement) {
for (int i = 0; i < fieldList.size(); ++i) {
Field field = fieldList.get(i);
Element fieldElement = new Element("field", NS_XMLVM);
fieldElement.setAttribute("name", field.getName().toHuman());
fieldElement.setAttribute("type", field.getNat().getFieldType().toHuman());
processAccessFlags(field.getAccessFlags(), fieldElement);
classElement.addContent(fieldElement);
}
}
/**
* Creates an XMLVM element for the given method and appends it to the given
* class element.
* <p>
* This method is roughly based on
* {@link CfTranslator#translate(String, byte[], com.android.dx.dex.cf.CfOptions)}
*
* @param method
* the method to create the element for
* @param classElement
* the class element to append the generated element to
* @param cf
* the class file where this method was originally defined in
*/
private static void processMethod(Method method, DirectClassFile cf, Element classElement) {
final boolean localInfo = true;
final int positionInfo = PositionList.NONE;
CstMethodRef meth = new CstMethodRef(method.getDefiningClass(), method.getNat());
// Extract flags for this method.
int accessFlags = method.getAccessFlags();
boolean isNative = AccessFlags.isNative(accessFlags);
boolean isStatic = AccessFlags.isStatic(accessFlags);
boolean isAbstract = AccessFlags.isAbstract(accessFlags);
// Create XMLVM element for this method
Element methodElement = new Element("method", NS_XMLVM);
methodElement.setAttribute("name", method.getName().getString());
classElement.addContent(methodElement);
// Set the access flag attrobutes for this method.
processAccessFlags(accessFlags, methodElement);
// Create signature element.
methodElement.addContent(processSignature(meth));
// Create code element.
Element codeElement = new Element("code", NS_DEX);
methodElement.addContent(codeElement);
if (isNative || isAbstract) {
// There's no code for native or abstract methods.
} else {
ConcreteMethod concrete = new ConcreteMethod(method, cf,
(positionInfo != PositionList.NONE), localInfo);
TranslationAdvice advice = DexTranslationAdvice.THE_ONE;
RopMethod rmeth = Ropper.convert(concrete, advice);
int paramSize = meth.getParameterWordCount(isStatic);
String canonicalName = method.getDefiningClass().getClassType().getDescriptor() + "."
+ method.getName().getString();
if (LOTS_OF_DEBUG) {
System.out.println("\n\nMethod: " + canonicalName);
}
// Optimize
rmeth = Optimizer.optimize(rmeth, paramSize, isStatic, localInfo, advice);
LocalVariableInfo locals = null;
if (localInfo) {
locals = LocalVariableExtractor.extract(rmeth);
}
DalvCode code = RopTranslator.translate(rmeth, positionInfo, locals, paramSize);
DalvCode.AssignIndicesCallback callback = new DalvCode.AssignIndicesCallback() {
public int getIndex(Constant cst) {
// Everything is at index 0!
return 0;
}
};
code.assignIndices(callback);
DalvInsnList instructions = code.getInsns();
codeElement.setAttribute("register-size", String.valueOf(instructions
.getRegistersSize()));
processLocals(code.getLocals(), codeElement);
processCatchTable(code.getCatches(), codeElement);
Set<Integer> targets = extractTargets(instructions);
Map<Integer, SwitchData> switchDataBlocks = extractSwitchData(instructions);
for (int j = 0; j < instructions.size(); ++j) {
processInstruction(instructions.get(j), codeElement, targets, switchDataBlocks);
}
}
}
/**
* Sets attributes in the element according to the access flags given.
*/
private static void processAccessFlags(int accessFlags, Element element) {
boolean isStatic = AccessFlags.isStatic(accessFlags);
boolean isPrivate = AccessFlags.isPrivate(accessFlags);
boolean isPublic = AccessFlags.isPublic(accessFlags);
boolean isNative = AccessFlags.isNative(accessFlags);
boolean isAbstract = AccessFlags.isAbstract(accessFlags);
boolean isSynthetic = AccessFlags.isSynthetic(accessFlags);
boolean isInterface = AccessFlags.isInterface(accessFlags);
setAttributeIfTrue(element, "isStatic", isStatic);
setAttributeIfTrue(element, "isPrivate", isPrivate);
setAttributeIfTrue(element, "isPublic", isPublic);
setAttributeIfTrue(element, "isNative", isNative);
setAttributeIfTrue(element, "isAbstract", isAbstract);
setAttributeIfTrue(element, "isSynthetic", isSynthetic);
setAttributeIfTrue(element, "isInterface", isInterface);
}
/**
* Extracts the local variables and add {@code var} elements to the {@code
* code} element for each of them.
*/
private static void processLocals(LocalList localList, Element codeElement) {
for (int i = 0; i < localList.size(); ++i) {
com.android.dx.dex.code.LocalList.Entry localEntry = localList.get(i);
Element localElement = new Element("var", NS_DEX);
localElement.setAttribute("name", localEntry.getName().toHuman());
localElement.setAttribute("register", String.valueOf(localEntry.getRegister()));
localElement.setAttribute("type", localEntry.getType().toHuman());
codeElement.addContent(localElement);
}
}
private static void processCatchTable(CatchTable catchTable, Element codeElement) {
if (catchTable.size() == 0) {
return;
}
Element catchTableElement = new Element("catches", NS_DEX);
for (int i = 0; i < catchTable.size(); ++i) {
Entry entry = catchTable.get(i);
Element entryElement = new Element("entry", NS_DEX);
entryElement.setAttribute("start", String.valueOf(entry.getStart()));
entryElement.setAttribute("end", String.valueOf(entry.getEnd()));
CatchHandlerList catchHandlers = entry.getHandlers();
for (int j = 0; j < catchHandlers.size(); ++j) {
com.android.dx.dex.code.CatchHandlerList.Entry handlerEntry = catchHandlers.get(j);
Element handlerElement = new Element("handler", NS_DEX);
handlerElement.setAttribute("type", handlerEntry.getExceptionType().toHuman());
handlerElement.setAttribute("target", String.valueOf(handlerEntry.getHandler()));
entryElement.addContent(handlerElement);
}
catchTableElement.addContent(entryElement);
}
codeElement.addContent(catchTableElement);
}
/**
* Extracts targets that are being jumped to, so we can later add labels at
* the corresponding positions when generating the code.
*
* @return a set containing the addresses of all jump targets
*/
private static Set<Integer> extractTargets(DalvInsnList instructions) {
Set<Integer> targets = new HashSet<Integer>();
for (int i = 0; i < instructions.size(); ++i) {
if (instructions.get(i) instanceof TargetInsn) {
TargetInsn targetInsn = (TargetInsn) instructions.get(i);
targets.add(targetInsn.getTargetAddress());
} else if (instructions.get(i) instanceof SwitchData) {
SwitchData switchData = (SwitchData) instructions.get(i);
CodeAddress[] caseTargets = switchData.getTargets();
for (CodeAddress caseTarget : caseTargets) {
targets.add(caseTarget.getAddress());
}
}
}
return targets;
}
/**
* Extracts all {@link SwitchData} pseudo-instructions from the given list
* of instructions.
*
* @param instructions
* the list of instructions from where to extract
* @return a map containing all found {@link SwitchData} instructions,
* indexed by address.
*/
private static Map<Integer, SwitchData> extractSwitchData(DalvInsnList instructions) {
Map<Integer, SwitchData> result = new HashMap<Integer, SwitchData>();
for (int i = 0; i < instructions.size(); ++i) {
if (instructions.get(i) instanceof SwitchData) {
SwitchData switchData = (SwitchData) instructions.get(i);
result.put(switchData.getAddress(), switchData);
}
}
return result;
}
/**
* Creates an element for the given instruction and puts it into the given
* code element. It is possible that no element is added for the given
* instruction.
*
* @param instruction
* the instruction to process
* @param codeElement
* the element to add the instruction element to
* @param targets
* the set of jump targets
*/
private static void processInstruction(DalvInsn instruction, Element codeElement,
Set<Integer> targets, Map<Integer, SwitchData> switchDataBlocks) {
Element dexInstruction = null;
if (instruction.hasAddress()) {
int address = instruction.getAddress();
if (targets.contains(address)) {
Element labelElement = new Element("label", NS_DEX);
labelElement.setAttribute("id", String.valueOf(address));
codeElement.addContent(labelElement);
targets.remove(address);
}
}
if (instruction instanceof CodeAddress) {
// Ignore.
} else if (instruction instanceof LocalSnapshot) {
- // Ingore.
+ // Ignore.
} else if (instruction instanceof OddSpacer) {
- // Ingore NOPs.
+ // Ignore NOPs.
} else if (instruction instanceof SwitchData) {
- // Ingore here because we already processes these and they were
+ // Ignore here because we already processes these and they were
// given to this method as an argument.
} else if (instruction instanceof LocalStart) {
// As we extract the locals information up-front we don't need to
// handle local-start.
} else if (instruction instanceof SimpleInsn) {
SimpleInsn simpleInsn = (SimpleInsn) instruction;
String instructionName = simpleInsn.getOpcode().getName();
// If this is a move-result instruction, we don't add it
// explicitly, but instead add the result register to the previous
// invoke instruction's return.
if (instructionName.startsWith("move-result")) {
// Sanity Check
if (simpleInsn.getRegisters().size() != 1) {
Log.error("DEXmlvmOutputProcess: Register Size doesn't fit 'move-result'.");
System.exit(-1);
}
RegisterSpec register = simpleInsn.getRegisters().get(0);
Element returnElement = lastInvokeInstruction.getChild("parameters", NS_DEX)
.getChild("return", NS_DEX);
returnElement.setAttribute("register", String.valueOf(registerNumber(register
.regString())));
} else {
RegisterSpecList registers = simpleInsn.getRegisters();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(registers, dexInstruction);
// For simple instructions with only one register, we also add
// the type of the register. This includes the return
// instructions.
if (registers.size() == 1) {
dexInstruction.setAttribute("class-type", registers.get(0).getType().toHuman());
}
}
} else if (instruction instanceof CstInsn) {
CstInsn cstInsn = (CstInsn) instruction;
if (isInvokeInstruction(cstInsn)) {
dexInstruction = processInvokeInstruction(cstInsn);
lastInvokeInstruction = dexInstruction;
} else {
dexInstruction = new Element(
sanitizeInstructionName(cstInsn.getOpcode().getName()), NS_DEX);
Constant constant = cstInsn.getConstant();
dexInstruction.setAttribute("type", constant.typeName());
if (constant instanceof CstMemberRef) {
CstMemberRef memberRef = (CstMemberRef) constant;
dexInstruction.setAttribute("class-type", memberRef.getDefiningClass()
.getClassType().toHuman());
CstNat nameAndType = memberRef.getNat();
dexInstruction.setAttribute("member-type", nameAndType.getFieldType().getType()
.toHuman());
dexInstruction.setAttribute("member-name", nameAndType.getName().toHuman());
} else if (constant instanceof CstString) {
CstString cstString = (CstString) constant;
dexInstruction.setAttribute("value", cstString.getString().getString());
} else {
dexInstruction.setAttribute("value", constant.toHuman());
}
processRegisters(cstInsn.getRegisters(), dexInstruction);
}
} else if (instruction instanceof TargetInsn) {
TargetInsn targetInsn = (TargetInsn) instruction;
String instructionName = targetInsn.getOpcode().getName();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(targetInsn.getRegisters(), dexInstruction);
if (instructionName.equals("packed-switch") || instructionName.equals("sparse-switch")) {
SwitchData switchData = switchDataBlocks.get(targetInsn.getTargetAddress());
if (switchData == null) {
Log.error("DEXmlvmOutputProcess: Couldn't find SwitchData block.");
System.exit(-1);
}
IntList cases = switchData.getCases();
CodeAddress[] caseTargets = switchData.getTargets();
// Sanity check.
if (cases.size() != caseTargets.length) {
Log.error("DEXmlvmOutputProcess: SwitchData size mismatch: cases vs targets.");
System.exit(-1);
}
for (int i = 0; i < cases.size(); ++i) {
Element caseElement = new Element("case", NS_DEX);
caseElement.setAttribute("key", String.valueOf(cases.get(i)));
caseElement.setAttribute("label", String.valueOf(caseTargets[i].getAddress()));
dexInstruction.addContent(caseElement);
}
} else {
dexInstruction
.setAttribute("target", String.valueOf(targetInsn.getTargetAddress()));
}
} else if (instruction instanceof HighRegisterPrefix) {
HighRegisterPrefix highRegisterPrefix = (HighRegisterPrefix) instruction;
SimpleInsn[] moveInstructions = highRegisterPrefix.getMoveInstructions();
for (SimpleInsn moveInstruction : moveInstructions) {
processInstruction(moveInstruction, codeElement, targets, switchDataBlocks);
}
} else {
System.err.print(">>> Unknown instruction: ");
System.err.print("(" + instruction.getClass().getName() + ") ");
System.err.print(instruction.listingString("", 0, true));
System.exit(-1);
}
if (LOTS_OF_DEBUG) {
System.out.print("(" + instruction.getClass().getName() + ") ");
System.out.print(instruction.listingString("", 0, true));
}
if (dexInstruction != null) {
codeElement.addContent(dexInstruction);
}
}
/**
* Takes the registers given and appends corresponding attributes to the
* given element.
*/
private static void processRegisters(RegisterSpecList registers, Element element) {
final String[] REGISTER_NAMES = { "vx", "vy", "vz" };
// Sanity check.
if (registers.size() > 3) {
Log.error("DEXmlvmOutputProcess.processRegisters: Too many registers.");
System.exit(-1);
}
for (int i = 0; i < registers.size(); ++i) {
// String type = registers.get(i).getTypeBearer().toHuman();
element.setAttribute(REGISTER_NAMES[i], String.valueOf(registerNumber(registers.get(i)
.regString())));
}
}
/**
* Returns whether the given instruction is an invoke instruction that can
* be handled by {@link #processInvokeInstruction(CstInsn)}.
*/
private static boolean isInvokeInstruction(CstInsn cstInsn) {
final Dop[] invokeInstructions = { Dops.INVOKE_VIRTUAL, Dops.INVOKE_VIRTUAL_RANGE,
Dops.INVOKE_STATIC, Dops.INVOKE_STATIC_RANGE, Dops.INVOKE_DIRECT,
Dops.INVOKE_DIRECT_RANGE, Dops.INVOKE_INTERFACE, Dops.INVOKE_INTERFACE_RANGE,
Dops.INVOKE_SUPER, Dops.INVOKE_SUPER_RANGE };
for (Dop dop : invokeInstructions) {
if (dop.equals(cstInsn.getOpcode())) {
return true;
}
}
return false;
}
/**
* Returns whether the given instruction is an invoke-static instruction.
*/
private static boolean isInvokeStaticInstruction(CstInsn cstInsn) {
final Dop[] staticInvokeInstructions = { Dops.INVOKE_STATIC, Dops.INVOKE_STATIC_RANGE };
for (Dop dop : staticInvokeInstructions) {
if (dop.equals(cstInsn.getOpcode())) {
return true;
}
}
return false;
}
/**
* Returns an element representing the given invoke instruction.
*/
private static Element processInvokeInstruction(CstInsn cstInsn) {
Element result = new Element(sanitizeInstructionName(cstInsn.getOpcode().getName()), NS_DEX);
CstMethodRef methodRef = (CstMethodRef) cstInsn.getConstant();
result.setAttribute("class-type", methodRef.getDefiningClass().toHuman());
result.setAttribute("method", methodRef.getNat().getName().toHuman());
RegisterSpecList registerList = cstInsn.getRegisters();
List<RegisterSpec> registers = new ArrayList<RegisterSpec>();
if (isInvokeStaticInstruction(cstInsn)) {
if (registerList.size() > 0) {
registers.add(registerList.get(0));
}
} else {
// For non-static invoke instruction, the first register is the
// instance the method is called on.
result.setAttribute("register", String.valueOf(registerNumber(registerList.get(0)
.regString())));
}
// Adds the rest of the registers, if any.
for (int i = 1; i < registerList.size(); ++i) {
registers.add(registerList.get(i));
}
result.addContent(processParameterList(methodRef, registers));
return result;
}
/**
* Processes the signature of the given method reference and returns a
* corresponding element.
*/
private static Element processParameterList(CstMethodRef methodRef, List<RegisterSpec> registers) {
Element result = new Element("parameters", NS_DEX);
Prototype prototype = methodRef.getPrototype();
StdTypeList parameters = prototype.getParameterTypes();
// Sanity check.
if (parameters.size() != registers.size()) {
Log.error("DEXmlvmOutputProcess.processParameterList: Size mismatch: "
+ "registers vs parameters");
System.exit(-1);
}
for (int i = 0; i < parameters.size(); ++i) {
Element parameterElement = new Element("parameter", NS_DEX);
parameterElement.setAttribute("type", parameters.get(i).toHuman());
parameterElement.setAttribute("register", String.valueOf(registerNumber(registers
.get(i).regString())));
result.addContent(parameterElement);
}
Element returnElement = new Element("return", NS_DEX);
returnElement.setAttribute("type", prototype.getReturnType().getType().toHuman());
result.addContent(returnElement);
return result;
}
/**
* Processes the signature of the given method reference and returns a
* corresponding element. It uses 'registers' to add register
*/
private static Element processSignature(CstMethodRef methodRef) {
Prototype prototype = methodRef.getPrototype();
StdTypeList parameters = prototype.getParameterTypes();
Element result = new Element("signature", NS_XMLVM);
for (int i = 0; i < parameters.size(); ++i) {
Element parameterElement = new Element("parameter", NS_XMLVM);
parameterElement.setAttribute("type", parameters.get(i).toHuman());
result.addContent(parameterElement);
}
Element returnElement = new Element("return", NS_XMLVM);
returnElement.setAttribute("type", prototype.getReturnType().getType().toHuman());
result.addContent(returnElement);
return result;
}
/**
* Makes sure the instruction name is valid as an XML tag name.
*/
private static String sanitizeInstructionName(String rawName) {
return rawName.replaceAll("/", "-");
}
/**
* Sets the given attribute in the given element if the value is true only.
* Otherwise, nothing changes.
*/
private static void setAttributeIfTrue(Element element, String attributeName, boolean value) {
if (value) {
element.setAttribute(attributeName, Boolean.toString(value));
}
}
/**
* Extracts the number out of the register name of the format (v0, v1, v2,
* etc).
*
* @param vFormat
* the register name in v-format
* @return the extracted register number
*/
private static int registerNumber(String vFormat) throws RuntimeException {
if (!vFormat.startsWith("v")) {
throw new RuntimeErrorException(new Error(
"Register name doesn't start with 'v' prefix: " + vFormat));
}
try {
int registerNumber = Integer.parseInt(vFormat.substring(1));
return registerNumber;
} catch (NumberFormatException ex) {
throw new RuntimeErrorException(new Error(
"Couldn't extract register number from register name: " + vFormat, ex));
}
}
/**
* Converts a {@link Document} into XML text.
*/
private String documentToString(Document document) {
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
StringWriter writer = new StringWriter();
try {
outputter.output(document, writer);
} catch (IOException e) {
e.printStackTrace();
return "";
}
return writer.toString();
}
}
| false | true | private static void processInstruction(DalvInsn instruction, Element codeElement,
Set<Integer> targets, Map<Integer, SwitchData> switchDataBlocks) {
Element dexInstruction = null;
if (instruction.hasAddress()) {
int address = instruction.getAddress();
if (targets.contains(address)) {
Element labelElement = new Element("label", NS_DEX);
labelElement.setAttribute("id", String.valueOf(address));
codeElement.addContent(labelElement);
targets.remove(address);
}
}
if (instruction instanceof CodeAddress) {
// Ignore.
} else if (instruction instanceof LocalSnapshot) {
// Ingore.
} else if (instruction instanceof OddSpacer) {
// Ingore NOPs.
} else if (instruction instanceof SwitchData) {
// Ingore here because we already processes these and they were
// given to this method as an argument.
} else if (instruction instanceof LocalStart) {
// As we extract the locals information up-front we don't need to
// handle local-start.
} else if (instruction instanceof SimpleInsn) {
SimpleInsn simpleInsn = (SimpleInsn) instruction;
String instructionName = simpleInsn.getOpcode().getName();
// If this is a move-result instruction, we don't add it
// explicitly, but instead add the result register to the previous
// invoke instruction's return.
if (instructionName.startsWith("move-result")) {
// Sanity Check
if (simpleInsn.getRegisters().size() != 1) {
Log.error("DEXmlvmOutputProcess: Register Size doesn't fit 'move-result'.");
System.exit(-1);
}
RegisterSpec register = simpleInsn.getRegisters().get(0);
Element returnElement = lastInvokeInstruction.getChild("parameters", NS_DEX)
.getChild("return", NS_DEX);
returnElement.setAttribute("register", String.valueOf(registerNumber(register
.regString())));
} else {
RegisterSpecList registers = simpleInsn.getRegisters();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(registers, dexInstruction);
// For simple instructions with only one register, we also add
// the type of the register. This includes the return
// instructions.
if (registers.size() == 1) {
dexInstruction.setAttribute("class-type", registers.get(0).getType().toHuman());
}
}
} else if (instruction instanceof CstInsn) {
CstInsn cstInsn = (CstInsn) instruction;
if (isInvokeInstruction(cstInsn)) {
dexInstruction = processInvokeInstruction(cstInsn);
lastInvokeInstruction = dexInstruction;
} else {
dexInstruction = new Element(
sanitizeInstructionName(cstInsn.getOpcode().getName()), NS_DEX);
Constant constant = cstInsn.getConstant();
dexInstruction.setAttribute("type", constant.typeName());
if (constant instanceof CstMemberRef) {
CstMemberRef memberRef = (CstMemberRef) constant;
dexInstruction.setAttribute("class-type", memberRef.getDefiningClass()
.getClassType().toHuman());
CstNat nameAndType = memberRef.getNat();
dexInstruction.setAttribute("member-type", nameAndType.getFieldType().getType()
.toHuman());
dexInstruction.setAttribute("member-name", nameAndType.getName().toHuman());
} else if (constant instanceof CstString) {
CstString cstString = (CstString) constant;
dexInstruction.setAttribute("value", cstString.getString().getString());
} else {
dexInstruction.setAttribute("value", constant.toHuman());
}
processRegisters(cstInsn.getRegisters(), dexInstruction);
}
} else if (instruction instanceof TargetInsn) {
TargetInsn targetInsn = (TargetInsn) instruction;
String instructionName = targetInsn.getOpcode().getName();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(targetInsn.getRegisters(), dexInstruction);
if (instructionName.equals("packed-switch") || instructionName.equals("sparse-switch")) {
SwitchData switchData = switchDataBlocks.get(targetInsn.getTargetAddress());
if (switchData == null) {
Log.error("DEXmlvmOutputProcess: Couldn't find SwitchData block.");
System.exit(-1);
}
IntList cases = switchData.getCases();
CodeAddress[] caseTargets = switchData.getTargets();
// Sanity check.
if (cases.size() != caseTargets.length) {
Log.error("DEXmlvmOutputProcess: SwitchData size mismatch: cases vs targets.");
System.exit(-1);
}
for (int i = 0; i < cases.size(); ++i) {
Element caseElement = new Element("case", NS_DEX);
caseElement.setAttribute("key", String.valueOf(cases.get(i)));
caseElement.setAttribute("label", String.valueOf(caseTargets[i].getAddress()));
dexInstruction.addContent(caseElement);
}
} else {
dexInstruction
.setAttribute("target", String.valueOf(targetInsn.getTargetAddress()));
}
} else if (instruction instanceof HighRegisterPrefix) {
HighRegisterPrefix highRegisterPrefix = (HighRegisterPrefix) instruction;
SimpleInsn[] moveInstructions = highRegisterPrefix.getMoveInstructions();
for (SimpleInsn moveInstruction : moveInstructions) {
processInstruction(moveInstruction, codeElement, targets, switchDataBlocks);
}
} else {
System.err.print(">>> Unknown instruction: ");
System.err.print("(" + instruction.getClass().getName() + ") ");
System.err.print(instruction.listingString("", 0, true));
System.exit(-1);
}
if (LOTS_OF_DEBUG) {
System.out.print("(" + instruction.getClass().getName() + ") ");
System.out.print(instruction.listingString("", 0, true));
}
if (dexInstruction != null) {
codeElement.addContent(dexInstruction);
}
}
| private static void processInstruction(DalvInsn instruction, Element codeElement,
Set<Integer> targets, Map<Integer, SwitchData> switchDataBlocks) {
Element dexInstruction = null;
if (instruction.hasAddress()) {
int address = instruction.getAddress();
if (targets.contains(address)) {
Element labelElement = new Element("label", NS_DEX);
labelElement.setAttribute("id", String.valueOf(address));
codeElement.addContent(labelElement);
targets.remove(address);
}
}
if (instruction instanceof CodeAddress) {
// Ignore.
} else if (instruction instanceof LocalSnapshot) {
// Ignore.
} else if (instruction instanceof OddSpacer) {
// Ignore NOPs.
} else if (instruction instanceof SwitchData) {
// Ignore here because we already processes these and they were
// given to this method as an argument.
} else if (instruction instanceof LocalStart) {
// As we extract the locals information up-front we don't need to
// handle local-start.
} else if (instruction instanceof SimpleInsn) {
SimpleInsn simpleInsn = (SimpleInsn) instruction;
String instructionName = simpleInsn.getOpcode().getName();
// If this is a move-result instruction, we don't add it
// explicitly, but instead add the result register to the previous
// invoke instruction's return.
if (instructionName.startsWith("move-result")) {
// Sanity Check
if (simpleInsn.getRegisters().size() != 1) {
Log.error("DEXmlvmOutputProcess: Register Size doesn't fit 'move-result'.");
System.exit(-1);
}
RegisterSpec register = simpleInsn.getRegisters().get(0);
Element returnElement = lastInvokeInstruction.getChild("parameters", NS_DEX)
.getChild("return", NS_DEX);
returnElement.setAttribute("register", String.valueOf(registerNumber(register
.regString())));
} else {
RegisterSpecList registers = simpleInsn.getRegisters();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(registers, dexInstruction);
// For simple instructions with only one register, we also add
// the type of the register. This includes the return
// instructions.
if (registers.size() == 1) {
dexInstruction.setAttribute("class-type", registers.get(0).getType().toHuman());
}
}
} else if (instruction instanceof CstInsn) {
CstInsn cstInsn = (CstInsn) instruction;
if (isInvokeInstruction(cstInsn)) {
dexInstruction = processInvokeInstruction(cstInsn);
lastInvokeInstruction = dexInstruction;
} else {
dexInstruction = new Element(
sanitizeInstructionName(cstInsn.getOpcode().getName()), NS_DEX);
Constant constant = cstInsn.getConstant();
dexInstruction.setAttribute("type", constant.typeName());
if (constant instanceof CstMemberRef) {
CstMemberRef memberRef = (CstMemberRef) constant;
dexInstruction.setAttribute("class-type", memberRef.getDefiningClass()
.getClassType().toHuman());
CstNat nameAndType = memberRef.getNat();
dexInstruction.setAttribute("member-type", nameAndType.getFieldType().getType()
.toHuman());
dexInstruction.setAttribute("member-name", nameAndType.getName().toHuman());
} else if (constant instanceof CstString) {
CstString cstString = (CstString) constant;
dexInstruction.setAttribute("value", cstString.getString().getString());
} else {
dexInstruction.setAttribute("value", constant.toHuman());
}
processRegisters(cstInsn.getRegisters(), dexInstruction);
}
} else if (instruction instanceof TargetInsn) {
TargetInsn targetInsn = (TargetInsn) instruction;
String instructionName = targetInsn.getOpcode().getName();
dexInstruction = new Element(sanitizeInstructionName(instructionName), NS_DEX);
processRegisters(targetInsn.getRegisters(), dexInstruction);
if (instructionName.equals("packed-switch") || instructionName.equals("sparse-switch")) {
SwitchData switchData = switchDataBlocks.get(targetInsn.getTargetAddress());
if (switchData == null) {
Log.error("DEXmlvmOutputProcess: Couldn't find SwitchData block.");
System.exit(-1);
}
IntList cases = switchData.getCases();
CodeAddress[] caseTargets = switchData.getTargets();
// Sanity check.
if (cases.size() != caseTargets.length) {
Log.error("DEXmlvmOutputProcess: SwitchData size mismatch: cases vs targets.");
System.exit(-1);
}
for (int i = 0; i < cases.size(); ++i) {
Element caseElement = new Element("case", NS_DEX);
caseElement.setAttribute("key", String.valueOf(cases.get(i)));
caseElement.setAttribute("label", String.valueOf(caseTargets[i].getAddress()));
dexInstruction.addContent(caseElement);
}
} else {
dexInstruction
.setAttribute("target", String.valueOf(targetInsn.getTargetAddress()));
}
} else if (instruction instanceof HighRegisterPrefix) {
HighRegisterPrefix highRegisterPrefix = (HighRegisterPrefix) instruction;
SimpleInsn[] moveInstructions = highRegisterPrefix.getMoveInstructions();
for (SimpleInsn moveInstruction : moveInstructions) {
processInstruction(moveInstruction, codeElement, targets, switchDataBlocks);
}
} else {
System.err.print(">>> Unknown instruction: ");
System.err.print("(" + instruction.getClass().getName() + ") ");
System.err.print(instruction.listingString("", 0, true));
System.exit(-1);
}
if (LOTS_OF_DEBUG) {
System.out.print("(" + instruction.getClass().getName() + ") ");
System.out.print(instruction.listingString("", 0, true));
}
if (dexInstruction != null) {
codeElement.addContent(dexInstruction);
}
}
|
diff --git a/src/test/java/com/lazerycode/selenium/charts/HighChartsTest.java b/src/test/java/com/lazerycode/selenium/charts/HighChartsTest.java
index 6428065..1a31789 100644
--- a/src/test/java/com/lazerycode/selenium/charts/HighChartsTest.java
+++ b/src/test/java/com/lazerycode/selenium/charts/HighChartsTest.java
@@ -1,108 +1,108 @@
package com.lazerycode.selenium.charts;
import com.lazerycode.selenium.JettyServer;
import com.lazerycode.selenium.graphs.ColumnChart;
import com.lazerycode.selenium.graphs.LineChart;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.Color;
import java.awt.*;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
public class HighChartsTest {
private static WebDriver driver;
private static JettyServer localWebServer;
private static int webServerPort = 9081;
private String webServerURL = "http://localhost";
@BeforeClass
public static void start() throws Exception {
//Move mouse out of the way so it can't mess about with hover events
Robot mouseRemover = new Robot();
mouseRemover.mouseMove(1200, 0);
localWebServer = new JettyServer(webServerPort);
driver = new FirefoxDriver();
driver.manage().window().setSize(new Dimension(1024, 768));
}
@AfterClass
public static void stop() throws Exception {
localWebServer.stopJettyServer();
driver.close();
}
@Test
public void validateColumnChart() {
driver.get(webServerURL + ":" + webServerPort + "/highcharts.html");
WebElement highChartSVGElement = driver.findElement(By.id("columnchart"));
ColumnChart chartObject = new ColumnChart(driver, highChartSVGElement);
assertThat(chartObject.isChartDisplayed(), is(equalTo(true)));
assertThat(chartObject.isLegendDisplayed(), is(equalTo(true)));
chartObject.hoverOverPrimarySeriesAtXAxisLabel("Bananas");
- assertThat(chartObject.getPrimarySeriesColourForXAxisLabel("Bananas").asHex(), is(equalTo(Color.fromString("#4572A7").asHex())));
+ assertThat(chartObject.getPrimarySeriesColourForXAxisLabel("Bananas"), is(equalTo(Color.fromString("#4572A7"))));
assertThat(chartObject.isTooltipDisplayed(), is(equalTo(true)));
assertThat(chartObject.getToolTipLine(1), is(equalTo("Bananas")));
assertThat(chartObject.getToolTipLine(2), is(equalTo("Jane")));
assertThat(chartObject.getToolTipLine(3), is(equalTo(":")));
assertThat(chartObject.getToolTipLine(4), is(equalTo("0")));
chartObject.hoverOverSecondarySeriesAtXAxisLabel("Bananas");
- assertThat(chartObject.getSecondarySeriesColourForXAxisLabel("Bananas").asHex(), is(equalTo(Color.fromString("#AA4643").asHex())));
+ assertThat(chartObject.getSecondarySeriesColourForXAxisLabel("Bananas"), is(equalTo(Color.fromString("#AA4643"))));
assertThat(chartObject.isTooltipDisplayed(), is(equalTo(true)));
assertThat(chartObject.getToolTipLine(1), is(equalTo("Bananas")));
assertThat(chartObject.getToolTipLine(2), is(equalTo("John")));
assertThat(chartObject.getToolTipLine(3), is(equalTo(":")));
assertThat(chartObject.getToolTipLine(4), is(equalTo("7")));
String[] EXPECTED_X_AXIS_LABELS = {"Apples", "Bananas", "Oranges"};
String[] EXPECTED_Y_AXIS_LABELS = {"0", "2.5", "5", "7.5", "Fruit eaten"};
assertThat(chartObject.getXAxisLabelsAsArray(), is(equalTo(EXPECTED_X_AXIS_LABELS)));
assertThat(chartObject.getYAxisLabelsAsArray(), is(equalTo(EXPECTED_Y_AXIS_LABELS)));
}
@Test
public void validateLineChart() {
driver.get(webServerURL + ":" + webServerPort + "/highcharts.html");
WebElement highChartSVGElement = driver.findElement(By.id("linechart"));
LineChart chartObject = new LineChart(driver, highChartSVGElement);
assertThat(chartObject.isChartDisplayed(), is(equalTo(true)));
assertThat(chartObject.isLegendDisplayed(), is(equalTo(true)));
chartObject.hoverOverMiddleOfGraphAtXAxisLabel("Bananas");
assertThat(chartObject.isTooltipDisplayed(), is(equalTo(true)));
assertThat(chartObject.getToolTipLine(1), is(equalTo("Bananas")));
assertThat(chartObject.getToolTipLine(2), is(equalTo("Jane")));
assertThat(chartObject.getToolTipLine(3), is(equalTo(":")));
assertThat(chartObject.getToolTipLine(4), is(equalTo("0")));
assertThat(chartObject.getToolTipLine(5), is(equalTo("John")));
assertThat(chartObject.getToolTipLine(6), is(equalTo(":")));
assertThat(chartObject.getToolTipLine(7), is(equalTo("7")));
String[] EXPECTED_X_AXIS_LABELS = {"Apples", "Bananas", "Oranges"};
String[] EXPECTED_Y_AXIS_LABELS = {"0", "-2.5", "2.5", "5", "7.5", "Fruit eaten"};
assertThat(chartObject.getXAxisLabelsAsArray(), is(equalTo(EXPECTED_X_AXIS_LABELS)));
assertThat(chartObject.getYAxisLabelsAsArray(), is(equalTo(EXPECTED_Y_AXIS_LABELS)));
}
}
| false | true | public void validateColumnChart() {
driver.get(webServerURL + ":" + webServerPort + "/highcharts.html");
WebElement highChartSVGElement = driver.findElement(By.id("columnchart"));
ColumnChart chartObject = new ColumnChart(driver, highChartSVGElement);
assertThat(chartObject.isChartDisplayed(), is(equalTo(true)));
assertThat(chartObject.isLegendDisplayed(), is(equalTo(true)));
chartObject.hoverOverPrimarySeriesAtXAxisLabel("Bananas");
assertThat(chartObject.getPrimarySeriesColourForXAxisLabel("Bananas").asHex(), is(equalTo(Color.fromString("#4572A7").asHex())));
assertThat(chartObject.isTooltipDisplayed(), is(equalTo(true)));
assertThat(chartObject.getToolTipLine(1), is(equalTo("Bananas")));
assertThat(chartObject.getToolTipLine(2), is(equalTo("Jane")));
assertThat(chartObject.getToolTipLine(3), is(equalTo(":")));
assertThat(chartObject.getToolTipLine(4), is(equalTo("0")));
chartObject.hoverOverSecondarySeriesAtXAxisLabel("Bananas");
assertThat(chartObject.getSecondarySeriesColourForXAxisLabel("Bananas").asHex(), is(equalTo(Color.fromString("#AA4643").asHex())));
assertThat(chartObject.isTooltipDisplayed(), is(equalTo(true)));
assertThat(chartObject.getToolTipLine(1), is(equalTo("Bananas")));
assertThat(chartObject.getToolTipLine(2), is(equalTo("John")));
assertThat(chartObject.getToolTipLine(3), is(equalTo(":")));
assertThat(chartObject.getToolTipLine(4), is(equalTo("7")));
String[] EXPECTED_X_AXIS_LABELS = {"Apples", "Bananas", "Oranges"};
String[] EXPECTED_Y_AXIS_LABELS = {"0", "2.5", "5", "7.5", "Fruit eaten"};
assertThat(chartObject.getXAxisLabelsAsArray(), is(equalTo(EXPECTED_X_AXIS_LABELS)));
assertThat(chartObject.getYAxisLabelsAsArray(), is(equalTo(EXPECTED_Y_AXIS_LABELS)));
}
| public void validateColumnChart() {
driver.get(webServerURL + ":" + webServerPort + "/highcharts.html");
WebElement highChartSVGElement = driver.findElement(By.id("columnchart"));
ColumnChart chartObject = new ColumnChart(driver, highChartSVGElement);
assertThat(chartObject.isChartDisplayed(), is(equalTo(true)));
assertThat(chartObject.isLegendDisplayed(), is(equalTo(true)));
chartObject.hoverOverPrimarySeriesAtXAxisLabel("Bananas");
assertThat(chartObject.getPrimarySeriesColourForXAxisLabel("Bananas"), is(equalTo(Color.fromString("#4572A7"))));
assertThat(chartObject.isTooltipDisplayed(), is(equalTo(true)));
assertThat(chartObject.getToolTipLine(1), is(equalTo("Bananas")));
assertThat(chartObject.getToolTipLine(2), is(equalTo("Jane")));
assertThat(chartObject.getToolTipLine(3), is(equalTo(":")));
assertThat(chartObject.getToolTipLine(4), is(equalTo("0")));
chartObject.hoverOverSecondarySeriesAtXAxisLabel("Bananas");
assertThat(chartObject.getSecondarySeriesColourForXAxisLabel("Bananas"), is(equalTo(Color.fromString("#AA4643"))));
assertThat(chartObject.isTooltipDisplayed(), is(equalTo(true)));
assertThat(chartObject.getToolTipLine(1), is(equalTo("Bananas")));
assertThat(chartObject.getToolTipLine(2), is(equalTo("John")));
assertThat(chartObject.getToolTipLine(3), is(equalTo(":")));
assertThat(chartObject.getToolTipLine(4), is(equalTo("7")));
String[] EXPECTED_X_AXIS_LABELS = {"Apples", "Bananas", "Oranges"};
String[] EXPECTED_Y_AXIS_LABELS = {"0", "2.5", "5", "7.5", "Fruit eaten"};
assertThat(chartObject.getXAxisLabelsAsArray(), is(equalTo(EXPECTED_X_AXIS_LABELS)));
assertThat(chartObject.getYAxisLabelsAsArray(), is(equalTo(EXPECTED_Y_AXIS_LABELS)));
}
|
diff --git a/plugins/ldapservers.apacheds.v200/src/main/java/org/apache/directory/studio/ldapservers/apacheds/v200/ApacheDS200LdapServerAdapter.java b/plugins/ldapservers.apacheds.v200/src/main/java/org/apache/directory/studio/ldapservers/apacheds/v200/ApacheDS200LdapServerAdapter.java
index c4191fe97..36fe3cdc3 100644
--- a/plugins/ldapservers.apacheds.v200/src/main/java/org/apache/directory/studio/ldapservers/apacheds/v200/ApacheDS200LdapServerAdapter.java
+++ b/plugins/ldapservers.apacheds.v200/src/main/java/org/apache/directory/studio/ldapservers/apacheds/v200/ApacheDS200LdapServerAdapter.java
@@ -1,858 +1,854 @@
/*
* 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.directory.studio.ldapservers.apacheds.v200;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.server.config.beans.ChangePasswordServerBean;
import org.apache.directory.server.config.beans.ConfigBean;
import org.apache.directory.server.config.beans.DirectoryServiceBean;
import org.apache.directory.server.config.beans.DnsServerBean;
import org.apache.directory.server.config.beans.KdcServerBean;
import org.apache.directory.server.config.beans.LdapServerBean;
import org.apache.directory.server.config.beans.NtpServerBean;
import org.apache.directory.server.config.beans.TransportBean;
import org.apache.directory.studio.apacheds.configuration.v2.editor.ServerConfigurationEditor;
import org.apache.directory.studio.apacheds.configuration.v2.jobs.LoadConfigurationRunnable;
import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor;
import org.apache.directory.studio.common.ui.filesystem.PathEditorInput;
import org.apache.directory.studio.ldapservers.LdapServersManager;
import org.apache.directory.studio.ldapservers.LdapServersUtils;
import org.apache.directory.studio.ldapservers.model.LdapServer;
import org.apache.directory.studio.ldapservers.model.LdapServerAdapter;
import org.apache.mina.util.AvailablePortFinder;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;
/**
* This class implements an LDAP Server Adapter for ApacheDS version 2.0.0.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class ApacheDS200LdapServerAdapter implements LdapServerAdapter
{
// Various strings constants used in paths
private static final String CONFIG_LDIF = "config.ldif"; //$NON-NLS-1$
private static final String LOG4J_PROPERTIES = "log4j.properties"; //$NON-NLS-1$
private static final String RESOURCES = "resources"; //$NON-NLS-1$
private static final String LIBS = "libs"; //$NON-NLS-1$
private static final String CONF = "conf"; //$NON-NLS-1$
/** The array of libraries names */
private static final String[] libraries = new String[]
{ "apacheds-service-2.0.0-M14.jar" }; //$NON-NLS-1$
/**
* {@inheritDoc}
*/
public void add( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
// Getting the bundle associated with the plugin
Bundle bundle = ApacheDS200Plugin.getDefault().getBundle();
// Verifying and copying ApacheDS 2.0.0 libraries
LdapServersUtils.verifyAndCopyLibraries( bundle, new Path( RESOURCES ).append( LIBS ),
getServerLibrariesFolder(), libraries, monitor,
Messages.getString( "ApacheDS200LdapServerAdapter.VerifyingAndCopyingLibraries" ) ); //$NON-NLS-1$
// Creating server folder structure
monitor.subTask( Messages.getString( "ApacheDS200LdapServerAdapter.CreatingServerFolderStructure" ) ); //$NON-NLS-1$
File serverFolder = LdapServersManager.getServerFolder( server ).toFile();
File confFolder = new File( serverFolder, CONF );
confFolder.mkdir();
File ldifFolder = new File( serverFolder, "ldif" ); //$NON-NLS-1$
ldifFolder.mkdir();
File logFolder = new File( serverFolder, "log" ); //$NON-NLS-1$
logFolder.mkdir();
File partitionFolder = new File( serverFolder, "partitions" ); //$NON-NLS-1$
partitionFolder.mkdir();
// Copying configuration files
monitor.subTask( Messages.getString( "ApacheDS200LdapServerAdapter.CopyingConfigurationFiles" ) ); //$NON-NLS-1$
IPath resourceConfFolderPath = new Path( RESOURCES ).append( CONF );
LdapServersUtils.copyResource( bundle, resourceConfFolderPath.append( CONFIG_LDIF ), new File( confFolder,
CONFIG_LDIF ) );
LdapServersUtils.copyResource( bundle, resourceConfFolderPath.append( LOG4J_PROPERTIES ), new File( confFolder,
LOG4J_PROPERTIES ) );
// Creating an empty log file
new File( logFolder, "apacheds.log" ).createNewFile(); //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void delete( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
// Nothing to do (nothing more than the default behavior of
// the delete action before this method is called)
}
/**
* {@inheritDoc}
*/
public void openConfiguration( final LdapServer server, final StudioProgressMonitor monitor ) throws Exception
{
// Opening the editor
Display.getDefault().syncExec( new Runnable()
{
public void run()
{
try
{
PathEditorInput input = new PathEditorInput( LdapServersManager.getServerFolder( server )
.append( CONF ).append( CONFIG_LDIF ) );
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.openEditor( input, ServerConfigurationEditor.ID );
}
catch ( PartInitException e )
{
monitor.reportError( e );
}
}
} );
}
/**
* {@inheritDoc}
*/
public void start( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
// Getting the bundle associated with the plugin
Bundle bundle = ApacheDS200Plugin.getDefault().getBundle();
// Verifying and copying ApacheDS 2.0.0 libraries
LdapServersUtils.verifyAndCopyLibraries( bundle, new Path( RESOURCES ).append( LIBS ),
getServerLibrariesFolder(), libraries, monitor,
Messages.getString( "ApacheDS200LdapServerAdapter.VerifyingAndCopyingLibraries" ) ); //$NON-NLS-1$
// Starting the console printer thread
LdapServersUtils.startConsolePrinterThread( server );
// Launching ApacheDS
ILaunch launch = launchApacheDS( server );
// Starting the "terminate" listener thread
LdapServersUtils.startTerminateListenerThread( server, launch );
// Running the startup listener watchdog
LdapServersUtils.runStartupListenerWatchdog( server, getTestingPort( server ) );
}
/**
* Launches ApacheDS using a launch configuration.
*
* @param server
* the server
* @return
* the associated launch
*/
public static ILaunch launchApacheDS( LdapServer server )
throws Exception
{
// Getting the default VM installation
IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
// Creating a new editable launch configuration
ILaunchConfigurationType type = DebugPlugin.getDefault().getLaunchManager()
.getLaunchConfigurationType( IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION );
ILaunchConfigurationWorkingCopy workingCopy = type.newInstance( null, server.getId() );
// Setting the JRE container path attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, vmInstall
.getInstallLocation().toString() );
// Setting the main type attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
"org.apache.directory.server.UberjarMain" ); //$NON-NLS-1$
// Creating the classpath list
List<String> classpath = new ArrayList<String>();
for ( String library : libraries )
{
IRuntimeClasspathEntry libraryClasspathEntry = JavaRuntime
.newArchiveRuntimeClasspathEntry( getServerLibrariesFolder().append( library ) );
libraryClasspathEntry.setClasspathProperty( IRuntimeClasspathEntry.USER_CLASSES );
classpath.add( libraryClasspathEntry.getMemento() );
}
// Setting the classpath type attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath );
// Setting the default classpath type attribute to false
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false );
// The server folder path
IPath serverFolderPath = LdapServersManager.getServerFolder( server );
// Setting the program arguments attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, "\"" //$NON-NLS-1$
+ serverFolderPath.toOSString() + "\"" ); //$NON-NLS-1$
// Creating the VM arguments string
StringBuffer vmArguments = new StringBuffer();
vmArguments.append( "-Dlog4j.configuration=file:\"" //$NON-NLS-1$
+ serverFolderPath.append( CONF ).append( LOG4J_PROPERTIES ).toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.var.dir=\"" + serverFolderPath.toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.log.dir=\"" + serverFolderPath.append( "log" ).toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.instance=\"" + server.getName() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments
- .append( "-Ddefault.controls=org.apache.directory.api.ldap.codec.controls.cascade.CascadeFactory," + //$NON-NLS-1$
+ .append( "-Dapacheds.controls=org.apache.directory.api.ldap.codec.controls.cascade.CascadeFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.manageDsaIT.ManageDsaITFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.entryChange.EntryChangeFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.pagedSearch.PagedResultsFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.persistentSearch.PersistentSearchFactory," + //$NON-NLS-1$
- "org.apache.directory.api.ldap.codec.controls.search.subentries.SubentriesFactory" ); //$NON-NLS-1$
- vmArguments.append( " " ); //$NON-NLS-1$
- vmArguments
- .append( "-Dextra.controls=org.apache.directory.api.ldap.extras.controls.ppolicy_impl.PasswordPolicyFactory," + //$NON-NLS-1$
+ "org.apache.directory.api.ldap.codec.controls.search.subentries.SubentriesFactory," + //$NON-NLS-1$
+ "org.apache.directory.api.ldap.extras.controls.ppolicy_impl.PasswordPolicyFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncDoneValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncInfoValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncRequestValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncStateValueFactory" ); //$NON-NLS-1$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments
- .append( "-Ddefault.extendedOperation.requests=org.apache.directory.api.ldap.extras.extended.ads_impl.cancel.CancelFactory," + //$NON-NLS-1$
+ .append( "-Dapacheds.extendedOperations=org.apache.directory.api.ldap.extras.extended.ads_impl.cancel.CancelFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.certGeneration.CertGenerationFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.gracefulShutdown.GracefulShutdownFactory," + //$NON-NLS-1$
- "org.apache.directory.api.ldap.extras.extended.ads_impl.storedProcedure.StoredProcedureFactory" ); //$NON-NLS-1$
- vmArguments.append( " " ); //$NON-NLS-1$
- vmArguments
- .append( "-Ddefault.extendedOperation.responses=org.apache.directory.api.ldap.extras.extended.ads_impl.gracefulDisconnect.GracefulDisconnectFactory" ); //$NON-NLS-1$
+ "org.apache.directory.api.ldap.extras.extended.ads_impl.storedProcedure.StoredProcedureFactory," + //$NON-NLS-1$
+ "org.apache.directory.api.ldap.extras.extended.ads_impl.gracefulDisconnect.GracefulDisconnectFactory" ); //$NON-NLS-1$
// Setting the VM arguments attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, vmArguments.toString() );
// Setting the launch configuration as private
workingCopy.setAttribute( IDebugUIConstants.ATTR_PRIVATE, true );
// Indicating that we don't want any console to show up
workingCopy.setAttribute( DebugPlugin.ATTR_CAPTURE_OUTPUT, false );
// Saving the launch configuration
ILaunchConfiguration configuration = workingCopy.doSave();
// Launching the launch configuration
ILaunch launch = configuration.launch( ILaunchManager.RUN_MODE, new NullProgressMonitor() );
// Storing the launch configuration as a custom object in the LDAP Server for later use
server.putCustomObject( LdapServersUtils.LAUNCH_CONFIGURATION_CUSTOM_OBJECT, launch );
return launch;
}
/**
* {@inheritDoc}
*/
public void stop( LdapServer server, StudioProgressMonitor monitor ) throws Exception
{
// Stopping the console printer thread
LdapServersUtils.stopConsolePrinterThread( server );
// Terminating the launch configuration
LdapServersUtils.terminateLaunchConfiguration( server );
}
/**
* Gets the path to the server libraries folder.
*
* @return
* the path to the server libraries folder
*/
private static IPath getServerLibrariesFolder()
{
return ApacheDS200Plugin.getDefault().getStateLocation().append( LIBS );
}
/**
* Gets the server configuration.
*
* @param server
* the server
* @return
* the associated server configuration
* @throws Exception
* @throws ServerXmlIOException
* @throws FileNotFoundException
*/
public static ConfigBean getServerConfiguration( LdapServer server ) throws Exception
{
InputStream fis = new FileInputStream( LdapServersManager.getServerFolder( server ).append( CONF )
.append( CONFIG_LDIF ).toFile() );
return LoadConfigurationRunnable.readConfiguration( fis );
}
/**
* Gets the testing port.
*
* @param configuration
* the 1.5.6 server configuration
* @return
* the testing port
* @throws Exception
* @throws ServerXmlIOException
*/
private int getTestingPort( LdapServer server ) throws Exception
{
ConfigBean configuration = getServerConfiguration( server );
// LDAP
if ( isEnableLdap( configuration ) )
{
return getLdapPort( configuration );
}
// LDAPS
else if ( isEnableLdaps( configuration ) )
{
return getLdapsPort( configuration );
}
// Kerberos
else if ( isEnableKerberos( configuration ) )
{
return getKerberosPort( configuration );
}
// DNS
else if ( isEnableDns( configuration ) )
{
return getDnsPort( configuration );
}
// NTP
else if ( isEnableNtp( configuration ) )
{
return getNtpPort( configuration );
}
// ChangePassword
else if ( isEnableChangePassword( configuration ) )
{
return getChangePasswordPort( configuration );
}
else
{
return 0;
}
}
/**
* Indicates if the LDAP Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the LDAP Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableLdap( ConfigBean configuration )
{
TransportBean ldapServerTransportBean = getLdapServerTransportBean( configuration );
if ( ldapServerTransportBean != null )
{
return ldapServerTransportBean.isEnabled();
}
return false;
}
/**
* Indicates if the LDAPS Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the LDAPS Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableLdaps( ConfigBean configuration )
{
TransportBean ldapsServerTransportBean = getLdapsServerTransportBean( configuration );
if ( ldapsServerTransportBean != null )
{
return ldapsServerTransportBean.isEnabled();
}
return false;
}
/**
* Gets the LDAP Server transport bean.
*
* @param configuration the configuration
* @return the LDAP Server transport bean.
*/
private static TransportBean getLdapServerTransportBean( ConfigBean configuration )
{
return getLdapServerTransportBean( configuration, "ldap" ); //$NON-NLS-1$
}
/**
* Gets the LDAPS Server transport bean.
*
* @param configuration the configuration
* @return the LDAPS Server transport bean.
*/
private static TransportBean getLdapsServerTransportBean( ConfigBean configuration )
{
return getLdapServerTransportBean( configuration, "ldaps" ); //$NON-NLS-1$
}
/**
* Gets the corresponding LDAP Server transport bean.
*
* @param configuration the configuration
* @param id the id
* @return the corresponding LDAP Server transport bean.
*/
private static TransportBean getLdapServerTransportBean( ConfigBean configuration, String id )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
LdapServerBean ldapServerBean = directoryServiceBean.getLdapServerBean();
if ( ldapServerBean != null )
{
// Looking for the transport in the list
TransportBean[] ldapServerTransportBeans = ldapServerBean.getTransports();
if ( ldapServerTransportBeans != null )
{
for ( TransportBean ldapServerTransportBean : ldapServerTransportBeans )
{
if ( id.equals( ldapServerTransportBean.getTransportId() ) )
{
return ldapServerTransportBean;
}
}
}
}
}
return null;
}
/**
* Indicates if the Kerberos Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the Kerberos Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableKerberos( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
KdcServerBean kdcServerBean = directoryServiceBean.getKdcServerBean();
if ( kdcServerBean != null )
{
kdcServerBean.isEnabled();
}
}
return false;
}
/**
* Indicates if the DNS Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the DNS Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableDns( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
DnsServerBean dnsServerBean = directoryServiceBean.getDnsServerBean();
if ( dnsServerBean != null )
{
dnsServerBean.isEnabled();
}
}
return false;
}
/**
* Indicates if the NTP Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the NTP Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableNtp( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
NtpServerBean ntpServerBean = directoryServiceBean.getNtpServerBean();
if ( ntpServerBean != null )
{
ntpServerBean.isEnabled();
}
}
return false;
}
/**
* Indicates if the Change Password Server is enabled.
*
* @param configuration the configuration
* @return <code>true</code> if the Change Password Server is enabled,
* <code>false</code> if not.
*/
public static boolean isEnableChangePassword( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
ChangePasswordServerBean changePasswordServerBean = directoryServiceBean.getChangePasswordServerBean();
if ( changePasswordServerBean != null )
{
changePasswordServerBean.isEnabled();
}
}
return false;
}
/**
* Gets the LDAP port.
*
* @param configuration the configuration
* @return the LDAP port
*/
public static int getLdapPort( ConfigBean configuration )
{
TransportBean ldapServerTransportBean = getLdapServerTransportBean( configuration );
if ( ldapServerTransportBean != null )
{
return ldapServerTransportBean.getSystemPort();
}
return 0;
}
/**
* Gets the LDAPS port.
*
* @param configuration the configuration
* @return the LDAPS port
*/
public static int getLdapsPort( ConfigBean configuration )
{
TransportBean ldapsServerTransportBean = getLdapsServerTransportBean( configuration );
if ( ldapsServerTransportBean != null )
{
return ldapsServerTransportBean.getSystemPort();
}
return 0;
}
/**
* Gets the Kerberos port.
*
* @param configuration the configuration
* @return the Kerberos port
*/
public static int getKerberosPort( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
KdcServerBean kdcServerBean = directoryServiceBean.getKdcServerBean();
if ( kdcServerBean != null )
{
// Looking for the transport in the list
TransportBean[] kdcServerTransportBeans = kdcServerBean.getTransports();
if ( kdcServerTransportBeans != null )
{
for ( TransportBean kdcServerTransportBean : kdcServerTransportBeans )
{
if ( ( "tcp".equals( kdcServerTransportBean.getTransportId() ) ) //$NON-NLS-1$
|| ( "udp".equals( kdcServerTransportBean.getTransportId() ) ) ) //$NON-NLS-1$
{
return kdcServerTransportBean.getSystemPort();
}
}
}
}
}
return 0;
}
/**
* Gets the DNS port.
*
* @param configuration the configuration
* @return the DNS port
*/
public static int getDnsPort( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
DnsServerBean dnsServerBean = directoryServiceBean.getDnsServerBean();
if ( dnsServerBean != null )
{
// Looking for the transport in the list
TransportBean[] dnsServerTransportBeans = dnsServerBean.getTransports();
if ( dnsServerTransportBeans != null )
{
for ( TransportBean dnsServerTransportBean : dnsServerTransportBeans )
{
if ( ( "tcp".equals( dnsServerTransportBean.getTransportId() ) ) //$NON-NLS-1$
|| ( "udp".equals( dnsServerTransportBean.getTransportId() ) ) ) //$NON-NLS-1$
{
return dnsServerTransportBean.getSystemPort();
}
}
}
}
}
return 0;
}
/**
* Gets the NTP port.
*
* @param configuration the configuration
* @return the NTP port
*/
public static int getNtpPort( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
NtpServerBean ntpServerBean = directoryServiceBean.getNtpServerBean();
if ( ntpServerBean != null )
{
// Looking for the transport in the list
TransportBean[] ntpServerTransportBeans = ntpServerBean.getTransports();
if ( ntpServerTransportBeans != null )
{
for ( TransportBean ntpServerTransportBean : ntpServerTransportBeans )
{
if ( ( "tcp".equals( ntpServerTransportBean.getTransportId() ) ) //$NON-NLS-1$
|| ( "udp".equals( ntpServerTransportBean.getTransportId() ) ) ) //$NON-NLS-1$
{
return ntpServerTransportBean.getSystemPort();
}
}
}
}
}
return 0;
}
/**
* Gets the Change Password port.
*
* @param configuration the configuration
* @return the Change Password port
*/
public static int getChangePasswordPort( ConfigBean configuration )
{
DirectoryServiceBean directoryServiceBean = configuration.getDirectoryServiceBean();
if ( directoryServiceBean != null )
{
ChangePasswordServerBean changePasswordServerBean = directoryServiceBean.getChangePasswordServerBean();
if ( changePasswordServerBean != null )
{
// Looking for the transport in the list
TransportBean[] changePasswordServerTransportBeans = changePasswordServerBean.getTransports();
if ( changePasswordServerTransportBeans != null )
{
for ( TransportBean changePasswordServerTransportBean : changePasswordServerTransportBeans )
{
if ( ( "tcp".equals( changePasswordServerTransportBean.getTransportId() ) ) //$NON-NLS-1$
|| ( "udp".equals( changePasswordServerTransportBean.getTransportId() ) ) ) //$NON-NLS-1$
{
return changePasswordServerTransportBean.getSystemPort();
}
}
}
}
}
return 0;
}
/**
* {@inheritDoc}
*/
public String[] checkPortsBeforeServerStart( LdapServer server ) throws Exception
{
List<String> alreadyInUseProtocolPortsList = new ArrayList<String>();
ConfigBean configuration = getServerConfiguration( server );
// LDAP
if ( isEnableLdap( configuration ) )
{
if ( !AvailablePortFinder.available( getLdapPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.LDAPPort" ), new Object[] { getLdapPort( configuration ) } ) ); //$NON-NLS-1$
}
}
// LDAPS
if ( isEnableLdaps( configuration ) )
{
if ( !AvailablePortFinder.available( getLdapsPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.LDAPSPort" ), new Object[] { getLdapsPort( configuration ) } ) ); //$NON-NLS-1$
}
}
// Kerberos
if ( isEnableKerberos( configuration ) )
{
if ( !AvailablePortFinder.available( getKerberosPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS
.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.KerberosPort" ), new Object[] { getKerberosPort( configuration ) } ) ); //$NON-NLS-1$
}
}
// DNS
if ( isEnableDns( configuration ) )
{
if ( !AvailablePortFinder.available( getDnsPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.DNSPort" ), new Object[] { getDnsPort( configuration ) } ) ); //$NON-NLS-1$
}
}
// NTP
if ( isEnableNtp( configuration ) )
{
if ( !AvailablePortFinder.available( getNtpPort( configuration ) ) )
{
alreadyInUseProtocolPortsList.add( NLS.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.NTPPort" ), new Object[] //$NON-NLS-1$
{ getNtpPort( configuration ) } ) );
}
}
// Change Password
if ( isEnableChangePassword( configuration ) )
{
if ( !AvailablePortFinder.available( getChangePasswordPort( configuration ) ) )
{
alreadyInUseProtocolPortsList
.add( NLS
.bind(
Messages.getString( "ApacheDS200LdapServerAdapter.ChangePasswordPort" ), new Object[] { getChangePasswordPort( configuration ) } ) ); //$NON-NLS-1$
}
}
return alreadyInUseProtocolPortsList.toArray( new String[0] );
}
}
| false | true | public static ILaunch launchApacheDS( LdapServer server )
throws Exception
{
// Getting the default VM installation
IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
// Creating a new editable launch configuration
ILaunchConfigurationType type = DebugPlugin.getDefault().getLaunchManager()
.getLaunchConfigurationType( IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION );
ILaunchConfigurationWorkingCopy workingCopy = type.newInstance( null, server.getId() );
// Setting the JRE container path attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, vmInstall
.getInstallLocation().toString() );
// Setting the main type attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
"org.apache.directory.server.UberjarMain" ); //$NON-NLS-1$
// Creating the classpath list
List<String> classpath = new ArrayList<String>();
for ( String library : libraries )
{
IRuntimeClasspathEntry libraryClasspathEntry = JavaRuntime
.newArchiveRuntimeClasspathEntry( getServerLibrariesFolder().append( library ) );
libraryClasspathEntry.setClasspathProperty( IRuntimeClasspathEntry.USER_CLASSES );
classpath.add( libraryClasspathEntry.getMemento() );
}
// Setting the classpath type attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath );
// Setting the default classpath type attribute to false
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false );
// The server folder path
IPath serverFolderPath = LdapServersManager.getServerFolder( server );
// Setting the program arguments attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, "\"" //$NON-NLS-1$
+ serverFolderPath.toOSString() + "\"" ); //$NON-NLS-1$
// Creating the VM arguments string
StringBuffer vmArguments = new StringBuffer();
vmArguments.append( "-Dlog4j.configuration=file:\"" //$NON-NLS-1$
+ serverFolderPath.append( CONF ).append( LOG4J_PROPERTIES ).toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.var.dir=\"" + serverFolderPath.toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.log.dir=\"" + serverFolderPath.append( "log" ).toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.instance=\"" + server.getName() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments
.append( "-Ddefault.controls=org.apache.directory.api.ldap.codec.controls.cascade.CascadeFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.manageDsaIT.ManageDsaITFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.entryChange.EntryChangeFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.pagedSearch.PagedResultsFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.persistentSearch.PersistentSearchFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.subentries.SubentriesFactory" ); //$NON-NLS-1$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments
.append( "-Dextra.controls=org.apache.directory.api.ldap.extras.controls.ppolicy_impl.PasswordPolicyFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncDoneValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncInfoValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncRequestValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncStateValueFactory" ); //$NON-NLS-1$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments
.append( "-Ddefault.extendedOperation.requests=org.apache.directory.api.ldap.extras.extended.ads_impl.cancel.CancelFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.certGeneration.CertGenerationFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.gracefulShutdown.GracefulShutdownFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.storedProcedure.StoredProcedureFactory" ); //$NON-NLS-1$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments
.append( "-Ddefault.extendedOperation.responses=org.apache.directory.api.ldap.extras.extended.ads_impl.gracefulDisconnect.GracefulDisconnectFactory" ); //$NON-NLS-1$
// Setting the VM arguments attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, vmArguments.toString() );
// Setting the launch configuration as private
workingCopy.setAttribute( IDebugUIConstants.ATTR_PRIVATE, true );
// Indicating that we don't want any console to show up
workingCopy.setAttribute( DebugPlugin.ATTR_CAPTURE_OUTPUT, false );
// Saving the launch configuration
ILaunchConfiguration configuration = workingCopy.doSave();
// Launching the launch configuration
ILaunch launch = configuration.launch( ILaunchManager.RUN_MODE, new NullProgressMonitor() );
// Storing the launch configuration as a custom object in the LDAP Server for later use
server.putCustomObject( LdapServersUtils.LAUNCH_CONFIGURATION_CUSTOM_OBJECT, launch );
return launch;
}
| public static ILaunch launchApacheDS( LdapServer server )
throws Exception
{
// Getting the default VM installation
IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
// Creating a new editable launch configuration
ILaunchConfigurationType type = DebugPlugin.getDefault().getLaunchManager()
.getLaunchConfigurationType( IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION );
ILaunchConfigurationWorkingCopy workingCopy = type.newInstance( null, server.getId() );
// Setting the JRE container path attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, vmInstall
.getInstallLocation().toString() );
// Setting the main type attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
"org.apache.directory.server.UberjarMain" ); //$NON-NLS-1$
// Creating the classpath list
List<String> classpath = new ArrayList<String>();
for ( String library : libraries )
{
IRuntimeClasspathEntry libraryClasspathEntry = JavaRuntime
.newArchiveRuntimeClasspathEntry( getServerLibrariesFolder().append( library ) );
libraryClasspathEntry.setClasspathProperty( IRuntimeClasspathEntry.USER_CLASSES );
classpath.add( libraryClasspathEntry.getMemento() );
}
// Setting the classpath type attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath );
// Setting the default classpath type attribute to false
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false );
// The server folder path
IPath serverFolderPath = LdapServersManager.getServerFolder( server );
// Setting the program arguments attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, "\"" //$NON-NLS-1$
+ serverFolderPath.toOSString() + "\"" ); //$NON-NLS-1$
// Creating the VM arguments string
StringBuffer vmArguments = new StringBuffer();
vmArguments.append( "-Dlog4j.configuration=file:\"" //$NON-NLS-1$
+ serverFolderPath.append( CONF ).append( LOG4J_PROPERTIES ).toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.var.dir=\"" + serverFolderPath.toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.log.dir=\"" + serverFolderPath.append( "log" ).toOSString() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments.append( "-Dapacheds.instance=\"" + server.getName() + "\"" ); //$NON-NLS-1$ //$NON-NLS-2$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments
.append( "-Dapacheds.controls=org.apache.directory.api.ldap.codec.controls.cascade.CascadeFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.manageDsaIT.ManageDsaITFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.entryChange.EntryChangeFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.pagedSearch.PagedResultsFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.persistentSearch.PersistentSearchFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.codec.controls.search.subentries.SubentriesFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.ppolicy_impl.PasswordPolicyFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncDoneValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncInfoValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncRequestValueFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.controls.syncrepl_impl.SyncStateValueFactory" ); //$NON-NLS-1$
vmArguments.append( " " ); //$NON-NLS-1$
vmArguments
.append( "-Dapacheds.extendedOperations=org.apache.directory.api.ldap.extras.extended.ads_impl.cancel.CancelFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.certGeneration.CertGenerationFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.gracefulShutdown.GracefulShutdownFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.storedProcedure.StoredProcedureFactory," + //$NON-NLS-1$
"org.apache.directory.api.ldap.extras.extended.ads_impl.gracefulDisconnect.GracefulDisconnectFactory" ); //$NON-NLS-1$
// Setting the VM arguments attribute
workingCopy.setAttribute( IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, vmArguments.toString() );
// Setting the launch configuration as private
workingCopy.setAttribute( IDebugUIConstants.ATTR_PRIVATE, true );
// Indicating that we don't want any console to show up
workingCopy.setAttribute( DebugPlugin.ATTR_CAPTURE_OUTPUT, false );
// Saving the launch configuration
ILaunchConfiguration configuration = workingCopy.doSave();
// Launching the launch configuration
ILaunch launch = configuration.launch( ILaunchManager.RUN_MODE, new NullProgressMonitor() );
// Storing the launch configuration as a custom object in the LDAP Server for later use
server.putCustomObject( LdapServersUtils.LAUNCH_CONFIGURATION_CUSTOM_OBJECT, launch );
return launch;
}
|
diff --git a/srcj/com/sun/electric/database/variable/ElectricObject.java b/srcj/com/sun/electric/database/variable/ElectricObject.java
index fa2928d29..d8c2d1cdf 100755
--- a/srcj/com/sun/electric/database/variable/ElectricObject.java
+++ b/srcj/com/sun/electric/database/variable/ElectricObject.java
@@ -1,1306 +1,1306 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: ElectricObject.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.database.variable;
import com.sun.electric.database.ImmutableElectricObject;
import com.sun.electric.database.geometry.GenMath;
import com.sun.electric.database.geometry.Geometric;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.EDatabase;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.text.Name;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.tool.user.ActivityLogger;
import com.sun.electric.tool.user.User;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* This class is the base class of all Electric objects that can be extended with "Variables".
* <P>
* This class should be thread-safe.
*/
public abstract class ElectricObject implements Serializable
{
// ------------------------ private data ------------------------------------
// ------------------------ private and protected methods -------------------
/**
* The protected constructor.
*/
protected ElectricObject() {}
/**
* Returns persistent data of this ElectricObject with Variables.
* @return persistent data of this ElectricObject.
*/
public abstract ImmutableElectricObject getImmutable();
// ------------------------ public methods -------------------
/**
* Returns true if object is linked into database
*/
public abstract boolean isLinked();
/**
* Method to return the Variable on this ElectricObject with a given name.
* @param name the name of the Variable.
* @return the Variable with that name, or null if there is no such Variable.
*/
public Variable getVar(String name)
{
Variable.Key key = Variable.findKey(name);
return getVar(key, null);
}
/**
* Method to return the Variable on this ElectricObject with a given key.
* @param key the key of the Variable.
* @return the Variable with that key, or null if there is no such Variable.
*/
public Variable getVar(Variable.Key key)
{
return getVar(key, null);
}
/**
* Method to return the Variable on this ElectricObject with a given name and type.
* @param name the name of the Variable.
* @param type the required type of the Variable.
* @return the Variable with that name and type, or null if there is no such Variable.
*/
public Variable getVar(String name, Class type)
{
Variable.Key key = Variable.findKey(name);
return getVar(key, type);
}
/**
* Method to return the Variable on this ElectricObject with a given key and type.
* @param key the key of the Variable. Returns null if key is null.
* @param type the required type of the Variable. Ignored if null.
* @return the Variable with that key and type, or null if there is no such Variable
* or default Variable value.
*/
public Variable getVar(Variable.Key key, Class type)
{
checkExamine();
if (key == null) return null;
Variable var;
synchronized(this) {
var = getImmutable().getVar(key);
}
if (var != null) {
if (type == null) return var; // null type means any type
if (type.isInstance(var.getObject())) return var;
}
return null;
}
/**
* Returns the TextDescriptor on this ElectricObject selected by variable key.
* This key may be a key of variable on this ElectricObject or one of the
* special keys:
* <code>NodeInst.NODE_NAME</code>
* <code>NodeInst.NODE_PROTO</code>
* <code>ArcInst.ARC_NAME</code>
* <code>Export.EXPORT_NAME</code>
* The TextDescriptor gives information for displaying the Variable.
* @param varKey key of variable or special key.
* @return the TextDescriptor on this ElectricObject.
*/
public TextDescriptor getTextDescriptor(Variable.Key varKey)
{
Variable var = getVar(varKey);
if (var == null) return null;
return var.getTextDescriptor();
}
/**
* Returns the TextDescriptor on this ElectricObject selected by variable key.
* This key may be a key of variable on this ElectricObject or one of the
* special keys:
* <code>NodeInst.NODE_NAME</code>
* <code>NodeInst.NODE_PROTO</code>
* <code>ArcInst.ARC_NAME</code>
* <code>Export.EXPORT_NAME</code>
* The TextDescriptor gives information for displaying the Variable.
* @param varKey key of variable or special key.
* @return the TextDescriptor on this ElectricObject.
*/
public MutableTextDescriptor getMutableTextDescriptor(Variable.Key varKey)
{
TextDescriptor td = getTextDescriptor(varKey);
if (td == null) return null;
return new MutableTextDescriptor(td);
}
/**
* Method to return true if the Variable on this ElectricObject with given key is a parameter.
* Parameters are those Variables that have values on instances which are
* passed down the hierarchy into the contents.
* Parameters can only exist on Cell and NodeInst objects.
* @param varKey key to test
* @return true if the Variable with given key is a parameter.
*/
public boolean isParam(Variable.Key varKey) { return false; }
/**
* Method to return the number of displayable Variables on this ElectricObject.
* A displayable Variable is one that will be shown with its object.
* Displayable Variables can only sensibly exist on NodeInst and ArcInst objects.
* @return the number of displayable Variables on this ElectricObject.
*/
public int numDisplayableVariables(boolean multipleStrings)
{
//checkExamine();
int numVars = 0;
for (Iterator<Variable> it = getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (var.isDisplay())
{
int len = var.getLength();
if (len > 1 && var.getTextDescriptor().getDispPart() == TextDescriptor.DispPos.NAMEVALUE) len++;
if (!multipleStrings) len = 1;
numVars += len;
}
}
return numVars;
}
/**
* Method to add all displayable Variables on this Electric object to an array of Poly objects.
* @param rect a rectangle describing the bounds of the object on which the Variables will be displayed.
* @param polys an array of Poly objects that will be filled with the displayable Variables.
* @param start the starting index in the array of Poly objects to fill with displayable Variables.
* @param wnd window in which the Variables will be displayed.
* @param multipleStrings true to break multiline text into multiple Polys.
* @return the number of Polys that were added.
*/
public int addDisplayableVariables(Rectangle2D rect, Poly [] polys, int start, EditWindow0 wnd, boolean multipleStrings)
{
checkExamine();
int numAddedVariables = 0;
double cX = rect.getCenterX();
double cY = rect.getCenterY();
for (Iterator<Variable> it = getVariables(); it.hasNext(); )
{
Variable var = it.next();
if (!var.isDisplay()) continue;
Poly [] polyList = getPolyList(var, cX, cY, wnd, multipleStrings);
for(int i=0; i<polyList.length; i++)
{
int index = start + numAddedVariables;
polys[index] = polyList[i];
polys[index].setStyle(Poly.rotateType(polys[index].getStyle(), this));
numAddedVariables++;
}
}
return numAddedVariables;
}
/**
* Method to compute a Poly that describes text.
* The text can be described by an ElectricObject (Exports or cell instance names).
* The text can be described by a node or arc name.
* The text can be described by a variable on an ElectricObject.
* @param wnd the EditWindow0 in which the text will be drawn.
* @param var the Variable on the ElectricObject (may be null).
* @param name the Name of the node or arc in the ElectricObject (may be null).
* @return a Poly that covers the text completely.
* Even though the Poly is scaled for a particular EditWindow,
* its coordinates are in object space, not screen space.
*/
public Poly computeTextPoly(EditWindow0 wnd, Variable.Key varKey)
{
checkExamine();
Poly poly = null;
if (varKey != null)
{
if (this instanceof Export)
{
Export pp = (Export)this;
if (varKey == Export.EXPORT_NAME)
{
poly = pp.getNamePoly();
} else
{
PortInst pi = pp.getOriginalPort();
Rectangle2D bounds = pp.getNamePoly().getBounds2D();
TextDescriptor td = pp.getTextDescriptor(Export.EXPORT_NAME);
Poly [] polys = pp.getPolyList(pp.getVar(varKey), bounds.getCenterX(), bounds.getCenterY(), wnd, false);
if (polys.length > 0)
{
poly = polys[0];
// poly.transform(pi.getNodeInst().rotateOut());
}
}
} else if (this instanceof PortInst)
{
PortInst pi = (PortInst)this;
Rectangle2D bounds = pi.getPoly().getBounds2D();
Poly [] polys = pi.getPolyList(pi.getVar(varKey), bounds.getCenterX(), bounds.getCenterY(), wnd, false);
if (polys.length > 0)
{
poly = polys[0];
poly.transform(pi.getNodeInst().rotateOut());
}
} else if (this instanceof Geometric)
{
Geometric geom = (Geometric)this;
if (varKey == NodeInst.NODE_NAME || varKey == ArcInst.ARC_NAME)
{
TextDescriptor td = geom.getTextDescriptor(varKey);
Poly.Type style = td.getPos().getPolyType();
Point2D [] pointList = null;
if (style == Poly.Type.TEXTBOX)
{
pointList = Poly.makePoints(geom.getBounds());
} else
{
pointList = new Point2D.Double[1];
pointList[0] = new Point2D.Double(geom.getTrueCenterX()+td.getXOff(), geom.getTrueCenterY()+td.getYOff());
}
poly = new Poly(pointList);
poly.setStyle(style);
if (geom instanceof NodeInst)
{
poly.transform(((NodeInst)geom).rotateOutAboutTrueCenter());
}
poly.setTextDescriptor(td);
if (varKey == NodeInst.NODE_NAME) poly.setString(((NodeInst)geom).getName()); else
poly.setString(((ArcInst)geom).getName());
} else if (varKey == NodeInst.NODE_PROTO)
{
if (!(geom instanceof NodeInst)) return null;
NodeInst ni = (NodeInst)this;
TextDescriptor td = ni.getTextDescriptor(NodeInst.NODE_PROTO);
Poly.Type style = td.getPos().getPolyType();
Point2D [] pointList = null;
if (style == Poly.Type.TEXTBOX)
{
pointList = Poly.makePoints(ni.getBounds());
} else
{
pointList = new Point2D.Double[1];
pointList[0] = new Point2D.Double(ni.getTrueCenterX()+td.getXOff(), ni.getTrueCenterY()+td.getYOff());
}
poly = new Poly(pointList);
poly.setStyle(style);
poly.setTextDescriptor(td);
poly.setString(ni.getProto().describe(false));
} else
{
double x = geom.getTrueCenterX();
double y = geom.getTrueCenterY();
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
Rectangle2D uBounds = ni.getUntransformedBounds();
x = uBounds.getCenterX();
y = uBounds.getCenterY();
}
Poly [] polys = geom.getPolyList(geom.getVar(varKey), x, y, wnd, false);
if (polys.length > 0)
{
poly = polys[0];
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
poly.transform(ni.rotateOut());
}
}
}
} else if (this instanceof Cell)
{
Cell cell = (Cell)this;
Poly [] polys = cell.getPolyList(cell.getVar(varKey), 0, 0, wnd, false);
if (polys.length > 0) poly = polys[0];
}
}
if (poly != null)
poly.setExactTextBounds(wnd, this);
return poly;
}
/**
* Method to return the bounds of this ElectricObject in an EditWindow.
* @param wnd the EditWindow0 in which the object is being displayed.
* @return the bounds of the text (does not include the bounds of the object).
*/
public Rectangle2D getTextBounds(EditWindow0 wnd)
{
Rectangle2D bounds = null;
for(Iterator<Variable> vIt = getVariables(); vIt.hasNext(); )
{
Variable var = vIt.next();
if (!var.isDisplay()) continue;
TextDescriptor td = var.getTextDescriptor();
// if (td.getSize().isAbsolute()) continue;
Poly poly = computeTextPoly(wnd, var.getKey());
if (poly == null) continue;
Rectangle2D polyBound = poly.getBounds2D();
if (bounds == null) bounds = polyBound; else
Rectangle2D.union(bounds, polyBound, bounds);
}
if (this instanceof ArcInst)
{
ArcInst ai = (ArcInst)this;
Name name = ai.getNameKey();
if (!name.isTempname())
{
Poly poly = computeTextPoly(wnd, ArcInst.ARC_NAME);
if (poly != null)
{
Rectangle2D polyBound = poly.getBounds2D();
if (bounds == null) bounds = polyBound; else
Rectangle2D.union(bounds, polyBound, bounds);
}
}
}
if (this instanceof NodeInst)
{
NodeInst ni = (NodeInst)this;
Name name = ni.getNameKey();
if (!name.isTempname())
{
Poly poly = computeTextPoly(wnd, NodeInst.NODE_NAME);
if (poly != null)
{
Rectangle2D polyBound = poly.getBounds2D();
if (bounds == null) bounds = polyBound; else
Rectangle2D.union(bounds, polyBound, bounds);
}
}
for(Iterator<Export> it = ni.getExports(); it.hasNext(); )
{
Export pp = it.next();
Poly poly = pp.computeTextPoly(wnd, Export.EXPORT_NAME);
if (poly != null)
{
Rectangle2D polyBound = poly.getBounds2D();
if (bounds == null) bounds = polyBound; else
Rectangle2D.union(bounds, polyBound, bounds);
}
}
}
return bounds;
}
/**
* Method to create an array of Poly objects that describes a displayable Variables on this Electric object.
* @param var the Variable on this ElectricObject to describe.
* @param cX the center X coordinate of the ElectricObject.
* @param cY the center Y coordinate of the ElectricObject.
* @param wnd window in which the Variable will be displayed.
* @param multipleStrings true to break multiline text into multiple Polys.
* @return an array of Poly objects that describe the Variable. May return zero length array.
*/
public Poly [] getPolyList(Variable var, double cX, double cY, EditWindow0 wnd, boolean multipleStrings)
{
double offX = var.getXOff();
double offY = var.getYOff();
int varLength = var.getLength();
double lineOffX = 0, lineOffY = 0;
AffineTransform trans = null;
Poly.Type style = var.getPos().getPolyType();
TextDescriptor td = var.getTextDescriptor();
if (this instanceof NodeInst && (offX != 0 || offY != 0))
{
td = td.withOff(0, 0);
// MutableTextDescriptor mtd = new MutableTextDescriptor(td);
// mtd.setOff(0, 0);
// td = mtd;
}
boolean headerString = false;
double fontHeight = 1;
double scale = 1;
if (wnd != null)
{
fontHeight = wnd.getFontHeight(td);
scale = wnd.getScale();
}
fontHeight *= User.getGlobalTextScale();
if (varLength > 1)
{
// compute text height
double lineDist = fontHeight / scale;
int rotQuadrant = td.getRotation().getIndex();
switch (rotQuadrant)
{
case 0: lineOffY = lineDist; break; // 0 degrees rotation
case 1: lineOffX = -lineDist; break; // 90 degrees rotation
case 2: lineOffY = -lineDist; break; // 180 degrees rotation
case 3: lineOffX = lineDist; break; // 270 degrees rotation
}
// multiline text on rotated nodes must compensate for node rotation
Poly.Type rotStyle = style;
if (this instanceof NodeInst)
{
NodeInst ni = (NodeInst)this;
trans = ni.rotateIn();
int origAngle = style.getTextAngle();
if (ni.isMirroredAboutXAxis() != ni.isMirroredAboutYAxis() && ((origAngle%1800) == 0 || (origAngle%1800) == 1350)) origAngle += 1800;
int angle = (origAngle - ni.getAngle() + 3600) % 3600;
style = Poly.Type.getTextTypeFromAngle(angle);
}
if (td.getDispPart() == TextDescriptor.DispPos.NAMEVALUE)
{
headerString = true;
varLength++;
}
if (multipleStrings)
{
if (rotStyle == Poly.Type.TEXTCENT || rotStyle == Poly.Type.TEXTBOX ||
rotStyle == Poly.Type.TEXTLEFT || rotStyle == Poly.Type.TEXTRIGHT)
{
cX += lineOffX * (varLength-1) / 2;
cY += lineOffY * (varLength-1) / 2;
}
if (rotStyle == Poly.Type.TEXTBOT || rotStyle == Poly.Type.TEXTBOTLEFT || rotStyle == Poly.Type.TEXTBOTRIGHT)
{
cX += lineOffX * (varLength-1);
cY += lineOffY * (varLength-1);
}
} else
{
if (rotStyle == Poly.Type.TEXTCENT || rotStyle == Poly.Type.TEXTBOX ||
rotStyle == Poly.Type.TEXTLEFT || rotStyle == Poly.Type.TEXTRIGHT)
{
cX -= lineOffX * (varLength-1) / 2;
cY -= lineOffY * (varLength-1) / 2;
}
if (rotStyle == Poly.Type.TEXTTOP || rotStyle == Poly.Type.TEXTTOPLEFT || rotStyle == Poly.Type.TEXTTOPRIGHT)
{
cX -= lineOffX * (varLength-1);
cY -= lineOffY * (varLength-1);
}
varLength = 1;
headerString = false;
}
}
VarContext context = null;
if (wnd != null) context = wnd.getVarContext();
Poly [] polys = new Poly[varLength];
for(int i=0; i<varLength; i++)
{
String message = null;
TextDescriptor entryTD = td;
if (varLength > 1 && headerString)
{
if (i == 0)
{
message = var.getTrueName()+ "[" + (varLength-1) + "]:";
entryTD = entryTD.withUnderline(true);
// MutableTextDescriptor mtd = new MutableTextDescriptor(td);
// mtd.setUnderline(true);
// entryTD = mtd;
} else
{
message = var.describe(i-1, context, this);
}
} else
{
message = var.describe(i, context, this);
}
Point2D [] pointList = null;
if (style == Poly.Type.TEXTBOX && this instanceof Geometric)
{
Geometric geom = (Geometric)this;
Rectangle2D bounds = geom.getBounds();
pointList = Poly.makePoints(bounds);
} else
{
pointList = new Point2D.Double[1];
pointList[0] = new Point2D.Double(cX+offX, cY+offY);
if (trans != null)
trans.transform(pointList[0], pointList[0]);
}
polys[i] = new Poly(pointList);
polys[i].setString(message);
polys[i].setStyle(style);
polys[i].setTextDescriptor(entryTD);
polys[i].setDisplayedText(new DisplayedText(this, var.getKey()));
polys[i].setLayer(null);
cX -= lineOffX;
cY -= lineOffY;
}
return polys;
}
/**
* Method to create a non-displayable Variable on this ElectricObject with the specified values.
* @param name the name of the Variable.
* @param value the object to store in the Variable.
* @return the Variable that has been created.
*/
public Variable newVar(String name, Object value) { return newVar(Variable.newKey(name), value); }
/**
* Method to create a displayable Variable on this ElectricObject with the specified values.
* @param key the key of the Variable.
* @param value the object to store in the Variable.
* @return the Variable that has been created.
*/
public Variable newDisplayVar(Variable.Key key, Object value) { return newVar(key, value, true); }
/**
* Method to create a non-displayable Variable on this ElectricObject with the specified values.
* Notify to observers as well.
* @param key the key of the Variable.
* @param value the object to store in the Variable.
* @return the Variable that has been created.
*/
public Variable newVar(Variable.Key key, Object value)
{
return newVar(key, value, false);
}
/**
* Method to create a Variable on this ElectricObject with the specified values.
* @param key the key of the Variable.
* @param value the object to store in the Variable.
* @param display true if the Variale is displayable.
* @return the Variable that has been created.
*/
public Variable newVar(Variable.Key key, Object value, boolean display) {
TextDescriptor td = null;
if (this instanceof Cell) td = TextDescriptor.cacheCellDescriptor.newTextDescriptor(display);
else if (this instanceof Export) td = TextDescriptor.cacheExportDescriptor.newTextDescriptor(display);
else if (this instanceof NodeInst) td = TextDescriptor.cacheNodeDescriptor.newTextDescriptor(display);
else if (this instanceof ArcInst) td = TextDescriptor.cacheArcDescriptor.newTextDescriptor(display);
else td = TextDescriptor.cacheAnnotationDescriptor.newTextDescriptor(display);
return newVar(key, value, td);
}
/**
* Method to create a Variable on this ElectricObject with the specified values.
* @param key the key of the Variable.
* @param value the object to store in the Variable.
* @param td text descriptor of the Variable
* @return the Variable that has been created.
*/
public Variable newVar(Variable.Key key, Object value, TextDescriptor td)
{
if (value == null) return null;
if (isDeprecatedVariable(key)) {
System.out.println("Deprecated variable " + key + " on " + this);
}
Variable var = null;
try {
var = Variable.newInstance(key, value, td);
} catch (IllegalArgumentException e) {
ActivityLogger.logException(e);
return null;
}
addVar(var);
return getVar(key);
// setChanged();
// notifyObservers(v);
// clearChanged();
}
/**
* Method to add a Variable on this ElectricObject.
* It may add a repaired copy of this Variable in some cases.
* @param var Variable to add.
*/
public abstract void addVar(Variable var);
/**
* Method to update a Variable on this ElectricObject with the specified values.
* If the Variable already exists, only the value is changed; the displayable attributes are preserved.
* @param key the key of the Variable.
* @param value the object to store in the Variable.
* @return the Variable that has been updated.
*/
public Variable updateVar(Variable.Key key, Object value)
{
Variable var = getVar(key);
if (var == null) return newVar(key, value);
addVar(var.withObject(value));
return getVar(key);
}
/**
* Updates the TextDescriptor on this ElectricObject selected by varKey.
* The varKey may be a key of variable on this ElectricObject or one of the
* special keys:
* NodeInst.NODE_NAME
* NodeInst.NODE_PROTO
* ArcInst.ARC_NAME
* Export.EXPORT_NAME
* If varKey doesn't select any text descriptor, no action is performed.
* The TextDescriptor gives information for displaying the Variable.
* @param varKey key of variable or special key.
* @param td new value TextDescriptor
*/
public void setTextDescriptor(Variable.Key varKey, TextDescriptor td) {
Variable var = getVar(varKey);
if (var == null) return;
if (!(this instanceof Cell))
td = td.withParam(false);
addVar(var.withTextDescriptor(td));
}
/**
* Method to set the X and Y offsets of the text in the TextDescriptor selected by key of
* variable or special key.
* The values are scaled by 4, so a value of 3 indicates a shift of 0.75 and a value of 4 shifts by 1.
* @param varKey key of variable or special key.
* @param xd the X offset of the text in the TextDescriptor.
* @param yd the Y offset of the text in the TextDescriptor.
* @see #setTextDescriptor(com.sun.electric.database.variable.Variable.Key,com.sun.electric.database.variable.TextDescriptor)
* @see com.sun.electric.database.variable.Variable#withOff(double,double)
*/
public synchronized void setOff(Variable.Key varKey, double xd, double yd) {
TextDescriptor td = getTextDescriptor(varKey);
if (td != null) setTextDescriptor(varKey, td.withOff(xd, yd));
}
/**
* Method to copy text descriptor from another ElectricObject to this ElectricObject.
* @param other the other ElectricObject from which to copy Variables.
* @param varKey selector of textdescriptor
*/
public void copyTextDescriptorFrom(ElectricObject other, Variable.Key varKey)
{
TextDescriptor td = other.getTextDescriptor(varKey);
if (td == null) return;
setTextDescriptor(varKey, td);
}
/**
* Rename a Variable. Note that this creates a new variable of
* the new name and copies all values from the old variable, and
* then deletes the old variable.
* @param name the name of the var to rename
* @param newName the new name of the variable
* @return the new renamed variable
*/
public Variable renameVar(String name, String newName) {
return renameVar(Variable.findKey(name), newName);
}
/**
* Rename a Variable. Note that this creates a new variable of
* the new name and copies all values from the old variable, and
* then deletes the old variable.
* @param key the name key of the var to rename
* @param newName the new name of the variable
* @return the new renamed variable, or null on error (no action taken)
*/
public Variable renameVar(Variable.Key key, String newName) {
// see if newName exists already
Variable.Key newKey = Variable.newKey(newName);
Variable var = getVar(newKey);
if (var != null) return null; // name already exists
// get current Variable
Variable oldvar = getVar(key);
if (oldvar == null) return null;
// create new var
Variable newVar = newVar(newKey, oldvar.getObject(), oldvar.getTextDescriptor());
if (newVar == null) return null;
// copy settings from old var to new var
// newVar.setTextDescriptor();
// newVar.copyFlags(oldvar);
// delete old var
delVar(oldvar.getKey());
return newVar;
}
/**
* Method to delete a Variable from this ElectricObject.
* @param key the key of the Variable to delete.
*/
public abstract void delVar(Variable.Key key);
/**
* Method to copy all variables from another ElectricObject to this ElectricObject.
* @param other the other ElectricObject from which to copy Variables.
*/
public void copyVarsFrom(ElectricObject other)
{
checkChanging();
Iterator<Variable> it = other.getVariables();
synchronized(this) {
while(it.hasNext())
{
Variable var = it.next();
Variable newVar = this.newVar(var.getKey(), var.getObject(), var.getTextDescriptor());
if (newVar != null)
{
// newVar.copyFlags(var);
// newVar.setTextDescriptor();
}
}
}
}
private static class ArrayName
{
private String baseName;
private String indexPart;
}
/**
* Method to return a unique object name in a Cell.
* @param name the original name that is not unique.
* @param cell the Cell in which this name resides.
* @param cls the class of the object on which this name resides.
* @return a unique name for that class in that Cell.
*/
public static String uniqueObjectName(String name, Cell cell, Class cls) {
String newName = name;
for (int i = 0; !cell.isUniqueName(newName, cls, null); i++) {
newName = uniqueObjectNameLow(newName, cell, cls, null, null);
if (i > 100) {
System.out.println("Can't create unique object name in " + cell + " from original " + name + " attempted " + newName);
return null;
}
}
return newName;
}
/**
* Method to return a unique object name in a Cell.
* @param name the original name that is not unique.
* @param cell the Cell in which this name resides.
* @param cls the class of the object on which this name resides.
* @param already a Set of names already in use (lower case).
* @return a unique name for that class in that Cell.
*/
public static String uniqueObjectName(String name, Cell cell, Class cls,
Set already, HashMap<String,GenMath.MutableInteger> nextPlainIndex)
{
String newName = name;
String lcName = TextUtils.canonicString(newName);
for (int i = 0; already.contains(lcName); i++)
{
newName = uniqueObjectNameLow(newName, cell, cls, already, nextPlainIndex);
if (i > 100)
{
System.out.println("Can't create unique object name in " + cell + " from original " + name + " attempted " + newName);
return null;
}
lcName = TextUtils.canonicString(newName);
}
return newName;
}
private static String uniqueObjectNameLow(String name, Cell cell, Class cls,
Set already, HashMap<String,GenMath.MutableInteger> nextPlainIndex)
{
// first see if the name is unique
if (already != null)
{
- if (!already.contains(name)) return name;
+ if (!already.contains(TextUtils.canonicString(name))) return name;
} else
{
if (cell.isUniqueName(name, cls, null)) return name;
}
// see if there is a "++" anywhere to tell us what to increment
int plusPlusPos = name.indexOf("++");
if (plusPlusPos >= 0)
{
int numStart = plusPlusPos;
while (numStart > 0 && TextUtils.isDigit(name.charAt(numStart-1))) numStart--;
if (numStart < plusPlusPos)
{
int nextIndex = TextUtils.atoi(name.substring(numStart)) + 1;
for( ; ; nextIndex++)
{
String newname = name.substring(0, numStart) + nextIndex + name.substring(plusPlusPos);
if (already != null)
{
- if (!already.contains(newname)) return newname;
+ if (!already.contains(TextUtils.canonicString(newname))) return newname;
} else
{
if (cell.isUniqueName(newname, cls, null)) return newname;
}
}
}
}
// see if there is a "--" anywhere to tell us what to decrement
int minusMinusPos = name.indexOf("--");
if (minusMinusPos >= 0)
{
int numStart = minusMinusPos;
while (numStart > 0 && TextUtils.isDigit(name.charAt(numStart-1))) numStart--;
if (numStart < minusMinusPos)
{
int nextIndex = TextUtils.atoi(name.substring(numStart)) - 1;
for( ; nextIndex >= 0; nextIndex--)
{
String newname = name.substring(0, numStart) + nextIndex + name.substring(minusMinusPos);
if (already != null)
{
- if (!already.contains(newname)) return newname;
+ if (!already.contains(TextUtils.canonicString(newname))) return newname;
} else
{
if (cell.isUniqueName(newname, cls, null)) return newname;
}
}
}
}
// break the string into a list of ArrayName objects
List<ArrayName> names = new ArrayList<ArrayName>();
boolean inBracket = false;
int len = name.length();
int startOfBase = 0;
int startOfIndex = -1;
for(int i=0; i<len; i++)
{
char ch = name.charAt(i);
if (ch == '[')
{
if (startOfIndex < 0) startOfIndex = i;
inBracket = true;
}
if (ch == ']') inBracket = false;
if ((ch == ',' && !inBracket) || i == len-1)
{
// remember this arrayname
if (i == len-1) i++;
ArrayName an = new ArrayName();
int endOfBase = startOfIndex;
if (endOfBase < 0) endOfBase = i;
an.baseName = name.substring(startOfBase, endOfBase);
if (startOfIndex >= 0) an.indexPart = name.substring(startOfIndex, i);
names.add(an);
startOfBase = i+1;
startOfIndex = -1;
}
}
char separateChar = '_';
for(ArrayName an : names)
{
// adjust the index part if possible
boolean indexAdjusted = false;
String index = an.indexPart;
if (index != null)
{
int possibleEnd = 0;
int nameLen = index.length();
// see if the index part can be incremented
int possibleStart = -1;
int endPos = nameLen-1;
for(;;)
{
// find the range of characters in square brackets
int startPos = index.lastIndexOf('[', endPos);
if (startPos < 0) break;
// see if there is a comma in the bracketed expression
int i = index.indexOf(',', startPos);
if (i >= 0 && i < endPos)
{
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// see if there is a colon in the bracketed expression
i = index.indexOf(':', startPos);
if (i >= 0 && i < endPos)
{
// colon: make sure there are two numbers
String firstIndex = index.substring(startPos+1, i);
String secondIndex = index.substring(i+1, endPos);
if (TextUtils.isANumber(firstIndex) && TextUtils.isANumber(secondIndex))
{
int startIndex = TextUtils.atoi(firstIndex);
int endIndex = TextUtils.atoi(secondIndex);
int spacing = Math.abs(endIndex - startIndex) + 1;
for(int nextIndex = 1; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + "[" + (startIndex+spacing*nextIndex) +
":" + (endIndex+spacing*nextIndex) + index.substring(endPos);
boolean unique;
if (already != null)
{
- unique = !already.contains(an.baseName + newIndex);
+ unique = !already.contains(TextUtils.canonicString(an.baseName + newIndex));
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
if (indexAdjusted) break;
}
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// see if this bracketed expression is a pure number
String bracketedExpression = index.substring(startPos+1, endPos);
if (TextUtils.isANumber(bracketedExpression))
{
int nextIndex = TextUtils.atoi(bracketedExpression) + 1;
for(; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + "[" + nextIndex + index.substring(endPos);
boolean unique;
if (already != null)
{
- unique = !already.contains(an.baseName + newIndex);
+ unique = !already.contains(TextUtils.canonicString(an.baseName + newIndex));
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
if (indexAdjusted) break;
}
// remember the first index that could be incremented in a pinch
if (possibleStart < 0)
{
possibleStart = startPos;
possibleEnd = endPos;
}
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// if there was a possible place to increment, do it
if (!indexAdjusted && possibleStart >= 0)
{
// nothing simple, but this one can be incremented
int i;
for(i=possibleEnd-1; i>possibleStart; i--)
if (!TextUtils.isDigit(index.charAt(i))) break;
int nextIndex = TextUtils.atoi(index.substring(i+1)) + 1;
int startPos = i+1;
if (index.charAt(startPos-1) == separateChar) startPos--;
for(; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + separateChar + nextIndex + index.substring(possibleEnd);
boolean unique;
if (already != null)
{
- unique = !already.contains(an.baseName + newIndex);
+ unique = !already.contains(TextUtils.canonicString(an.baseName + newIndex));
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
}
}
// if the index was not adjusted, adjust the base part
if (!indexAdjusted)
{
// array contents cannot be incremented: increment base name
String base = an.baseName;
int startPos = base.length();
int endPos = base.length();
// if there is a numeric part at the end, increment that
String localSepString = String.valueOf(separateChar);
while (startPos > 0 && TextUtils.isDigit(base.charAt(startPos-1))) startPos--;
int nextIndex = 1;
if (startPos >= endPos)
{
if (startPos > 0 && base.charAt(startPos-1) == separateChar) startPos--;
} else
{
nextIndex = TextUtils.atoi(base.substring(startPos)) + 1;
localSepString = "";
}
// find the unique index to use
String prefix = base.substring(0, startPos) + localSepString;
if (nextPlainIndex != null)
{
GenMath.MutableInteger nxt = nextPlainIndex.get(prefix);
if (nxt == null)
{
nxt = new GenMath.MutableInteger(cell.getUniqueNameIndex(prefix, cls, nextIndex));
nextPlainIndex.put(prefix, nxt);
}
nextIndex = nxt.intValue();
nxt.increment();
} else
{
nextIndex = cell.getUniqueNameIndex(prefix, cls, nextIndex);
}
an.baseName = prefix + nextIndex + base.substring(endPos);
}
}
StringBuffer result = new StringBuffer();
boolean first = true;
for(ArrayName an : names)
{
if (first) first = false; else
result.append(",");
result.append(an.baseName);
if (an.indexPart != null) result.append(an.indexPart);
}
return result.toString();
}
/**
* Method to determine whether a Variable key on this object is deprecated.
* Deprecated Variable keys are those that were used in old versions of Electric,
* but are no longer valid.
* @param key the key of the Variable.
* @return true if the Variable key is deprecated.
*/
public boolean isDeprecatedVariable(Variable.Key key)
{
String name = key.toString();
if (name.length() == 0) return true;
if (name.length() == 1)
{
char chr = name.charAt(0);
if (!Character.isLetter(chr)) return true;
}
return false;
}
/**
* Method to return an Iterator over all Variables on this ElectricObject.
* @return an Iterator over all Variables on this ElectricObject.
*/
public synchronized Iterator<Variable> getVariables() { return getImmutable().getVariables(); }
/**
* Method to return the number of Variables on this ElectricObject.
* @return the number of Variables on this ElectricObject.
*/
public synchronized int getNumVariables() { return getImmutable().getNumVariables(); }
/**
* Routing to check whether changing of this cell allowed or not.
* By default checks whole database change. Overriden in subclasses.
*/
public void checkChanging() {
EDatabase database = getDatabase();
if (database != null)
database.checkChanging();
}
/**
* Routing to check whether undoing of this cell allowed or not.
* By default checks whole database undo. Overriden in subclasses.
*/
public void checkUndoing() {
getDatabase().checkUndoing();
}
/**
* Method to make sure that this object can be examined.
* Ensures that an examine job is running.
*/
public void checkExamine() {
EDatabase database = getDatabase();
if (database != null)
database.checkExamine();
}
/**
* Returns database to which this ElectricObject belongs.
* Some objects are not in database, for example Geometrics in PaletteFrame.
* Method returns null for non-database objects.
* @return database to which this ElectricObject belongs.
*/
public abstract EDatabase getDatabase();
/**
* Method which indicates that this object is in database.
* Some objects are not in database, for example Geometrics in PaletteFrame.
* @return true if this object is in database, false if it is not a database object,
* or if it is a dummy database object (considered not to be in the database).
*/
protected boolean isDatabaseObject() { return true; }
/**
* Method to determine the appropriate Cell associated with this ElectricObject.
* @return the appropriate Cell associated with this ElectricObject.
* Returns null if no Cell can be found.
*/
public Cell whichCell() { return null; }
/**
* Method to write a description of this ElectricObject (lists all Variables).
* Displays the description in the Messages Window.
*/
public void getInfo()
{
checkExamine();
boolean firstvar = true;
for(Iterator<Variable> it = getVariables(); it.hasNext() ;)
{
Variable val = it.next();
Variable.Key key = val.getKey();
if (val == null) continue;
if (firstvar) System.out.println("Variables:"); firstvar = false;
Object addr = val.getObject();
String par = isParam(key) ? "(param)" : "";
// String par = val.isParam() ? "(param)" : "";
if (addr instanceof Object[])
{
Object[] ary = (Object[]) addr;
System.out.print(" " + key.getName() + "(" + ary.length + ") = [");
for (int i = 0; i < ary.length; i++)
{
if (i > 4)
{
System.out.print("...");
break;
}
if (ary[i] instanceof String) System.out.print("\"");
System.out.print(ary[i]);
if (ary[i] instanceof String) System.out.print("\"");
if (i < ary.length-1) System.out.print(", ");
}
System.out.println("] "+par);
} else
{
System.out.println(" " + key.getName() + "= " + addr + " "+par);
}
}
}
/**
* Returns a printable version of this ElectricObject.
* @return a printable version of this ElectricObject.
*/
public String toString()
{
return getClass().getName();
}
// /**
// * Observer method to update variables in Icon instance if cell master changes
// * @param o
// * @param arg
// */
// public void update(Observable o, Object arg)
// {
// System.out.println("Entering update");
// // New
// if (arg instanceof Variable)
// {
// Variable var = (Variable)arg;
// // You can't call newVar(var.getKey(), var.getObject()) to avoid infinite loop
// newVar(var.getD());
// }
// else if (arg instanceof Object[])
// {
// Object[] array = (Object[])arg;
//
// if (!(array[0] instanceof String))
// {
// System.out.println("Error in ElectricObject.update");
// return;
// }
// String function = (String)array[0];
// if (function.startsWith("setTextDescriptor"))
// {
// Variable.Key varKey = (Variable.Key)array[1];
// TextDescriptor td = (TextDescriptor)array[2];
// // setTextDescriptor(String varName, TextDescriptor td)
// setTextDescriptor(varKey, td);
// }
// else if (function.startsWith("delVar"))
// {
// Variable.Key key = (Variable.Key)array[1];
// delVarNoObserver(key);
// }
//// else if (array[0] instanceof Variable.Key)
//// {
//// // Variable updateVar(String name, Object value)
//// Variable.Key key = (Variable.Key)array[0];
//// updateVar(key, array[1]);
//// }
// }
// }
/**
* Method to check invariants in this ElectricObject.
* @exception AssertionError if invariants are not valid
*/
protected void check() {}
}
| false | true | private static String uniqueObjectNameLow(String name, Cell cell, Class cls,
Set already, HashMap<String,GenMath.MutableInteger> nextPlainIndex)
{
// first see if the name is unique
if (already != null)
{
if (!already.contains(name)) return name;
} else
{
if (cell.isUniqueName(name, cls, null)) return name;
}
// see if there is a "++" anywhere to tell us what to increment
int plusPlusPos = name.indexOf("++");
if (plusPlusPos >= 0)
{
int numStart = plusPlusPos;
while (numStart > 0 && TextUtils.isDigit(name.charAt(numStart-1))) numStart--;
if (numStart < plusPlusPos)
{
int nextIndex = TextUtils.atoi(name.substring(numStart)) + 1;
for( ; ; nextIndex++)
{
String newname = name.substring(0, numStart) + nextIndex + name.substring(plusPlusPos);
if (already != null)
{
if (!already.contains(newname)) return newname;
} else
{
if (cell.isUniqueName(newname, cls, null)) return newname;
}
}
}
}
// see if there is a "--" anywhere to tell us what to decrement
int minusMinusPos = name.indexOf("--");
if (minusMinusPos >= 0)
{
int numStart = minusMinusPos;
while (numStart > 0 && TextUtils.isDigit(name.charAt(numStart-1))) numStart--;
if (numStart < minusMinusPos)
{
int nextIndex = TextUtils.atoi(name.substring(numStart)) - 1;
for( ; nextIndex >= 0; nextIndex--)
{
String newname = name.substring(0, numStart) + nextIndex + name.substring(minusMinusPos);
if (already != null)
{
if (!already.contains(newname)) return newname;
} else
{
if (cell.isUniqueName(newname, cls, null)) return newname;
}
}
}
}
// break the string into a list of ArrayName objects
List<ArrayName> names = new ArrayList<ArrayName>();
boolean inBracket = false;
int len = name.length();
int startOfBase = 0;
int startOfIndex = -1;
for(int i=0; i<len; i++)
{
char ch = name.charAt(i);
if (ch == '[')
{
if (startOfIndex < 0) startOfIndex = i;
inBracket = true;
}
if (ch == ']') inBracket = false;
if ((ch == ',' && !inBracket) || i == len-1)
{
// remember this arrayname
if (i == len-1) i++;
ArrayName an = new ArrayName();
int endOfBase = startOfIndex;
if (endOfBase < 0) endOfBase = i;
an.baseName = name.substring(startOfBase, endOfBase);
if (startOfIndex >= 0) an.indexPart = name.substring(startOfIndex, i);
names.add(an);
startOfBase = i+1;
startOfIndex = -1;
}
}
char separateChar = '_';
for(ArrayName an : names)
{
// adjust the index part if possible
boolean indexAdjusted = false;
String index = an.indexPart;
if (index != null)
{
int possibleEnd = 0;
int nameLen = index.length();
// see if the index part can be incremented
int possibleStart = -1;
int endPos = nameLen-1;
for(;;)
{
// find the range of characters in square brackets
int startPos = index.lastIndexOf('[', endPos);
if (startPos < 0) break;
// see if there is a comma in the bracketed expression
int i = index.indexOf(',', startPos);
if (i >= 0 && i < endPos)
{
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// see if there is a colon in the bracketed expression
i = index.indexOf(':', startPos);
if (i >= 0 && i < endPos)
{
// colon: make sure there are two numbers
String firstIndex = index.substring(startPos+1, i);
String secondIndex = index.substring(i+1, endPos);
if (TextUtils.isANumber(firstIndex) && TextUtils.isANumber(secondIndex))
{
int startIndex = TextUtils.atoi(firstIndex);
int endIndex = TextUtils.atoi(secondIndex);
int spacing = Math.abs(endIndex - startIndex) + 1;
for(int nextIndex = 1; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + "[" + (startIndex+spacing*nextIndex) +
":" + (endIndex+spacing*nextIndex) + index.substring(endPos);
boolean unique;
if (already != null)
{
unique = !already.contains(an.baseName + newIndex);
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
if (indexAdjusted) break;
}
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// see if this bracketed expression is a pure number
String bracketedExpression = index.substring(startPos+1, endPos);
if (TextUtils.isANumber(bracketedExpression))
{
int nextIndex = TextUtils.atoi(bracketedExpression) + 1;
for(; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + "[" + nextIndex + index.substring(endPos);
boolean unique;
if (already != null)
{
unique = !already.contains(an.baseName + newIndex);
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
if (indexAdjusted) break;
}
// remember the first index that could be incremented in a pinch
if (possibleStart < 0)
{
possibleStart = startPos;
possibleEnd = endPos;
}
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// if there was a possible place to increment, do it
if (!indexAdjusted && possibleStart >= 0)
{
// nothing simple, but this one can be incremented
int i;
for(i=possibleEnd-1; i>possibleStart; i--)
if (!TextUtils.isDigit(index.charAt(i))) break;
int nextIndex = TextUtils.atoi(index.substring(i+1)) + 1;
int startPos = i+1;
if (index.charAt(startPos-1) == separateChar) startPos--;
for(; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + separateChar + nextIndex + index.substring(possibleEnd);
boolean unique;
if (already != null)
{
unique = !already.contains(an.baseName + newIndex);
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
}
}
// if the index was not adjusted, adjust the base part
if (!indexAdjusted)
{
// array contents cannot be incremented: increment base name
String base = an.baseName;
int startPos = base.length();
int endPos = base.length();
// if there is a numeric part at the end, increment that
String localSepString = String.valueOf(separateChar);
while (startPos > 0 && TextUtils.isDigit(base.charAt(startPos-1))) startPos--;
int nextIndex = 1;
if (startPos >= endPos)
{
if (startPos > 0 && base.charAt(startPos-1) == separateChar) startPos--;
} else
{
nextIndex = TextUtils.atoi(base.substring(startPos)) + 1;
localSepString = "";
}
// find the unique index to use
String prefix = base.substring(0, startPos) + localSepString;
if (nextPlainIndex != null)
{
GenMath.MutableInteger nxt = nextPlainIndex.get(prefix);
if (nxt == null)
{
nxt = new GenMath.MutableInteger(cell.getUniqueNameIndex(prefix, cls, nextIndex));
nextPlainIndex.put(prefix, nxt);
}
nextIndex = nxt.intValue();
nxt.increment();
} else
{
nextIndex = cell.getUniqueNameIndex(prefix, cls, nextIndex);
}
an.baseName = prefix + nextIndex + base.substring(endPos);
}
}
StringBuffer result = new StringBuffer();
boolean first = true;
for(ArrayName an : names)
{
if (first) first = false; else
result.append(",");
result.append(an.baseName);
if (an.indexPart != null) result.append(an.indexPart);
}
return result.toString();
}
| private static String uniqueObjectNameLow(String name, Cell cell, Class cls,
Set already, HashMap<String,GenMath.MutableInteger> nextPlainIndex)
{
// first see if the name is unique
if (already != null)
{
if (!already.contains(TextUtils.canonicString(name))) return name;
} else
{
if (cell.isUniqueName(name, cls, null)) return name;
}
// see if there is a "++" anywhere to tell us what to increment
int plusPlusPos = name.indexOf("++");
if (plusPlusPos >= 0)
{
int numStart = plusPlusPos;
while (numStart > 0 && TextUtils.isDigit(name.charAt(numStart-1))) numStart--;
if (numStart < plusPlusPos)
{
int nextIndex = TextUtils.atoi(name.substring(numStart)) + 1;
for( ; ; nextIndex++)
{
String newname = name.substring(0, numStart) + nextIndex + name.substring(plusPlusPos);
if (already != null)
{
if (!already.contains(TextUtils.canonicString(newname))) return newname;
} else
{
if (cell.isUniqueName(newname, cls, null)) return newname;
}
}
}
}
// see if there is a "--" anywhere to tell us what to decrement
int minusMinusPos = name.indexOf("--");
if (minusMinusPos >= 0)
{
int numStart = minusMinusPos;
while (numStart > 0 && TextUtils.isDigit(name.charAt(numStart-1))) numStart--;
if (numStart < minusMinusPos)
{
int nextIndex = TextUtils.atoi(name.substring(numStart)) - 1;
for( ; nextIndex >= 0; nextIndex--)
{
String newname = name.substring(0, numStart) + nextIndex + name.substring(minusMinusPos);
if (already != null)
{
if (!already.contains(TextUtils.canonicString(newname))) return newname;
} else
{
if (cell.isUniqueName(newname, cls, null)) return newname;
}
}
}
}
// break the string into a list of ArrayName objects
List<ArrayName> names = new ArrayList<ArrayName>();
boolean inBracket = false;
int len = name.length();
int startOfBase = 0;
int startOfIndex = -1;
for(int i=0; i<len; i++)
{
char ch = name.charAt(i);
if (ch == '[')
{
if (startOfIndex < 0) startOfIndex = i;
inBracket = true;
}
if (ch == ']') inBracket = false;
if ((ch == ',' && !inBracket) || i == len-1)
{
// remember this arrayname
if (i == len-1) i++;
ArrayName an = new ArrayName();
int endOfBase = startOfIndex;
if (endOfBase < 0) endOfBase = i;
an.baseName = name.substring(startOfBase, endOfBase);
if (startOfIndex >= 0) an.indexPart = name.substring(startOfIndex, i);
names.add(an);
startOfBase = i+1;
startOfIndex = -1;
}
}
char separateChar = '_';
for(ArrayName an : names)
{
// adjust the index part if possible
boolean indexAdjusted = false;
String index = an.indexPart;
if (index != null)
{
int possibleEnd = 0;
int nameLen = index.length();
// see if the index part can be incremented
int possibleStart = -1;
int endPos = nameLen-1;
for(;;)
{
// find the range of characters in square brackets
int startPos = index.lastIndexOf('[', endPos);
if (startPos < 0) break;
// see if there is a comma in the bracketed expression
int i = index.indexOf(',', startPos);
if (i >= 0 && i < endPos)
{
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// see if there is a colon in the bracketed expression
i = index.indexOf(':', startPos);
if (i >= 0 && i < endPos)
{
// colon: make sure there are two numbers
String firstIndex = index.substring(startPos+1, i);
String secondIndex = index.substring(i+1, endPos);
if (TextUtils.isANumber(firstIndex) && TextUtils.isANumber(secondIndex))
{
int startIndex = TextUtils.atoi(firstIndex);
int endIndex = TextUtils.atoi(secondIndex);
int spacing = Math.abs(endIndex - startIndex) + 1;
for(int nextIndex = 1; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + "[" + (startIndex+spacing*nextIndex) +
":" + (endIndex+spacing*nextIndex) + index.substring(endPos);
boolean unique;
if (already != null)
{
unique = !already.contains(TextUtils.canonicString(an.baseName + newIndex));
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
if (indexAdjusted) break;
}
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// see if this bracketed expression is a pure number
String bracketedExpression = index.substring(startPos+1, endPos);
if (TextUtils.isANumber(bracketedExpression))
{
int nextIndex = TextUtils.atoi(bracketedExpression) + 1;
for(; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + "[" + nextIndex + index.substring(endPos);
boolean unique;
if (already != null)
{
unique = !already.contains(TextUtils.canonicString(an.baseName + newIndex));
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
if (indexAdjusted) break;
}
// remember the first index that could be incremented in a pinch
if (possibleStart < 0)
{
possibleStart = startPos;
possibleEnd = endPos;
}
// this bracketed expression cannot be incremented: move on
if (startPos > 0 && index.charAt(startPos-1) == ']')
{
endPos = startPos-1;
continue;
}
break;
}
// if there was a possible place to increment, do it
if (!indexAdjusted && possibleStart >= 0)
{
// nothing simple, but this one can be incremented
int i;
for(i=possibleEnd-1; i>possibleStart; i--)
if (!TextUtils.isDigit(index.charAt(i))) break;
int nextIndex = TextUtils.atoi(index.substring(i+1)) + 1;
int startPos = i+1;
if (index.charAt(startPos-1) == separateChar) startPos--;
for(; ; nextIndex++)
{
String newIndex = index.substring(0, startPos) + separateChar + nextIndex + index.substring(possibleEnd);
boolean unique;
if (already != null)
{
unique = !already.contains(TextUtils.canonicString(an.baseName + newIndex));
} else
{
unique = cell.isUniqueName(an.baseName + newIndex, cls, null);
}
if (unique)
{
indexAdjusted = true;
an.indexPart = newIndex;
break;
}
}
}
}
// if the index was not adjusted, adjust the base part
if (!indexAdjusted)
{
// array contents cannot be incremented: increment base name
String base = an.baseName;
int startPos = base.length();
int endPos = base.length();
// if there is a numeric part at the end, increment that
String localSepString = String.valueOf(separateChar);
while (startPos > 0 && TextUtils.isDigit(base.charAt(startPos-1))) startPos--;
int nextIndex = 1;
if (startPos >= endPos)
{
if (startPos > 0 && base.charAt(startPos-1) == separateChar) startPos--;
} else
{
nextIndex = TextUtils.atoi(base.substring(startPos)) + 1;
localSepString = "";
}
// find the unique index to use
String prefix = base.substring(0, startPos) + localSepString;
if (nextPlainIndex != null)
{
GenMath.MutableInteger nxt = nextPlainIndex.get(prefix);
if (nxt == null)
{
nxt = new GenMath.MutableInteger(cell.getUniqueNameIndex(prefix, cls, nextIndex));
nextPlainIndex.put(prefix, nxt);
}
nextIndex = nxt.intValue();
nxt.increment();
} else
{
nextIndex = cell.getUniqueNameIndex(prefix, cls, nextIndex);
}
an.baseName = prefix + nextIndex + base.substring(endPos);
}
}
StringBuffer result = new StringBuffer();
boolean first = true;
for(ArrayName an : names)
{
if (first) first = false; else
result.append(",");
result.append(an.baseName);
if (an.indexPart != null) result.append(an.indexPart);
}
return result.toString();
}
|
diff --git a/common/logisticspipes/logic/BaseRoutingLogic.java b/common/logisticspipes/logic/BaseRoutingLogic.java
index 8c197d56..c1597067 100644
--- a/common/logisticspipes/logic/BaseRoutingLogic.java
+++ b/common/logisticspipes/logic/BaseRoutingLogic.java
@@ -1,116 +1,113 @@
/**
* Copyright (c) Krapht, 2011
*
* "LogisticsPipes" is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package logisticspipes.logic;
import java.util.ArrayList;
import java.util.Arrays;
import logisticspipes.LogisticsPipes;
import logisticspipes.network.GuiIDs;
import logisticspipes.pipes.basic.RoutedPipe;
import logisticspipes.proxy.MainProxy;
import logisticspipes.proxy.SimpleServiceLocator;
import logisticspipes.routing.IRouter;
import logisticspipes.routing.SearchNode;
import logisticspipes.routing.ServerRouter;
import logisticspipes.utils.Pair;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.ForgeDirection;
import buildcraft.transport.pipes.PipeLogic;
public abstract class BaseRoutingLogic extends PipeLogic{
public RoutedPipe getRoutedPipe(){
return (RoutedPipe) this.container.pipe;
}
public abstract void onWrenchClicked(EntityPlayer entityplayer);
public abstract void destroy();
protected int throttleTime = 20;
private int throttleTimeLeft = 0;
@Override
public void updateEntity() {
super.updateEntity();
if (--throttleTimeLeft > 0) return;
throttledUpdateEntity();
resetThrottle();
}
public void throttledUpdateEntity(){}
protected void resetThrottle(){
throttleTimeLeft = throttleTime;
}
@Override
public boolean blockActivated(EntityPlayer entityplayer) {
if (entityplayer.getCurrentEquippedItem() == null) {
if (!entityplayer.isSneaking()) return false;
//getRoutedPipe().getRouter().displayRoutes();
if (LogisticsPipes.DEBUG) {
doDebugStuff(entityplayer);
}
return true;
} else if (entityplayer.getCurrentEquippedItem().getItem() == LogisticsPipes.LogisticsNetworkMonitior) {
if(MainProxy.isServer(entityplayer.worldObj)) {
entityplayer.openGui(LogisticsPipes.instance, GuiIDs.GUI_RoutingStats_ID, worldObj, xCoord, yCoord, zCoord);
}
return true;
} else if (SimpleServiceLocator.buildCraftProxy.isWrenchEquipped(entityplayer)) {
onWrenchClicked(entityplayer);
return true;
} else if (entityplayer.getCurrentEquippedItem().getItem() == LogisticsPipes.LogisticsRemoteOrderer) {
if(MainProxy.isServer(entityplayer.worldObj)) {
entityplayer.openGui(LogisticsPipes.instance, GuiIDs.GUI_Normal_Orderer_ID, worldObj, xCoord, yCoord, zCoord);
}
return true;
}
return super.blockActivated(entityplayer);
}
private void doDebugStuff(EntityPlayer entityplayer) {
//entityplayer.worldObj.setWorldTime(4951);
IRouter r = getRoutedPipe().getRouter();
if(!(r instanceof ServerRouter)) return;
System.out.println("***");
ServerRouter sr = (ServerRouter) r;
System.out.println("ID: " + r.getSimpleID());
System.out.println("---------CONNECTED TO---------------");
for (RoutedPipe adj : sr._adjacent.keySet()) {
System.out.println(adj.getRouter().getSimpleID());
}
System.out.println();
System.out.println("========DISTANCE TABLE==============");
for(SearchNode n : r.getIRoutersByCost()) {
System.out.println(n.node.getId() + " @ " + n.distance + " -> "+ n.getFlags());
}
System.out.println();
System.out.println("*******EXIT ROUTE TABLE*************");
ArrayList<Pair<ForgeDirection, ForgeDirection>> table = r.getRouteTable();
for (int i=0; i < table.size(); i++){
if(table.get(i)!=null)
System.out.println(i + " -> " + r.getSimpleID() + " via " + table.get(i).getValue1().toString());
}
System.out.println();
System.out.println("++++++++++CONNECTIONS+++++++++++++++");
System.out.println(Arrays.toString(ForgeDirection.VALID_DIRECTIONS));
System.out.println(Arrays.toString(sr.sideConnected));
System.out.println(Arrays.toString(getRoutedPipe().container.pipeConnectionsBuffer));
- System.out.println(Arrays.toString(getRoutedPipe().container.renderState.pipeConnectionMatrix._connected));
getRoutedPipe().refreshConnectionAndRender(true);
- System.out.println(Arrays.toString(getRoutedPipe().container.pipeConnectionsBuffer));
- System.out.println(Arrays.toString(getRoutedPipe().container.renderState.pipeConnectionMatrix._connected));
}
}
| false | true | private void doDebugStuff(EntityPlayer entityplayer) {
//entityplayer.worldObj.setWorldTime(4951);
IRouter r = getRoutedPipe().getRouter();
if(!(r instanceof ServerRouter)) return;
System.out.println("***");
ServerRouter sr = (ServerRouter) r;
System.out.println("ID: " + r.getSimpleID());
System.out.println("---------CONNECTED TO---------------");
for (RoutedPipe adj : sr._adjacent.keySet()) {
System.out.println(adj.getRouter().getSimpleID());
}
System.out.println();
System.out.println("========DISTANCE TABLE==============");
for(SearchNode n : r.getIRoutersByCost()) {
System.out.println(n.node.getId() + " @ " + n.distance + " -> "+ n.getFlags());
}
System.out.println();
System.out.println("*******EXIT ROUTE TABLE*************");
ArrayList<Pair<ForgeDirection, ForgeDirection>> table = r.getRouteTable();
for (int i=0; i < table.size(); i++){
if(table.get(i)!=null)
System.out.println(i + " -> " + r.getSimpleID() + " via " + table.get(i).getValue1().toString());
}
System.out.println();
System.out.println("++++++++++CONNECTIONS+++++++++++++++");
System.out.println(Arrays.toString(ForgeDirection.VALID_DIRECTIONS));
System.out.println(Arrays.toString(sr.sideConnected));
System.out.println(Arrays.toString(getRoutedPipe().container.pipeConnectionsBuffer));
System.out.println(Arrays.toString(getRoutedPipe().container.renderState.pipeConnectionMatrix._connected));
getRoutedPipe().refreshConnectionAndRender(true);
System.out.println(Arrays.toString(getRoutedPipe().container.pipeConnectionsBuffer));
System.out.println(Arrays.toString(getRoutedPipe().container.renderState.pipeConnectionMatrix._connected));
}
| private void doDebugStuff(EntityPlayer entityplayer) {
//entityplayer.worldObj.setWorldTime(4951);
IRouter r = getRoutedPipe().getRouter();
if(!(r instanceof ServerRouter)) return;
System.out.println("***");
ServerRouter sr = (ServerRouter) r;
System.out.println("ID: " + r.getSimpleID());
System.out.println("---------CONNECTED TO---------------");
for (RoutedPipe adj : sr._adjacent.keySet()) {
System.out.println(adj.getRouter().getSimpleID());
}
System.out.println();
System.out.println("========DISTANCE TABLE==============");
for(SearchNode n : r.getIRoutersByCost()) {
System.out.println(n.node.getId() + " @ " + n.distance + " -> "+ n.getFlags());
}
System.out.println();
System.out.println("*******EXIT ROUTE TABLE*************");
ArrayList<Pair<ForgeDirection, ForgeDirection>> table = r.getRouteTable();
for (int i=0; i < table.size(); i++){
if(table.get(i)!=null)
System.out.println(i + " -> " + r.getSimpleID() + " via " + table.get(i).getValue1().toString());
}
System.out.println();
System.out.println("++++++++++CONNECTIONS+++++++++++++++");
System.out.println(Arrays.toString(ForgeDirection.VALID_DIRECTIONS));
System.out.println(Arrays.toString(sr.sideConnected));
System.out.println(Arrays.toString(getRoutedPipe().container.pipeConnectionsBuffer));
getRoutedPipe().refreshConnectionAndRender(true);
}
|
diff --git a/src/main/java/edu/stanford/prpl/junction/impl/JunctionMaker.java b/src/main/java/edu/stanford/prpl/junction/impl/JunctionMaker.java
index ce20c69..2418f61 100644
--- a/src/main/java/edu/stanford/prpl/junction/impl/JunctionMaker.java
+++ b/src/main/java/edu/stanford/prpl/junction/impl/JunctionMaker.java
@@ -1,241 +1,241 @@
package edu.stanford.prpl.junction.impl;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.json.JSONException;
import org.json.JSONObject;
import edu.stanford.prpl.junction.api.activity.ActivityDescription;
import edu.stanford.prpl.junction.api.activity.JunctionActor;
import edu.stanford.prpl.junction.api.messaging.MessageHandler;
import edu.stanford.prpl.junction.api.messaging.MessageHeader;
public class JunctionMaker {
private String mSwitchboard;
public static JunctionMaker getInstance(String switchboard) {
// todo: singleton per-URL?
return new JunctionMaker(switchboard);
}
public static JunctionMaker getInstance() {
return new JunctionMaker();
}
protected JunctionMaker() {
}
protected JunctionMaker(String switchboard) {
mSwitchboard=switchboard;
}
// TODO: add 0-arg constructor for activities w/ given junction hosts
// or allow static call for newJunction?
public Junction newJunction(String friendlyName, JunctionActor actor) {
return null;
}
public Junction newJunction(URI uri, JunctionActor actor) {
ActivityDescription desc = new ActivityDescription();
desc.setHost(uri.getHost());
if (uri.getPath() != null) { // TODO: check to make sure this works for URIs w/o path
desc.setSessionID(uri.getPath().substring(1));
}
return newJunction(desc,actor);
/*
ActivityDescription desc = new ActivityDescription();
String query = url.getQuery();
String tmp;
if (null != (tmp = getURLParam(query,"sessionID"))) {
desc.setSessionID(tmp);
}
desc.setHost(url.getHost());
//desc.setActorID(actor.getActorID());
return newJunction(desc,actor);
*/
}
private String getURLParam(String query, String param) {
int pos = query.indexOf(param+"=");
if (pos < 0) return null;
String val = query.substring(pos+1+param.length());
pos = val.indexOf("&");
if (pos > 0)
val = val.substring(0,pos);
return val;
}
public Junction newJunction(ActivityDescription desc, JunctionActor actor) {
// this needs to be made more formal
if (null == desc.getHost() && mSwitchboard != null) {
desc.setHost(mSwitchboard);
}
Junction jx = new Junction(desc);
jx.registerActor(actor);
// creating an activity is an activity using a JunctionService.
// Invite the JunctionMaker service to the session.
// This service will be bundled with all Junction servers.
//activity.requestService("JunctionMaker", mHostURL, "edu.stanford.prpl.junction.impl.JunctionMakerService");
return jx;
}
public void inviteActorByListenerService(final URI invitationURI, URI listenerServiceURI) {
JunctionActor actor = new JunctionActor("inviter") {
@Override
public void onActivityJoin() {
JSONObject invitation = new JSONObject();
try {
invitation.put("activity", invitationURI.toString());
} catch (Exception e) {}
getJunction().sendMessageToSession(invitation);
leave();
}
};
JunctionMaker.getInstance().newJunction(listenerServiceURI, actor);
}
/**
* Requests a listening service to join this activity as the prescribed role. Here,
* the service must be detailed in the activity description's list of roles.
*
* An example platform in the role specification:
* { role: "dealer", platforms: [
* { platform: "jxservice",
* classname: "edu.stanford.prpl.poker.dealer",
* switchboard: "my.foreign.switchboard" } ] }
*
* If switchboard is not present, it is assumed to be on the same switchboard
* on which this activity is being run.
*
* @param role
* @param host
* @param serviceName
*/
public void inviteActorService(final URI invitationURI) {
ActivityDescription desc = getActivityDescription(invitationURI);
System.out.println("Desc: " + desc.getJSON().toString());
// find service platform spec
int i;
String role = invitationURI.toString();
if ((i=role.indexOf("requestedRole=")) >= 0) {
role = role.substring(i+14);
if ((i=role.indexOf("&")) >= 0) {
role = role.substring(0,i);
}
System.out.println("inviting service for role " + role);
JSONObject platform = desc.getRolePlatform(role, "jxservice");
System.out.println("got platform " + platform);
if (platform == null) return;
String switchboard = platform.optString("switchboard");
System.out.println("switchboard: " + switchboard);
- if (switchboard == null) {
+ if (switchboard == null || switchboard.length() == 0) {
switchboard = invitationURI.getHost();
System.out.println("switchboard is null, new: " + switchboard);
}
final String serviceName = platform.optString("serviceName");
// // // // // // // // // // // // // // // //
JunctionActor actor = new JunctionActor("inviter") {
@Override
public void onActivityJoin() {
JSONObject invitation = new JSONObject();
try {
invitation.put("activity", invitationURI.toString());
invitation.put("serviceName",serviceName);
} catch (Exception e) {}
getJunction().sendMessageToSession(invitation);
leave();
}
};
// remote jxservice activity:
URI remoteServiceActivity=null;
try {
remoteServiceActivity = new URI("junction://"+switchboard+"/jxservice");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
System.out.println("Inviting serice at uri " + remoteServiceActivity);
JunctionMaker.getInstance().newJunction(remoteServiceActivity, actor);
}
}
public ActivityDescription getActivityDescription(URI uri) {
// TODO: Move the XMPPConnection into the JunctionMaker
// (out of Junction)
/*
JunctionMaker jm = null;
String host = uri.getHost();
if (host.equals(mSwitchboard)) {
jm = this;
} else {
jm = new JunctionMaker(host);
}
*/
String host = uri.getHost();
String sessionID = uri.getPath().substring(1);
XMPPConnection conn = getXMPPConnection(host);
String room = sessionID+"@conference."+host;
System.err.println("looking up info from xmpp room " + room);
try {
RoomInfo info = MultiUserChat.getRoomInfo(conn, room);
String descString = info.getDescription();
JSONObject descJSON = new JSONObject(descString);
return new ActivityDescription(descJSON);
} catch (XMPPException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private XMPPConnection getXMPPConnection(String host) {
XMPPConnection mXMPPConnection= new XMPPConnection(host);
try {
mXMPPConnection.connect();
mXMPPConnection.loginAnonymously();
return mXMPPConnection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| true | true | public void inviteActorService(final URI invitationURI) {
ActivityDescription desc = getActivityDescription(invitationURI);
System.out.println("Desc: " + desc.getJSON().toString());
// find service platform spec
int i;
String role = invitationURI.toString();
if ((i=role.indexOf("requestedRole=")) >= 0) {
role = role.substring(i+14);
if ((i=role.indexOf("&")) >= 0) {
role = role.substring(0,i);
}
System.out.println("inviting service for role " + role);
JSONObject platform = desc.getRolePlatform(role, "jxservice");
System.out.println("got platform " + platform);
if (platform == null) return;
String switchboard = platform.optString("switchboard");
System.out.println("switchboard: " + switchboard);
if (switchboard == null) {
switchboard = invitationURI.getHost();
System.out.println("switchboard is null, new: " + switchboard);
}
final String serviceName = platform.optString("serviceName");
// // // // // // // // // // // // // // // //
JunctionActor actor = new JunctionActor("inviter") {
@Override
public void onActivityJoin() {
JSONObject invitation = new JSONObject();
try {
invitation.put("activity", invitationURI.toString());
invitation.put("serviceName",serviceName);
} catch (Exception e) {}
getJunction().sendMessageToSession(invitation);
leave();
}
};
// remote jxservice activity:
URI remoteServiceActivity=null;
try {
remoteServiceActivity = new URI("junction://"+switchboard+"/jxservice");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
System.out.println("Inviting serice at uri " + remoteServiceActivity);
JunctionMaker.getInstance().newJunction(remoteServiceActivity, actor);
}
}
| public void inviteActorService(final URI invitationURI) {
ActivityDescription desc = getActivityDescription(invitationURI);
System.out.println("Desc: " + desc.getJSON().toString());
// find service platform spec
int i;
String role = invitationURI.toString();
if ((i=role.indexOf("requestedRole=")) >= 0) {
role = role.substring(i+14);
if ((i=role.indexOf("&")) >= 0) {
role = role.substring(0,i);
}
System.out.println("inviting service for role " + role);
JSONObject platform = desc.getRolePlatform(role, "jxservice");
System.out.println("got platform " + platform);
if (platform == null) return;
String switchboard = platform.optString("switchboard");
System.out.println("switchboard: " + switchboard);
if (switchboard == null || switchboard.length() == 0) {
switchboard = invitationURI.getHost();
System.out.println("switchboard is null, new: " + switchboard);
}
final String serviceName = platform.optString("serviceName");
// // // // // // // // // // // // // // // //
JunctionActor actor = new JunctionActor("inviter") {
@Override
public void onActivityJoin() {
JSONObject invitation = new JSONObject();
try {
invitation.put("activity", invitationURI.toString());
invitation.put("serviceName",serviceName);
} catch (Exception e) {}
getJunction().sendMessageToSession(invitation);
leave();
}
};
// remote jxservice activity:
URI remoteServiceActivity=null;
try {
remoteServiceActivity = new URI("junction://"+switchboard+"/jxservice");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
System.out.println("Inviting serice at uri " + remoteServiceActivity);
JunctionMaker.getInstance().newJunction(remoteServiceActivity, actor);
}
}
|
diff --git a/fabric/fabric-agent/src/main/java/org/fusesource/fabric/agent/ObrResolver.java b/fabric/fabric-agent/src/main/java/org/fusesource/fabric/agent/ObrResolver.java
index 136ce02a1..79d4a7cb9 100644
--- a/fabric/fabric-agent/src/main/java/org/fusesource/fabric/agent/ObrResolver.java
+++ b/fabric/fabric-agent/src/main/java/org/fusesource/fabric/agent/ObrResolver.java
@@ -1,343 +1,352 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.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.fusesource.fabric.agent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.felix.bundlerepository.Property;
import org.apache.felix.bundlerepository.Reason;
import org.apache.felix.bundlerepository.Repository;
import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.apache.felix.bundlerepository.Requirement;
import org.apache.felix.bundlerepository.Resource;
import org.apache.felix.bundlerepository.impl.ResourceImpl;
import org.apache.karaf.features.BundleInfo;
import org.apache.karaf.features.Feature;
import org.fusesource.fabric.fab.DependencyTree;
import org.fusesource.fabric.fab.osgi.FabBundleInfo;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ObrResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(ObrResolver.class);
private RepositoryAdmin repositoryAdmin;
public ObrResolver() {
}
public ObrResolver(RepositoryAdmin repositoryAdmin) {
this.repositoryAdmin = repositoryAdmin;
}
public RepositoryAdmin getRepositoryAdmin() {
return repositoryAdmin;
}
public void setRepositoryAdmin(RepositoryAdmin repositoryAdmin) {
this.repositoryAdmin = repositoryAdmin;
}
public List<Resource> resolve(Set<Feature> features,
Set<String> bundles,
Map<String, FabBundleInfo> fabs,
Set<String> overrides,
Map<String, File> downloads) throws Exception {
List<Requirement> reqs = new ArrayList<Requirement>();
List<Resource> ress = new ArrayList<Resource>();
List<Resource> deploy = new ArrayList<Resource>();
Map<Object, BundleInfo> infos = new HashMap<Object, BundleInfo>();
for (Feature feature : features) {
for (BundleInfo bundleInfo : feature.getBundles()) {
try {
//We ignore Fabs completely as the are already been added to fabs set.
if (!bundleInfo.getLocation().startsWith(DeploymentAgent.FAB_PROTOCOL)) {
Resource res = createResource(bundleInfo.getLocation(), downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundleInfo.getLocation());
}
ress.add(res);
infos.put(res, bundleInfo);
}
} catch (MalformedURLException e) {
Requirement req = parseRequirement(bundleInfo.getLocation());
reqs.add(req);
infos.put(req, bundleInfo);
}
}
}
for (String bundle : bundles) {
Resource res = createResource(bundle, downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundle);
}
ress.add(res);
infos.put(res, new SimpleBundleInfo(bundle, false));
}
for (FabBundleInfo fab : fabs.values()) {
Resource res = repositoryAdmin.getHelper().createResource(fab.getManifest());
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab " + fab.getUrl());
}
((ResourceImpl) res).put(Resource.URI, DeploymentAgent.FAB_PROTOCOL + fab.getUrl(), Property.URI);
ress.add(res);
infos.put(res, new SimpleBundleInfo(fab.getUrl(), false));
for (DependencyTree dep : fab.getBundles()) {
if (dep.isBundle()) {
URL url = new URL(dep.getUrl());
Resource resDep = createResource(dep.getUrl(), downloads, fabs);
if (resDep == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab dependency " + url);
}
ress.add(resDep);
infos.put(resDep, new SimpleBundleInfo(dep.getUrl(), true));
}
}
}
for (String override : overrides) {
- Resource over = createResource(override, downloads, fabs);
+ Resource over = null;
+ try {
+ over = createResource(override, downloads, fabs);
+ } catch (Exception e) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.info("Ignoring patched resource: {}: {}", new Object[] { override, e.getMessage() }, e);
+ } else {
+ LOGGER.info("Ignoring patched resource: {}: {}", override, e.getMessage());
+ }
+ }
if (over == null) {
// Artifacts may not be valid bundles, so just ignore those artifacts
continue;
}
boolean add = false;
boolean dependency = true;
for (Resource res : new ArrayList<Resource>(ress)) {
if (res.getSymbolicName().equals(over.getSymbolicName())) {
Version v1 = res.getVersion();
Version v2 = new Version(v1.getMajor(), v1.getMinor() + 1, 0);
if (compareFuseVersions(v1, over.getVersion()) < 0 && compareFuseVersions(over.getVersion(), v2) < 0) {
ress.remove(res);
dependency &= infos.remove(res).isDependency();
add = true;
}
}
}
if (add) {
ress.add(over);
infos.put(over, new SimpleBundleInfo(override, dependency));
}
}
Repository repository = repositoryAdmin.getHelper().repository(ress.toArray(new Resource[ress.size()]));
List<Repository> repos = new ArrayList<Repository>();
repos.add(repositoryAdmin.getSystemRepository());
repos.add(repository);
repos.addAll(Arrays.asList(repositoryAdmin.listRepositories()));
org.apache.felix.bundlerepository.Resolver resolver = repositoryAdmin.resolver(repos.toArray(new Repository[repos.size()]));
for (Resource res : ress) {
if (!infos.get(res).isDependency()) {
resolver.add(res);
}
}
for (Requirement req : reqs) {
resolver.add(req);
}
if (!resolver.resolve(org.apache.felix.bundlerepository.Resolver.NO_OPTIONAL_RESOURCES)) {
StringWriter w = new StringWriter();
PrintWriter out = new PrintWriter(w);
Reason[] failedReqs = resolver.getUnsatisfiedRequirements();
if ((failedReqs != null) && (failedReqs.length > 0)) {
out.println("Unsatisfied requirement(s):");
printUnderline(out, 27);
for (Reason r : failedReqs) {
out.println(" " + r.getRequirement().getName() + ":" + r.getRequirement().getFilter());
out.println(" " + r.getResource().getPresentationName());
}
} else {
out.println("Could not resolve targets.");
}
out.flush();
throw new Exception("Can not resolve feature:\n" + w.toString());
}
Collections.addAll(deploy, resolver.getAddedResources());
Collections.addAll(deploy, resolver.getRequiredResources());
return deploy;
}
private int compareFuseVersions(org.osgi.framework.Version v1, org.osgi.framework.Version v2) {
int c = v1.getMajor() - v2.getMajor();
if (c != 0) {
return c;
}
c = v1.getMinor() - v2.getMinor();
if (c != 0) {
return c;
}
c = v1.getMicro() - v2.getMicro();
if (c != 0) {
return c;
}
String q1 = v1.getQualifier();
String q2 = v2.getQualifier();
if (q1.startsWith("fuse-") && q2.startsWith("fuse-")) {
q1 = cleanQualifierForComparison(q1);
q2 = cleanQualifierForComparison(q2);
}
return q1.compareTo(q2);
}
private String cleanQualifierForComparison(String q) {
return q.replace("-alpha-", "-").replace("-beta-", "-")
.replace("-7-0-", "-70-")
.replace("-7-", "-70-");
}
protected Resource createResource(String uri, Map<String, File> urls, Map<String, FabBundleInfo> infos) throws Exception {
URL url = new URL(uri);
Attributes attributes = getAttributes(uri, urls, infos);
ResourceImpl resource = (ResourceImpl) repositoryAdmin.getHelper().createResource(attributes);
if (resource != null) {
if ("file".equals(url.getProtocol()))
{
try {
File f = new File(url.toURI());
resource.put(Resource.SIZE, Long.toString(f.length()), null);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
resource.put(Resource.URI, url.toExternalForm(), null);
}
return resource;
}
protected Attributes getAttributes(String uri, Map<String, File> urls, Map<String, FabBundleInfo> infos) throws Exception {
InputStream is = DeploymentAgent.getBundleInputStream(uri, urls, infos);
byte[] man = loadEntry(is, JarFile.MANIFEST_NAME);
if (man == null)
{
throw new IllegalArgumentException("The specified url is not a valid jar (can't read manifest): " + uri);
}
Manifest manifest = new Manifest(new ByteArrayInputStream(man));
return manifest.getMainAttributes();
}
private byte[] loadEntry(InputStream is, String name) throws IOException
{
try
{
ZipInputStream jis = new ZipInputStream(is);
for (ZipEntry e = jis.getNextEntry(); e != null; e = jis.getNextEntry())
{
if (name.equalsIgnoreCase(e.getName()))
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while ((n = jis.read(buf, 0, buf.length)) > 0)
{
baos.write(buf, 0, n);
}
return baos.toByteArray();
}
}
}
finally
{
is.close();
}
return null;
}
protected void printUnderline(PrintWriter out, int length) {
for (int i = 0; i < length; i++) {
out.print('-');
}
out.println("");
}
protected Requirement parseRequirement(String req) throws InvalidSyntaxException {
int p = req.indexOf(':');
String name;
String filter;
if (p > 0) {
name = req.substring(0, p);
filter = req.substring(p + 1);
} else {
if (req.contains("package")) {
name = "package";
} else if (req.contains("service")) {
name = "service";
} else {
name = "bundle";
}
filter = req;
}
if (!filter.startsWith("(")) {
filter = "(" + filter + ")";
}
return repositoryAdmin.getHelper().requirement(name, filter);
}
private static class SimpleBundleInfo implements BundleInfo {
private final String bundle;
private final boolean dependency;
public SimpleBundleInfo(String bundle, boolean dependency) {
this.bundle = bundle;
this.dependency = dependency;
}
@Override
public String getLocation() {
return bundle;
}
@Override
public int getStartLevel() {
return 0;
}
@Override
public boolean isStart() {
return true;
}
@Override
public boolean isDependency() {
return dependency;
}
}
}
| true | true | public List<Resource> resolve(Set<Feature> features,
Set<String> bundles,
Map<String, FabBundleInfo> fabs,
Set<String> overrides,
Map<String, File> downloads) throws Exception {
List<Requirement> reqs = new ArrayList<Requirement>();
List<Resource> ress = new ArrayList<Resource>();
List<Resource> deploy = new ArrayList<Resource>();
Map<Object, BundleInfo> infos = new HashMap<Object, BundleInfo>();
for (Feature feature : features) {
for (BundleInfo bundleInfo : feature.getBundles()) {
try {
//We ignore Fabs completely as the are already been added to fabs set.
if (!bundleInfo.getLocation().startsWith(DeploymentAgent.FAB_PROTOCOL)) {
Resource res = createResource(bundleInfo.getLocation(), downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundleInfo.getLocation());
}
ress.add(res);
infos.put(res, bundleInfo);
}
} catch (MalformedURLException e) {
Requirement req = parseRequirement(bundleInfo.getLocation());
reqs.add(req);
infos.put(req, bundleInfo);
}
}
}
for (String bundle : bundles) {
Resource res = createResource(bundle, downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundle);
}
ress.add(res);
infos.put(res, new SimpleBundleInfo(bundle, false));
}
for (FabBundleInfo fab : fabs.values()) {
Resource res = repositoryAdmin.getHelper().createResource(fab.getManifest());
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab " + fab.getUrl());
}
((ResourceImpl) res).put(Resource.URI, DeploymentAgent.FAB_PROTOCOL + fab.getUrl(), Property.URI);
ress.add(res);
infos.put(res, new SimpleBundleInfo(fab.getUrl(), false));
for (DependencyTree dep : fab.getBundles()) {
if (dep.isBundle()) {
URL url = new URL(dep.getUrl());
Resource resDep = createResource(dep.getUrl(), downloads, fabs);
if (resDep == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab dependency " + url);
}
ress.add(resDep);
infos.put(resDep, new SimpleBundleInfo(dep.getUrl(), true));
}
}
}
for (String override : overrides) {
Resource over = createResource(override, downloads, fabs);
if (over == null) {
// Artifacts may not be valid bundles, so just ignore those artifacts
continue;
}
boolean add = false;
boolean dependency = true;
for (Resource res : new ArrayList<Resource>(ress)) {
if (res.getSymbolicName().equals(over.getSymbolicName())) {
Version v1 = res.getVersion();
Version v2 = new Version(v1.getMajor(), v1.getMinor() + 1, 0);
if (compareFuseVersions(v1, over.getVersion()) < 0 && compareFuseVersions(over.getVersion(), v2) < 0) {
ress.remove(res);
dependency &= infos.remove(res).isDependency();
add = true;
}
}
}
if (add) {
ress.add(over);
infos.put(over, new SimpleBundleInfo(override, dependency));
}
}
Repository repository = repositoryAdmin.getHelper().repository(ress.toArray(new Resource[ress.size()]));
List<Repository> repos = new ArrayList<Repository>();
repos.add(repositoryAdmin.getSystemRepository());
repos.add(repository);
repos.addAll(Arrays.asList(repositoryAdmin.listRepositories()));
org.apache.felix.bundlerepository.Resolver resolver = repositoryAdmin.resolver(repos.toArray(new Repository[repos.size()]));
for (Resource res : ress) {
if (!infos.get(res).isDependency()) {
resolver.add(res);
}
}
for (Requirement req : reqs) {
resolver.add(req);
}
if (!resolver.resolve(org.apache.felix.bundlerepository.Resolver.NO_OPTIONAL_RESOURCES)) {
StringWriter w = new StringWriter();
PrintWriter out = new PrintWriter(w);
Reason[] failedReqs = resolver.getUnsatisfiedRequirements();
if ((failedReqs != null) && (failedReqs.length > 0)) {
out.println("Unsatisfied requirement(s):");
printUnderline(out, 27);
for (Reason r : failedReqs) {
out.println(" " + r.getRequirement().getName() + ":" + r.getRequirement().getFilter());
out.println(" " + r.getResource().getPresentationName());
}
} else {
out.println("Could not resolve targets.");
}
out.flush();
throw new Exception("Can not resolve feature:\n" + w.toString());
}
Collections.addAll(deploy, resolver.getAddedResources());
Collections.addAll(deploy, resolver.getRequiredResources());
return deploy;
}
| public List<Resource> resolve(Set<Feature> features,
Set<String> bundles,
Map<String, FabBundleInfo> fabs,
Set<String> overrides,
Map<String, File> downloads) throws Exception {
List<Requirement> reqs = new ArrayList<Requirement>();
List<Resource> ress = new ArrayList<Resource>();
List<Resource> deploy = new ArrayList<Resource>();
Map<Object, BundleInfo> infos = new HashMap<Object, BundleInfo>();
for (Feature feature : features) {
for (BundleInfo bundleInfo : feature.getBundles()) {
try {
//We ignore Fabs completely as the are already been added to fabs set.
if (!bundleInfo.getLocation().startsWith(DeploymentAgent.FAB_PROTOCOL)) {
Resource res = createResource(bundleInfo.getLocation(), downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundleInfo.getLocation());
}
ress.add(res);
infos.put(res, bundleInfo);
}
} catch (MalformedURLException e) {
Requirement req = parseRequirement(bundleInfo.getLocation());
reqs.add(req);
infos.put(req, bundleInfo);
}
}
}
for (String bundle : bundles) {
Resource res = createResource(bundle, downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundle);
}
ress.add(res);
infos.put(res, new SimpleBundleInfo(bundle, false));
}
for (FabBundleInfo fab : fabs.values()) {
Resource res = repositoryAdmin.getHelper().createResource(fab.getManifest());
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab " + fab.getUrl());
}
((ResourceImpl) res).put(Resource.URI, DeploymentAgent.FAB_PROTOCOL + fab.getUrl(), Property.URI);
ress.add(res);
infos.put(res, new SimpleBundleInfo(fab.getUrl(), false));
for (DependencyTree dep : fab.getBundles()) {
if (dep.isBundle()) {
URL url = new URL(dep.getUrl());
Resource resDep = createResource(dep.getUrl(), downloads, fabs);
if (resDep == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab dependency " + url);
}
ress.add(resDep);
infos.put(resDep, new SimpleBundleInfo(dep.getUrl(), true));
}
}
}
for (String override : overrides) {
Resource over = null;
try {
over = createResource(override, downloads, fabs);
} catch (Exception e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.info("Ignoring patched resource: {}: {}", new Object[] { override, e.getMessage() }, e);
} else {
LOGGER.info("Ignoring patched resource: {}: {}", override, e.getMessage());
}
}
if (over == null) {
// Artifacts may not be valid bundles, so just ignore those artifacts
continue;
}
boolean add = false;
boolean dependency = true;
for (Resource res : new ArrayList<Resource>(ress)) {
if (res.getSymbolicName().equals(over.getSymbolicName())) {
Version v1 = res.getVersion();
Version v2 = new Version(v1.getMajor(), v1.getMinor() + 1, 0);
if (compareFuseVersions(v1, over.getVersion()) < 0 && compareFuseVersions(over.getVersion(), v2) < 0) {
ress.remove(res);
dependency &= infos.remove(res).isDependency();
add = true;
}
}
}
if (add) {
ress.add(over);
infos.put(over, new SimpleBundleInfo(override, dependency));
}
}
Repository repository = repositoryAdmin.getHelper().repository(ress.toArray(new Resource[ress.size()]));
List<Repository> repos = new ArrayList<Repository>();
repos.add(repositoryAdmin.getSystemRepository());
repos.add(repository);
repos.addAll(Arrays.asList(repositoryAdmin.listRepositories()));
org.apache.felix.bundlerepository.Resolver resolver = repositoryAdmin.resolver(repos.toArray(new Repository[repos.size()]));
for (Resource res : ress) {
if (!infos.get(res).isDependency()) {
resolver.add(res);
}
}
for (Requirement req : reqs) {
resolver.add(req);
}
if (!resolver.resolve(org.apache.felix.bundlerepository.Resolver.NO_OPTIONAL_RESOURCES)) {
StringWriter w = new StringWriter();
PrintWriter out = new PrintWriter(w);
Reason[] failedReqs = resolver.getUnsatisfiedRequirements();
if ((failedReqs != null) && (failedReqs.length > 0)) {
out.println("Unsatisfied requirement(s):");
printUnderline(out, 27);
for (Reason r : failedReqs) {
out.println(" " + r.getRequirement().getName() + ":" + r.getRequirement().getFilter());
out.println(" " + r.getResource().getPresentationName());
}
} else {
out.println("Could not resolve targets.");
}
out.flush();
throw new Exception("Can not resolve feature:\n" + w.toString());
}
Collections.addAll(deploy, resolver.getAddedResources());
Collections.addAll(deploy, resolver.getRequiredResources());
return deploy;
}
|
diff --git a/library/src/main/java/com/malhartech/lib/testbench/SeedEventGenerator.java b/library/src/main/java/com/malhartech/lib/testbench/SeedEventGenerator.java
index 2e1b4c7f4..6212e7dd0 100644
--- a/library/src/main/java/com/malhartech/lib/testbench/SeedEventGenerator.java
+++ b/library/src/main/java/com/malhartech/lib/testbench/SeedEventGenerator.java
@@ -1,216 +1,218 @@
/*
* Copyright (c) 2012 Malhar, Inc.
* All Rights Reserved.
*/
package com.malhartech.lib.testbench;
import com.malhartech.api.InputOperator;
import com.malhartech.api.BaseOperator;
import com.malhartech.api.DefaultOutputPort;
import com.malhartech.lib.util.OneKeyValPair;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.malhartech.api.AsyncInputOperator;
import com.malhartech.api.BaseOperator;
import com.malhartech.api.DefaultOutputPort;
import com.malhartech.lib.util.OneKeyValPair;
/**
* Generates one time seed load based on range provided for the keys, and adds new classification to incoming keys. The new tuple is emitted
* on the output port <b>data</b>
* <br>
* Examples of getting seed distributions include<br>
* Clients data of a company for every clientId (key is clienId)<br>
* Persons age, gender, for every phone number (key is phone number)<br>
* Year, color, mileage for every car make (key is car make model)<br>
* <br>
* The classification to be done is based on the value of the property <b>key</b>. This property provides all the classification
* information and their ranges<br>The range of values for the key is given in the format described below<br>
* <br>
* <b>Benchmarks</b>: Generate as many tuples as possible in inline mode<br>
* HashMap<String, String>: 8 million/sec with no classification; 1.8 million tuples/sec with classification<br>
* HashMap<Sring, ArrayList<Integer>>: 8 million/sec with no classification; 3.5 million tuples/sec with classification<br>
* <br>
* <b>Default schema</b>:<br>
* Schema for port <b>data</b>: The default schema is HashMap<String, ArrayList<valueData>>, where valueData is class{String, Integer}<br>
* <b>String schema</b>: The string is "key;valkey1:value1;valkey2:value2;..."<br>
* <b>HashMap schema</b>: Key is String, and Value is a ArrrayList<String, Number><br>
* The value in both the schemas is an integer (for choice of strings, these are enum values)
* <br>
* <b>Port Interface</b><br>
* <b>data</b>: Output port for emitting the new classified seed<br>
* <br>
* <b>Properties</b>:
* <b>seed_start</b>: An integer for the seed to start from<br>
* <b>seed_end</b>: An integer for the seed to end with<br>
* <br>string_schema</b>: If set to true, operates in string schema mode<br>
* <br>key</b>: Classifier keys to be inserted randomly. Format is "key1,key1start, key1end; key2, key2start, key2end;..."
* <br>
* Compile time checks are:<br>
* <b>seed_start</b>Has to be an integer<br>
* <b>seed_end</b>Has to be an integer<br>
* <b>key</b>If provided has to be in format "key1,key1start,key1end;key2, key2start, key2end; ..."
* <br>
*
* @author amol
*/
public class SeedEventGenerator extends BaseOperator implements InputOperator
{
public final transient DefaultOutputPort<HashMap<String, ArrayList<OneKeyValPair>>> keyvalpair_list = new DefaultOutputPort<HashMap<String, ArrayList<OneKeyValPair>>>(this);
public final transient DefaultOutputPort<HashMap<String, ArrayList<Integer>>> val_list = new DefaultOutputPort<HashMap<String, ArrayList<Integer>>>(this);
public final transient DefaultOutputPort<HashMap<String, String>> string_data = new DefaultOutputPort<HashMap<String, String>>(this);
public final transient DefaultOutputPort<HashMap<String, String>> val_data = new DefaultOutputPort<HashMap<String, String>>(this);
private static Logger LOG = LoggerFactory.getLogger(SeedEventGenerator.class);
/**
* Data for classification values
*/
ArrayList<String> keys = null;
ArrayList<Integer> keys_min = null;
ArrayList<Integer> keys_range = null;
int s_start = 0;
int s_end = 99;
private final Random random = new Random();
public void setSeedstart(int i)
{
s_start = i;
}
public void setSeedend(int i)
{
s_end = i;
}
@Override
public void emitTuples()
{
int lstart = s_start;
int lend = s_end;
if (lstart < lend) {
for (int i = lstart; i < lend; i++) {
emitTuple(i);
}
}
else {
for (int i = lstart; i > lend; i--) {
emitTuple(i);
}
}
}
/**
*
* Inserts a tuple for a given outbound key
*
* @param tuples bag of tuples
* @param key the key
*/
public void emitTuple(int i)
{
- HashMap<String, String> stuple = null;
- HashMap<String, ArrayList<OneKeyValPair>> atuple = null;
+ HashMap<String, String> stuple;
+ HashMap<String, ArrayList<OneKeyValPair>> atuple;
String key = Integer.toString(i);
if (keys == null) {
if (string_data.isConnected()) {
+ stuple = new HashMap<String, String>(1);
stuple.put(key, null);
string_data.emit(stuple);
}
if (keyvalpair_list.isConnected()) {
+ atuple = new HashMap<String, ArrayList<OneKeyValPair>>(1);
atuple.put(key, null);
keyvalpair_list.emit(atuple);
}
return;
}
ArrayList<OneKeyValPair> alist = null;
ArrayList<Integer> vlist = null;
String str = new String();
String vstr = new String();
boolean iskv = keyvalpair_list.isConnected();
boolean isvl = val_list.isConnected();
boolean issd = string_data.isConnected();
boolean isvd = val_data.isConnected();
int j = 0;
for (String s: keys) {
if (iskv) {
if (alist == null) {
alist = new ArrayList<OneKeyValPair>(keys.size());
}
alist.add(new OneKeyValPair<String, Integer>(s, new Integer(keys_min.get(j) + random.nextInt(keys_range.get(j)))));
}
if (isvl) {
if (vlist == null) {
vlist = new ArrayList<Integer>(keys.size());
}
vlist.add(new Integer(keys_min.get(j) + random.nextInt(keys_range.get(j))));
}
if (issd) {
if (!str.isEmpty()) {
str += ';';
}
str += s + ":" + Integer.toString(keys_min.get(j) + random.nextInt(keys_range.get(j)));
}
if (isvd) {
if (!vstr.isEmpty()) {
vstr += ';';
}
vstr += Integer.toString(keys_min.get(j) + random.nextInt(keys_range.get(j)));
}
j++;
}
if (iskv) {
atuple = new HashMap<String, ArrayList<OneKeyValPair>>(1);
atuple.put(key, alist);
keyvalpair_list.emit(atuple);
}
if (isvl) {
HashMap<String, ArrayList<Integer>> ituple = new HashMap<String, ArrayList<Integer>>(1);
ituple.put(key, vlist);
val_list.emit(ituple);
}
if (issd) {
stuple = new HashMap<String, String>(1);
stuple.put(key, str);
string_data.emit(stuple);
}
if (isvd) {
HashMap vtuple = new HashMap<String, String>(1);
vtuple.put(key, vstr);
val_data.emit(vtuple);
}
}
/**
*
* Add a key data. By making a single call we ensure that all three Arrays are not corrupt and that the addition is atomic/one place
*
* @param key
* @param low
* @param high
*/
public void addKeyData(String key, int low, int high)
{
if (keys == null) {
keys = new ArrayList<String>();
keys_min = new ArrayList<Integer>();
keys_range = new ArrayList<Integer>();
}
keys.add(key);
keys_min.add(low);
keys_range.add(high - low + 1);
}
}
| false | true | public void emitTuple(int i)
{
HashMap<String, String> stuple = null;
HashMap<String, ArrayList<OneKeyValPair>> atuple = null;
String key = Integer.toString(i);
if (keys == null) {
if (string_data.isConnected()) {
stuple.put(key, null);
string_data.emit(stuple);
}
if (keyvalpair_list.isConnected()) {
atuple.put(key, null);
keyvalpair_list.emit(atuple);
}
return;
}
ArrayList<OneKeyValPair> alist = null;
ArrayList<Integer> vlist = null;
String str = new String();
String vstr = new String();
boolean iskv = keyvalpair_list.isConnected();
boolean isvl = val_list.isConnected();
boolean issd = string_data.isConnected();
boolean isvd = val_data.isConnected();
int j = 0;
for (String s: keys) {
if (iskv) {
if (alist == null) {
alist = new ArrayList<OneKeyValPair>(keys.size());
}
alist.add(new OneKeyValPair<String, Integer>(s, new Integer(keys_min.get(j) + random.nextInt(keys_range.get(j)))));
}
if (isvl) {
if (vlist == null) {
vlist = new ArrayList<Integer>(keys.size());
}
vlist.add(new Integer(keys_min.get(j) + random.nextInt(keys_range.get(j))));
}
if (issd) {
if (!str.isEmpty()) {
str += ';';
}
str += s + ":" + Integer.toString(keys_min.get(j) + random.nextInt(keys_range.get(j)));
}
if (isvd) {
if (!vstr.isEmpty()) {
vstr += ';';
}
vstr += Integer.toString(keys_min.get(j) + random.nextInt(keys_range.get(j)));
}
j++;
}
if (iskv) {
atuple = new HashMap<String, ArrayList<OneKeyValPair>>(1);
atuple.put(key, alist);
keyvalpair_list.emit(atuple);
}
if (isvl) {
HashMap<String, ArrayList<Integer>> ituple = new HashMap<String, ArrayList<Integer>>(1);
ituple.put(key, vlist);
val_list.emit(ituple);
}
if (issd) {
stuple = new HashMap<String, String>(1);
stuple.put(key, str);
string_data.emit(stuple);
}
if (isvd) {
HashMap vtuple = new HashMap<String, String>(1);
vtuple.put(key, vstr);
val_data.emit(vtuple);
}
}
| public void emitTuple(int i)
{
HashMap<String, String> stuple;
HashMap<String, ArrayList<OneKeyValPair>> atuple;
String key = Integer.toString(i);
if (keys == null) {
if (string_data.isConnected()) {
stuple = new HashMap<String, String>(1);
stuple.put(key, null);
string_data.emit(stuple);
}
if (keyvalpair_list.isConnected()) {
atuple = new HashMap<String, ArrayList<OneKeyValPair>>(1);
atuple.put(key, null);
keyvalpair_list.emit(atuple);
}
return;
}
ArrayList<OneKeyValPair> alist = null;
ArrayList<Integer> vlist = null;
String str = new String();
String vstr = new String();
boolean iskv = keyvalpair_list.isConnected();
boolean isvl = val_list.isConnected();
boolean issd = string_data.isConnected();
boolean isvd = val_data.isConnected();
int j = 0;
for (String s: keys) {
if (iskv) {
if (alist == null) {
alist = new ArrayList<OneKeyValPair>(keys.size());
}
alist.add(new OneKeyValPair<String, Integer>(s, new Integer(keys_min.get(j) + random.nextInt(keys_range.get(j)))));
}
if (isvl) {
if (vlist == null) {
vlist = new ArrayList<Integer>(keys.size());
}
vlist.add(new Integer(keys_min.get(j) + random.nextInt(keys_range.get(j))));
}
if (issd) {
if (!str.isEmpty()) {
str += ';';
}
str += s + ":" + Integer.toString(keys_min.get(j) + random.nextInt(keys_range.get(j)));
}
if (isvd) {
if (!vstr.isEmpty()) {
vstr += ';';
}
vstr += Integer.toString(keys_min.get(j) + random.nextInt(keys_range.get(j)));
}
j++;
}
if (iskv) {
atuple = new HashMap<String, ArrayList<OneKeyValPair>>(1);
atuple.put(key, alist);
keyvalpair_list.emit(atuple);
}
if (isvl) {
HashMap<String, ArrayList<Integer>> ituple = new HashMap<String, ArrayList<Integer>>(1);
ituple.put(key, vlist);
val_list.emit(ituple);
}
if (issd) {
stuple = new HashMap<String, String>(1);
stuple.put(key, str);
string_data.emit(stuple);
}
if (isvd) {
HashMap vtuple = new HashMap<String, String>(1);
vtuple.put(key, vstr);
val_data.emit(vtuple);
}
}
|
diff --git a/Cocoa4Android/src/org/cocoa4android/ui/UITextField.java b/Cocoa4Android/src/org/cocoa4android/ui/UITextField.java
index 416920a..ccc3424 100644
--- a/Cocoa4Android/src/org/cocoa4android/ui/UITextField.java
+++ b/Cocoa4Android/src/org/cocoa4android/ui/UITextField.java
@@ -1,219 +1,222 @@
/*
* Copyright (C) 2012 Wu Tong
*
* 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.cocoa4android.ui;
import org.cocoa4android.cg.CGRect;
import android.content.Context;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import org.cocoa4android.ns.NSTextAlignment;
public class UITextField extends UIView {
private EditText textField = null;
public String placeholder;
public UITextField(){
textField = new EditText(context);
textField.setGravity(Gravity.CENTER_VERTICAL);
textField.setFocusable(YES);
this.setTextField(textField);
this.setView(textField);
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(new float[] {8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY},null,null));
background.getPaint().setColor(UIColor.whiteColor().getColor());
background.getPaint().setStrokeWidth(1);
this.textField.setBackgroundDrawable(background);
this.textField.setPadding((int)(8*scaleDensityX), 0, (int)(8*scaleDensityY), 0);
this.textField.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
+ if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MENU) {
+ return NO;
+ }
if (event.getAction()!=KeyEvent.ACTION_DOWN)
return YES;
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (delegate!=null) {
UITextField.firstResponder = UITextField.this;
UITextField.this.resignFirstResponder();
return delegate.textFieldShouldReturn(UITextField.this);
}
}
return NO;
}
});
this.textField.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (delegate!=null) {
//UITextField.this.resignFirstResponder();
//return delegate.textFieldShouldReturn(UITextField.this);
}
return false;
}
});
}
public UITextField(CGRect frame){
this();
this.setFrame(frame);
}
public EditText getTextField() {
return textField;
}
public void setTextField(EditText textField) {
this.textField = textField;
}
public void setText(String text){
this.textField.setText(text);
}
public String text(){
return this.textField.getText().toString();
}
private UIColor textColor;
public void setTextColor(UIColor color){
this.textField.setTextColor(color.getColor());
textColor = color;
}
public UIColor textColor(){
return textColor;
}
private NSTextAlignment textAlignment;
public void setTextAlignment(NSTextAlignment alignment){
switch (alignment) {
case NSTextAlignmentLeft:
this.textField.setGravity(textField.getGravity()&Gravity.VERTICAL_GRAVITY_MASK|Gravity.LEFT);
break;
case NSTextAlignmentCenter:
this.textField.setGravity(textField.getGravity()&Gravity.VERTICAL_GRAVITY_MASK|Gravity.CENTER);
break;
case NSTextAlignmentRight:
this.textField.setGravity(textField.getGravity()&Gravity.VERTICAL_GRAVITY_MASK|Gravity.RIGHT);
break;
}
textAlignment = alignment;
}
public NSTextAlignment textAlignment() {
return textAlignment;
}
public void setFont(UIFont font) {
this.setFontSize(font.fontSize);
this.textField.setTypeface(font.getFont());
}
public void setFontSize(float fontSize){
this.textField.setTextSize(fontSize*UIScreen.mainScreen().getDensityText());
}
public void setSecureTextEntry(boolean secureTextEntry){
if(secureTextEntry){
String temporary_stored_text = textField.getText().toString().trim();
textField.setTransformationMethod(PasswordTransformationMethod.getInstance());
textField.setText(temporary_stored_text);
}else{
textField.setTransformationMethod(null);
}
}
public boolean isSecureTextEntry(){
return false;
}
@Override
public boolean canBecomeFirstResponder(){
return YES;
}
@Override
public boolean becomeFirstResponder(){
if (!this.isFirstResponder()) {
super.becomeFirstResponder();
textField.requestFocus();
InputMethodManager imm = (InputMethodManager)textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (!imm.isActive()) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
return YES;
}
@Override
public boolean resignFirstResponder(){
if (this.isFirstResponder()) {
super.resignFirstResponder();
textField.clearFocus();
InputMethodManager imm = (InputMethodManager)textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
}
return YES;
}
public String placeholder() {
return placeholder;
}
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
this.textField.setHintTextColor(UIColor.lightGrayColor().getColor());
this.textField.setHint(placeholder);
}
private UITextFieldDelegate delegate = null;
public UITextFieldDelegate delegate() {
return delegate;
}
public void setDelegate(UITextFieldDelegate delegate) {
this.delegate = delegate;
}
public interface UITextFieldDelegate{
/*
//TODO other delegate method
*
public boolean textFieldShouldBeginEditing(UITextField textField);
public void textFieldDidBeginEditing(UITextField textField);
public boolean textFieldShouldEndEditing(UITextField textField);
public void textFieldDidEndEditing(UITextField textField);
public void shouldChangeCharactersInRange(UITextField textField,NSRange range,String string);
public boolean textFieldShouldClear(UITextField textField);
*/
public boolean textFieldShouldReturn(UITextField textField);
/*
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField; // return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField; // became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField; // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField; // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text
- (BOOL)textFieldShouldClear:(UITextField *)textField; // called when clear button pressed. return NO to ignore (no notifications)
- (BOOL)textFieldShouldReturn:(UITextField *)textField; // called when 'return' key pressed. return NO to ignore.
*/
}
}
| true | true | public UITextField(){
textField = new EditText(context);
textField.setGravity(Gravity.CENTER_VERTICAL);
textField.setFocusable(YES);
this.setTextField(textField);
this.setView(textField);
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(new float[] {8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY},null,null));
background.getPaint().setColor(UIColor.whiteColor().getColor());
background.getPaint().setStrokeWidth(1);
this.textField.setBackgroundDrawable(background);
this.textField.setPadding((int)(8*scaleDensityX), 0, (int)(8*scaleDensityY), 0);
this.textField.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()!=KeyEvent.ACTION_DOWN)
return YES;
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (delegate!=null) {
UITextField.firstResponder = UITextField.this;
UITextField.this.resignFirstResponder();
return delegate.textFieldShouldReturn(UITextField.this);
}
}
return NO;
}
});
this.textField.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (delegate!=null) {
//UITextField.this.resignFirstResponder();
//return delegate.textFieldShouldReturn(UITextField.this);
}
return false;
}
});
}
| public UITextField(){
textField = new EditText(context);
textField.setGravity(Gravity.CENTER_VERTICAL);
textField.setFocusable(YES);
this.setTextField(textField);
this.setView(textField);
ShapeDrawable background = new ShapeDrawable(new RoundRectShape(new float[] {8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY, 8*scaleFactorX,8*scaleFactorY},null,null));
background.getPaint().setColor(UIColor.whiteColor().getColor());
background.getPaint().setStrokeWidth(1);
this.textField.setBackgroundDrawable(background);
this.textField.setPadding((int)(8*scaleDensityX), 0, (int)(8*scaleDensityY), 0);
this.textField.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MENU) {
return NO;
}
if (event.getAction()!=KeyEvent.ACTION_DOWN)
return YES;
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (delegate!=null) {
UITextField.firstResponder = UITextField.this;
UITextField.this.resignFirstResponder();
return delegate.textFieldShouldReturn(UITextField.this);
}
}
return NO;
}
});
this.textField.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (delegate!=null) {
//UITextField.this.resignFirstResponder();
//return delegate.textFieldShouldReturn(UITextField.this);
}
return false;
}
});
}
|
diff --git a/src/java/org/apache/log4j/net/SocketNode.java b/src/java/org/apache/log4j/net/SocketNode.java
index 27a4667f..07fa310d 100644
--- a/src/java/org/apache/log4j/net/SocketNode.java
+++ b/src/java/org/apache/log4j/net/SocketNode.java
@@ -1,96 +1,94 @@
// Copyright 1996-2000, International Business Machines
// Corporation. All Rights Reserved.
// Copyright 2000, Ceki Gulcu. All Rights Reserved.
// See the LICENCE file for the terms of usage and distribution.
package org.apache.log4j.net;
import java.net.InetAddress;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import org.apache.log4j.Category;
import org.apache.log4j.Hierarchy;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.Priority;
import org.apache.log4j.NDC;
// Contributors: Moses Hohman <[email protected]>
/**
Read {@link LoggingEvent} objects sent from a remote client using
Sockets (TCP). These logging events are logged according to local
policy, as if they were generated locally.
<p>For example, the socket node might decide to log events to a
local file and also resent them to a second socket node.
@author Ceki Gülcü
@since 0.8.4
*/
public class SocketNode implements Runnable {
Socket socket;
Hierarchy hierarchy;
ObjectInputStream ois;
static Category cat = Category.getInstance(SocketNode.class.getName());
public
SocketNode(Socket socket, Hierarchy hierarchy) {
this.socket = socket;
this.hierarchy = hierarchy;
try {
ois = new ObjectInputStream(socket.getInputStream());
}
catch(Exception e) {
cat.error("Could not open ObjectInputStream to "+socket, e);
}
}
//public
//void finalize() {
//System.err.println("-------------------------Finalize called");
// System.err.flush();
//}
public void run() {
LoggingEvent event;
Category remoteCategory;
try {
while(true) {
event = (LoggingEvent) ois.readObject();
remoteCategory = hierarchy.getInstance(event.categoryName);
event.category = remoteCategory;
if(event.priority.isGreaterOrEqual(remoteCategory.getChainedPriority())) {
remoteCategory.callAppenders(event);
}
}
}
catch(java.io.EOFException e) {
cat.info("Caught java.io.EOFException closing conneciton.");
- }
- catch(java.net.SocketException e) {
+ } catch(java.net.SocketException e) {
cat.info("Caught java.net.SocketException closing conneciton.");
- }
- catch(Exception e) {
- cat.error("Unexpected exception. Closing conneciton.", e);
+ } catch(Exception e) {
+ cat.warn("Unexpected exception. Closing conneciton.", e);
}
try {
ois.close();
}
catch(Exception e) {
cat.info("Could not close connection.", e);
}
}
}
| false | true | public void run() {
LoggingEvent event;
Category remoteCategory;
try {
while(true) {
event = (LoggingEvent) ois.readObject();
remoteCategory = hierarchy.getInstance(event.categoryName);
event.category = remoteCategory;
if(event.priority.isGreaterOrEqual(remoteCategory.getChainedPriority())) {
remoteCategory.callAppenders(event);
}
}
}
catch(java.io.EOFException e) {
cat.info("Caught java.io.EOFException closing conneciton.");
}
catch(java.net.SocketException e) {
cat.info("Caught java.net.SocketException closing conneciton.");
}
catch(Exception e) {
cat.error("Unexpected exception. Closing conneciton.", e);
}
try {
ois.close();
}
catch(Exception e) {
cat.info("Could not close connection.", e);
}
}
| public void run() {
LoggingEvent event;
Category remoteCategory;
try {
while(true) {
event = (LoggingEvent) ois.readObject();
remoteCategory = hierarchy.getInstance(event.categoryName);
event.category = remoteCategory;
if(event.priority.isGreaterOrEqual(remoteCategory.getChainedPriority())) {
remoteCategory.callAppenders(event);
}
}
}
catch(java.io.EOFException e) {
cat.info("Caught java.io.EOFException closing conneciton.");
} catch(java.net.SocketException e) {
cat.info("Caught java.net.SocketException closing conneciton.");
} catch(Exception e) {
cat.warn("Unexpected exception. Closing conneciton.", e);
}
try {
ois.close();
}
catch(Exception e) {
cat.info("Could not close connection.", e);
}
}
|
diff --git a/src/uk/co/oliwali/HawkEye/listeners/MonitorEntityListener.java b/src/uk/co/oliwali/HawkEye/listeners/MonitorEntityListener.java
index 232f7c2..e52746a 100644
--- a/src/uk/co/oliwali/HawkEye/listeners/MonitorEntityListener.java
+++ b/src/uk/co/oliwali/HawkEye/listeners/MonitorEntityListener.java
@@ -1,106 +1,107 @@
package uk.co.oliwali.HawkEye.listeners;
import java.util.Arrays;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageByProjectileEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.event.painting.PaintingBreakEvent.RemoveCause;
import org.bukkit.inventory.ItemStack;
import uk.co.oliwali.HawkEye.HawkEye;
import uk.co.oliwali.HawkEye.DataType;
import uk.co.oliwali.HawkEye.PlayerSession;
import uk.co.oliwali.HawkEye.database.DataManager;
import uk.co.oliwali.HawkEye.entry.BlockEntry;
import uk.co.oliwali.HawkEye.entry.DataEntry;
import uk.co.oliwali.HawkEye.util.Config;
import uk.co.oliwali.HawkEye.util.Util;
/**
* Entity listener class for HawkEye
* Contains system for managing player deaths
* @author oliverw92
*/
public class MonitorEntityListener extends EntityListener {
public HawkEye plugin;
public MonitorEntityListener(HawkEye HawkEye) {
plugin = HawkEye;
}
/**
* Uses the lastAttacker field in the players {@link PlayerSession} to log the death and cause
*/
public void onEntityDeath(EntityDeathEvent event) {
Entity entity = event.getEntity();
//Only interested if it is a player death
if (entity instanceof Player) {
Player victim = (Player) entity;
EntityDamageEvent attackEvent = victim.getLastDamageCause();
//Mob or PVP death
if (attackEvent instanceof EntityDamageByEntityEvent || attackEvent instanceof EntityDamageByProjectileEvent) {
Entity damager;
if (attackEvent instanceof EntityDamageByEntityEvent) damager = ((EntityDamageByEntityEvent)attackEvent).getDamager();
else damager = ((EntityDamageByProjectileEvent)attackEvent).getDamager();
if (damager instanceof Player) {
DataManager.addEntry(new DataEntry(victim, DataType.PVP_DEATH, victim.getLocation(), Util.getEntityName(damager)));
} else {
DataManager.addEntry(new DataEntry(victim, DataType.MOB_DEATH, victim.getLocation(), Util.getEntityName(damager)));
}
//Other death
} else {
- String cause = victim.getLastDamageCause().getCause().name();
+ EntityDamageEvent dEvent = victim.getLastDamageCause();
+ String cause = dEvent == null?"Unknown":victim.getLastDamageCause().getCause().name();
String[] words = cause.split("_");
for (int i = 0; i < words.length; i++)
words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1).toLowerCase();
cause = Util.join(Arrays.asList(words), " ");
DataManager.addEntry(new DataEntry(victim, DataType.OTHER_DEATH, victim.getLocation(), cause));
}
//Log item drops
if (Config.LogDeathDrops) {
String data = null;
for (ItemStack stack : event.getDrops()) {
if (stack.getData() != null)
data = stack.getAmount() + "x " + stack.getTypeId() + ":" + stack.getData().getData();
else
data = stack.getAmount() + "x " + stack.getTypeId();
DataManager.addEntry(new DataEntry(victim, DataType.ITEM_DROP, victim.getLocation(), data));
}
}
}
}
public void onEntityExplode(EntityExplodeEvent event) {
if (event.isCancelled()) return;
for (Block b : event.blockList().toArray(new Block[0]))
DataManager.addEntry(new BlockEntry("Environment", DataType.EXPLOSION, b));
}
public void onPaintingBreak(PaintingBreakEvent event) {
if (event.isCancelled() || event.getCause() != RemoveCause.ENTITY) return;
PaintingBreakByEntityEvent e = (PaintingBreakByEntityEvent)event;
if (e.getRemover() instanceof Player)
DataManager.addEntry(new DataEntry((Player)e.getRemover(), DataType.PAINTING_BREAK, e.getPainting().getLocation(), ""));
}
public void onPaintingPlace(PaintingPlaceEvent event) {
if (event.isCancelled()) return;
DataManager.addEntry(new DataEntry(event.getPlayer(), DataType.PAINTING_PLACE, event.getPainting().getLocation(), ""));
}
}
| true | true | public void onEntityDeath(EntityDeathEvent event) {
Entity entity = event.getEntity();
//Only interested if it is a player death
if (entity instanceof Player) {
Player victim = (Player) entity;
EntityDamageEvent attackEvent = victim.getLastDamageCause();
//Mob or PVP death
if (attackEvent instanceof EntityDamageByEntityEvent || attackEvent instanceof EntityDamageByProjectileEvent) {
Entity damager;
if (attackEvent instanceof EntityDamageByEntityEvent) damager = ((EntityDamageByEntityEvent)attackEvent).getDamager();
else damager = ((EntityDamageByProjectileEvent)attackEvent).getDamager();
if (damager instanceof Player) {
DataManager.addEntry(new DataEntry(victim, DataType.PVP_DEATH, victim.getLocation(), Util.getEntityName(damager)));
} else {
DataManager.addEntry(new DataEntry(victim, DataType.MOB_DEATH, victim.getLocation(), Util.getEntityName(damager)));
}
//Other death
} else {
String cause = victim.getLastDamageCause().getCause().name();
String[] words = cause.split("_");
for (int i = 0; i < words.length; i++)
words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1).toLowerCase();
cause = Util.join(Arrays.asList(words), " ");
DataManager.addEntry(new DataEntry(victim, DataType.OTHER_DEATH, victim.getLocation(), cause));
}
//Log item drops
if (Config.LogDeathDrops) {
String data = null;
for (ItemStack stack : event.getDrops()) {
if (stack.getData() != null)
data = stack.getAmount() + "x " + stack.getTypeId() + ":" + stack.getData().getData();
else
data = stack.getAmount() + "x " + stack.getTypeId();
DataManager.addEntry(new DataEntry(victim, DataType.ITEM_DROP, victim.getLocation(), data));
}
}
}
}
| public void onEntityDeath(EntityDeathEvent event) {
Entity entity = event.getEntity();
//Only interested if it is a player death
if (entity instanceof Player) {
Player victim = (Player) entity;
EntityDamageEvent attackEvent = victim.getLastDamageCause();
//Mob or PVP death
if (attackEvent instanceof EntityDamageByEntityEvent || attackEvent instanceof EntityDamageByProjectileEvent) {
Entity damager;
if (attackEvent instanceof EntityDamageByEntityEvent) damager = ((EntityDamageByEntityEvent)attackEvent).getDamager();
else damager = ((EntityDamageByProjectileEvent)attackEvent).getDamager();
if (damager instanceof Player) {
DataManager.addEntry(new DataEntry(victim, DataType.PVP_DEATH, victim.getLocation(), Util.getEntityName(damager)));
} else {
DataManager.addEntry(new DataEntry(victim, DataType.MOB_DEATH, victim.getLocation(), Util.getEntityName(damager)));
}
//Other death
} else {
EntityDamageEvent dEvent = victim.getLastDamageCause();
String cause = dEvent == null?"Unknown":victim.getLastDamageCause().getCause().name();
String[] words = cause.split("_");
for (int i = 0; i < words.length; i++)
words[i] = words[i].substring(0,1).toUpperCase() + words[i].substring(1).toLowerCase();
cause = Util.join(Arrays.asList(words), " ");
DataManager.addEntry(new DataEntry(victim, DataType.OTHER_DEATH, victim.getLocation(), cause));
}
//Log item drops
if (Config.LogDeathDrops) {
String data = null;
for (ItemStack stack : event.getDrops()) {
if (stack.getData() != null)
data = stack.getAmount() + "x " + stack.getTypeId() + ":" + stack.getData().getData();
else
data = stack.getAmount() + "x " + stack.getTypeId();
DataManager.addEntry(new DataEntry(victim, DataType.ITEM_DROP, victim.getLocation(), data));
}
}
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/SiteListener.java b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/SiteListener.java
index 888b57b1a..faffa378c 100644
--- a/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/SiteListener.java
+++ b/bundles/org.eclipse.equinox.p2.extensionlocation/src/org/eclipse/equinox/internal/p2/extensionlocation/SiteListener.java
@@ -1,356 +1,364 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 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
* Code 9 - ongoing development
*******************************************************************************/
package org.eclipse.equinox.internal.p2.extensionlocation;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
import org.eclipse.equinox.internal.p2.publisher.eclipse.FeatureParser;
import org.eclipse.equinox.internal.p2.update.Site;
import org.eclipse.equinox.internal.provisional.p2.directorywatcher.*;
import org.eclipse.equinox.p2.core.ProvisionException;
import org.eclipse.equinox.p2.publisher.eclipse.*;
import org.eclipse.osgi.service.resolver.BundleDescription;
/**
* @since 1.0
*/
public class SiteListener extends DirectoryChangeListener {
public static final String SITE_POLICY = "org.eclipse.update.site.policy"; //$NON-NLS-1$
public static final String SITE_LIST = "org.eclipse.update.site.list"; //$NON-NLS-1$
private static final String FEATURES = "features"; //$NON-NLS-1$
private static final String PLUGINS = "plugins"; //$NON-NLS-1$
private static final String FEATURE_MANIFEST = "feature.xml"; //$NON-NLS-1$
public static final Object UNINITIALIZED = "uninitialized"; //$NON-NLS-1$
public static final Object INITIALIZING = "initializing"; //$NON-NLS-1$
public static final Object INITIALIZED = "initialized"; //$NON-NLS-1$
private String policy;
private String[] list;
private String siteLocation;
private DirectoryChangeListener delegate;
private String[] managedFiles;
private String[] toBeRemoved;
/*
* Return true if the given list contains the full path of the given file
* handle. Return false otherwise.
*/
private static boolean contains(String[] plugins, File file) {
String filename = file.getAbsolutePath();
for (int i = 0; i < plugins.length; i++)
if (filename.endsWith(new File(plugins[i]).toString()))
return true;
return false;
}
/**
* Given one repo and a base location, ensure cause the other repo to be loaded and then
* poll the base location once updating the repositories accordingly. This method is used to
* ensure that both the metadata and artifact repos corresponding to one location are
* synchronized in one go. It is expected that both repos have been previously created
* so simply loading them here will work and that all their properties etc have been configured
* previously.
* @param metadataRepository
* @param artifactRepository
* @param base
*/
public static synchronized void synchronizeRepositories(ExtensionLocationMetadataRepository metadataRepository, ExtensionLocationArtifactRepository artifactRepository, File base) {
try {
if (metadataRepository == null) {
artifactRepository.reload();
ExtensionLocationMetadataRepositoryFactory factory = new ExtensionLocationMetadataRepositoryFactory();
factory.setAgent(artifactRepository.getProvisioningAgent());
metadataRepository = (ExtensionLocationMetadataRepository) factory.load(artifactRepository.getLocation(), 0, null);
} else if (artifactRepository == null) {
metadataRepository.reload();
ExtensionLocationArtifactRepositoryFactory factory = new ExtensionLocationArtifactRepositoryFactory();
factory.setAgent(metadataRepository.getProvisioningAgent());
artifactRepository = (ExtensionLocationArtifactRepository) factory.load(metadataRepository.getLocation(), 0, null);
}
} catch (ProvisionException e) {
// TODO need proper error handling here. What should we do if there is a failure
// when loading "the other" repo?
e.printStackTrace();
return;
}
artifactRepository.state(INITIALIZING);
metadataRepository.state(INITIALIZING);
File plugins = new File(base, PLUGINS);
File features = new File(base, FEATURES);
DirectoryWatcher watcher = new DirectoryWatcher(new File[] {plugins, features});
// here we have to sync with the inner repos as the extension location repos are
// read-only wrappers.
DirectoryChangeListener listener = new RepositoryListener(metadataRepository.metadataRepository, artifactRepository.artifactRepository);
if (metadataRepository.getProperties().get(SiteListener.SITE_POLICY) != null)
listener = new SiteListener(metadataRepository.getProperties(), metadataRepository.getLocation().toString(), new BundlePoolFilteredListener(listener));
watcher.addListener(listener);
watcher.poll();
artifactRepository.state(INITIALIZED);
metadataRepository.state(INITIALIZED);
}
/*
* Create a new site listener on the given site.
*/
public SiteListener(Map<String, String> properties, String url, DirectoryChangeListener delegate) {
this.siteLocation = url;
this.delegate = delegate;
this.policy = properties.get(SITE_POLICY);
Collection<String> listCollection = new HashSet<String>();
String listString = properties.get(SITE_LIST);
if (listString != null)
for (StringTokenizer tokenizer = new StringTokenizer(listString, ","); tokenizer.hasMoreTokens();) //$NON-NLS-1$
listCollection.add(tokenizer.nextToken());
this.list = listCollection.toArray(new String[listCollection.size()]);
}
/* (non-Javadoc)
* @see org.eclipse.equinox.internal.provisional.p2.directorywatcher.DirectoryChangeListener#isInterested(java.io.File)
*/
public boolean isInterested(File file) {
// make sure that our delegate and super-class are both interested in
// the file before we consider it
if (!delegate.isInterested(file))
return false;
if (Site.POLICY_MANAGED_ONLY.equals(policy)) {
// we only want plug-ins referenced by features
return contains(getManagedFiles(), file);
} else if (Site.POLICY_USER_EXCLUDE.equals(policy)) {
// ensure the file doesn't refer to a plug-in in our list
if (contains(list, file))
return false;
} else if (Site.POLICY_USER_INCLUDE.equals(policy)) {
// we are only interested in plug-ins in the list
if (!contains(list, file))
return false;
} else {
// shouldn't happen... unknown policy type
return false;
}
// at this point we have either a user-include or user-exclude policy set
// and we think we are interested in the file. we should first check to
// see if it is in the list of things to be removed
return !isToBeRemoved(file);
}
/*
* Return a boolean value indicating whether or not the feature pointed to
* by the given file is in the update manager's list of features to be
* uninstalled in its clean-up phase.
*/
private boolean isToBeRemoved(File file) {
String[] removed = getToBeRemoved();
if (removed.length == 0)
return false;
Feature feature = getFeature(file);
if (feature == null)
return false;
for (int i = 0; i < removed.length; i++) {
String line = removed[i];
// the line is a versioned identifier which is id_version
if (line.equals(feature.getId() + '_' + feature.getVersion()))
return true;
}
return false;
}
/*
* Parse and return the feature.xml file in the given location.
* Can return null.
*/
private Feature getFeature(File location) {
if (location.isFile())
return null;
File manifest = new File(location, FEATURE_MANIFEST);
if (!manifest.exists())
return null;
FeatureParser parser = new FeatureParser();
return parser.parse(location);
}
/*
* Return an array describing the list of features are are going
* to be removed by the update manager in its clean-up phase.
* The strings are in the format of versioned identifiers: id_version
*/
private String[] getToBeRemoved() {
if (toBeRemoved != null)
return toBeRemoved;
File configurationLocation = Activator.getConfigurationLocation();
if (configurationLocation == null) {
LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Unable to compute the configuration location.")); //$NON-NLS-1$
toBeRemoved = new String[0];
return toBeRemoved;
}
File toBeUninstalledFile = new File(configurationLocation, "org.eclipse.update/toBeUninstalled"); //$NON-NLS-1$
if (!toBeUninstalledFile.exists()) {
toBeRemoved = new String[0];
return toBeRemoved;
}
// set it to be empty here in case we don't have a match in the file
toBeRemoved = new String[0];
Properties properties = new Properties();
InputStream input = null;
try {
input = new BufferedInputStream(new FileInputStream(toBeUninstalledFile));
properties.load(input);
} catch (IOException e) {
// TODO
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
// ignore
}
}
String urlString = siteLocation;
if (urlString.endsWith(Constants.EXTENSION_LOCATION))
urlString = urlString.substring(0, urlString.length() - Constants.EXTENSION_LOCATION.length());
List<String> result = new ArrayList<String>();
for (Enumeration<Object> e = properties.elements(); e.hasMoreElements();) {
String line = (String) e.nextElement();
StringTokenizer tokenizer = new StringTokenizer(line, ";"); //$NON-NLS-1$
String targetSite = tokenizer.nextToken();
- if (!urlString.equals(targetSite))
+ try {
+ // the urlString is coming from the site location which is an encoded URI
+ // so we need to encode the targetSite string before we check for equality
+ if (!urlString.equals(URIUtil.fromString(targetSite).toString()))
+ continue;
+ } catch (URISyntaxException e1) {
+ // shouldn't happen
+ e1.printStackTrace();
continue;
+ }
result.add(tokenizer.nextToken());
}
toBeRemoved = result.toArray(new String[result.size()]);
return toBeRemoved;
}
/*
* Return an array of files which are managed. This includes all of the features
* for this site, as well as the locations for all the plug-ins referenced by those
* features.
*/
private String[] getManagedFiles() {
if (managedFiles != null)
return managedFiles;
List<String> result = new ArrayList<String>();
File siteFile;
try {
siteFile = URIUtil.toFile(new URI(siteLocation));
} catch (URISyntaxException e) {
LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Unable to create a URL from site location: " + siteLocation, e)); //$NON-NLS-1$
return new String[0];
}
Map<String, File> pluginCache = getPlugins(siteFile);
Map<File, Feature> featureCache = getFeatures(siteFile);
for (File featureFile : featureCache.keySet()) {
// add the feature path
result.add(featureFile.toString());
Feature feature = featureCache.get(featureFile);
FeatureEntry[] entries = feature.getEntries();
for (int inner = 0; inner < entries.length; inner++) {
FeatureEntry entry = entries[inner];
// grab the right location from the plug-in cache
String key = entry.getId() + '/' + entry.getVersion();
File pluginLocation = pluginCache.get(key);
if (pluginLocation != null)
result.add(pluginLocation.toString());
}
}
managedFiles = result.toArray(new String[result.size()]);
return managedFiles;
}
/*
* Iterate over the feature directory and return a map of
* File to Feature objects (from the generator bundle)
*/
private Map<File, Feature> getFeatures(File location) {
Map<File, Feature> result = new HashMap<File, Feature>();
File featureDir = new File(location, FEATURES);
File[] children = featureDir.listFiles();
for (int i = 0; i < children.length; i++) {
File featureLocation = children[i];
if (featureLocation.isDirectory() && featureLocation.getParentFile() != null && featureLocation.getParentFile().getName().equals("features") && new File(featureLocation, "feature.xml").exists()) {//$NON-NLS-1$ //$NON-NLS-2$
FeatureParser parser = new FeatureParser();
Feature entry = parser.parse(featureLocation);
if (entry != null)
result.put(featureLocation, entry);
}
}
return result;
}
/*
* Iterate over the plugins directory and return a map of
* plug-in id/version to File locations.
*/
private Map<String, File> getPlugins(File location) {
File[] plugins = new File(location, PLUGINS).listFiles();
Map<String, File> result = new HashMap<String, File>();
for (int i = 0; plugins != null && i < plugins.length; i++) {
File bundleLocation = plugins[i];
if (bundleLocation.isDirectory() || bundleLocation.getName().endsWith(".jar")) { //$NON-NLS-1$
BundleDescription description = BundlesAction.createBundleDescription(bundleLocation);
if (description != null) {
String id = description.getSymbolicName();
String version = description.getVersion().toString();
result.put(id + '/' + version, bundleLocation);
}
}
}
return result;
}
/* (non-Javadoc)
* @see org.eclipse.equinox.internal.provisional.p2.directorywatcher.RepositoryListener#added(java.io.File)
*/
public boolean added(File file) {
return delegate.added(file);
}
/* (non-Javadoc)
* @see org.eclipse.equinox.internal.provisional.p2.directorywatcher.RepositoryListener#changed(java.io.File)
*/
public boolean changed(File file) {
return delegate.changed(file);
}
/* (non-Javadoc)
* @see org.eclipse.equinox.internal.provisional.p2.directorywatcher.RepositoryListener#getSeenFile(java.io.File)
*/
public Long getSeenFile(File file) {
return delegate.getSeenFile(file);
}
/* (non-Javadoc)
* @see org.eclipse.equinox.internal.provisional.p2.directorywatcher.RepositoryListener#removed(java.io.File)
*/
public boolean removed(File file) {
return delegate.removed(file);
}
/* (non-Javadoc)
* @see org.eclipse.equinox.internal.provisional.p2.directorywatcher.RepositoryListener#startPoll()
*/
public void startPoll() {
delegate.startPoll();
}
/* (non-Javadoc)
* @see org.eclipse.equinox.internal.provisional.p2.directorywatcher.RepositoryListener#stopPoll()
*/
public void stopPoll() {
delegate.stopPoll();
}
}
| false | true | private String[] getToBeRemoved() {
if (toBeRemoved != null)
return toBeRemoved;
File configurationLocation = Activator.getConfigurationLocation();
if (configurationLocation == null) {
LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Unable to compute the configuration location.")); //$NON-NLS-1$
toBeRemoved = new String[0];
return toBeRemoved;
}
File toBeUninstalledFile = new File(configurationLocation, "org.eclipse.update/toBeUninstalled"); //$NON-NLS-1$
if (!toBeUninstalledFile.exists()) {
toBeRemoved = new String[0];
return toBeRemoved;
}
// set it to be empty here in case we don't have a match in the file
toBeRemoved = new String[0];
Properties properties = new Properties();
InputStream input = null;
try {
input = new BufferedInputStream(new FileInputStream(toBeUninstalledFile));
properties.load(input);
} catch (IOException e) {
// TODO
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
// ignore
}
}
String urlString = siteLocation;
if (urlString.endsWith(Constants.EXTENSION_LOCATION))
urlString = urlString.substring(0, urlString.length() - Constants.EXTENSION_LOCATION.length());
List<String> result = new ArrayList<String>();
for (Enumeration<Object> e = properties.elements(); e.hasMoreElements();) {
String line = (String) e.nextElement();
StringTokenizer tokenizer = new StringTokenizer(line, ";"); //$NON-NLS-1$
String targetSite = tokenizer.nextToken();
if (!urlString.equals(targetSite))
continue;
result.add(tokenizer.nextToken());
}
toBeRemoved = result.toArray(new String[result.size()]);
return toBeRemoved;
}
| private String[] getToBeRemoved() {
if (toBeRemoved != null)
return toBeRemoved;
File configurationLocation = Activator.getConfigurationLocation();
if (configurationLocation == null) {
LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Unable to compute the configuration location.")); //$NON-NLS-1$
toBeRemoved = new String[0];
return toBeRemoved;
}
File toBeUninstalledFile = new File(configurationLocation, "org.eclipse.update/toBeUninstalled"); //$NON-NLS-1$
if (!toBeUninstalledFile.exists()) {
toBeRemoved = new String[0];
return toBeRemoved;
}
// set it to be empty here in case we don't have a match in the file
toBeRemoved = new String[0];
Properties properties = new Properties();
InputStream input = null;
try {
input = new BufferedInputStream(new FileInputStream(toBeUninstalledFile));
properties.load(input);
} catch (IOException e) {
// TODO
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
// ignore
}
}
String urlString = siteLocation;
if (urlString.endsWith(Constants.EXTENSION_LOCATION))
urlString = urlString.substring(0, urlString.length() - Constants.EXTENSION_LOCATION.length());
List<String> result = new ArrayList<String>();
for (Enumeration<Object> e = properties.elements(); e.hasMoreElements();) {
String line = (String) e.nextElement();
StringTokenizer tokenizer = new StringTokenizer(line, ";"); //$NON-NLS-1$
String targetSite = tokenizer.nextToken();
try {
// the urlString is coming from the site location which is an encoded URI
// so we need to encode the targetSite string before we check for equality
if (!urlString.equals(URIUtil.fromString(targetSite).toString()))
continue;
} catch (URISyntaxException e1) {
// shouldn't happen
e1.printStackTrace();
continue;
}
result.add(tokenizer.nextToken());
}
toBeRemoved = result.toArray(new String[result.size()]);
return toBeRemoved;
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/MylarTasklistPlugin.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/MylarTasklistPlugin.java
index 3d53a5955..baacbfd78 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/MylarTasklistPlugin.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasklist/MylarTasklistPlugin.java
@@ -1,642 +1,642 @@
/*******************************************************************************
* Copyright (c) 2004 - 2005 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.tasklist;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import org.eclipse.core.runtime.Preferences.PropertyChangeEvent;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.tasklist.internal.ISaveTimerListener;
import org.eclipse.mylar.tasklist.internal.SaveTimer;
import org.eclipse.mylar.tasklist.internal.TaskListExternalizer;
import org.eclipse.mylar.tasklist.planner.internal.ReminderRequiredCollector;
import org.eclipse.mylar.tasklist.planner.internal.TaskReportGenerator;
import org.eclipse.mylar.tasklist.ui.TasksReminderDialog;
import org.eclipse.mylar.tasklist.ui.views.TaskListView;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* @author Mik Kersten
*
* TODO: this class is in serious need of refactoring
*/
public class MylarTasklistPlugin extends AbstractUIPlugin implements IStartup, ISaveTimerListener {
private static MylarTasklistPlugin INSTANCE;
private static TaskListManager taskListManager;
private TaskListExternalizer externalizer;
private List<ITaskHandler> taskHandlers = new ArrayList<ITaskHandler>(); // TODO: use extension points
private List<IContextEditorFactory> contextEditors = new ArrayList<IContextEditorFactory>();
/**
* TODO: move to common color map.
*/
public static final Color ACTIVE_TASK = new Color(Display.getDefault(), 36, 22, 50);
public static final String AUTO_MANAGE_EDITORS = "org.eclipse.mylar.ui.editors.auto.manage";
public static final String PLANNER_WIZARD_ID = "org.eclipse.mylar.tasklist.ui.planner.wizard";
public static final String PLANNER_EDITOR_ID = "org.eclipse.mylar.tasklist.ui.planner.editor";
public static final String REPORT_OPEN_EDITOR = "org.eclipse.mylar.tasklist.report.open.editor";
public static final String REPORT_OPEN_INTERNAL = "org.eclipse.mylar.tasklist.report.open.internal";
public static final String REPORT_OPEN_EXTERNAL = "org.eclipse.mylar.tasklist.report.open.external";
public static final String MULTIPLE_ACTIVE_TASKS = "org.eclipse.mylar.tasklist.active.multipe";
public static final String COPY_TASK_DATA = "org.eclipse.mylar.tasklist.preferences.copyTaskData";
public static final String PLUGIN_ID = "org.eclipse.mylar.tasklist";
public static final String FILE_EXTENSION = ".xml";
public static final String TASK_ID = "org.eclipse.mylar.tasklist.userid";
public static final String DEFAULT_TASK_LIST_FILE = "tasklist" + FILE_EXTENSION;
public static final String TASK_EDITOR_ID = "org.eclipse.mylar.tasklist.ui.taskEditor";
public static final String CATEGORY_EDITOR_ID = "org.eclipse.mylar.tasklist.ui.catEditor";
public static final String SELECTED_PRIORITY = "org.eclipse.mylar.tasklist.filter.priority";
public static final String FILTER_COMPLETE_MODE = "org.eclipse.mylar.tasklist.filter.complete";
public static final String FILTER_INCOMPLETE_MODE = "org.eclipse.mylar.tasklist.filter.incomplete";
public static final String SAVE_TASKLIST_MODE = "org.eclipse.mylar.tasklist.save.mode";
public static final String PREVIOUS_SAVE_DATE = "org.eclipse.mylar.tasklist.save.last";
public static final String DEFAULT_URL_PREFIX = "org.eclipse.mylar.tasklist.defaultUrlPrefix";
public static final String COMMIT_PREFIX_COMPLETED = "org.eclipse.mylar.team.commit.prefix.completed";
public static final String COMMIT_PREFIX_PROGRESS = "org.eclipse.mylar.team.commit.prefix.progress";
public static final String DEFAULT_PREFIX_PROGRESS = "Progress on:";
public static final String DEFAULT_PREFIX_COMPLETED = "Completed:";
private ResourceBundle resourceBundle;
private long AUTOMATIC_BACKUP_SAVE_INTERVAL = 1 * 3600 * 1000; // every hour
private static Date lastBackup = new Date();
private ITaskHighlighter highlighter;
private SaveTimer saveTimer = null;
private static boolean shouldAutoSave = true;
public enum TaskListSaveMode {
ONE_HOUR, THREE_HOURS, DAY;
@Override
public String toString() {
switch (this) {
case ONE_HOUR:
return "1 hour";
case THREE_HOURS:
return "3 hours";
case DAY:
return "1 day";
default:
return "3 hours";
}
}
public static TaskListSaveMode fromString(String string) {
if (string == null)
return null;
if (string.equals("1 hour"))
return ONE_HOUR;
if (string.equals("3 hours"))
return THREE_HOURS;
if (string.equals("1 day"))
return DAY;
return null;
}
public static long fromStringToLong(String string) {
long hour = 3600 * 1000;
switch (fromString(string)) {
case ONE_HOUR:
return hour;
case THREE_HOURS:
return hour * 3;
case DAY:
return hour * 24;
default:
return hour * 3;
}
}
}
public enum ReportOpenMode {
EDITOR, INTERNAL_BROWSER, EXTERNAL_BROWSER;
}
public enum PriorityLevel {
P1, P2, P3, P4, P5;
@Override
public String toString() {
switch (this) {
case P1:
return "P1";
case P2:
return "P2";
case P3:
return "P3";
case P4:
return "P4";
case P5:
return "P5";
default:
return "P5";
}
}
public static PriorityLevel fromString(String string) {
if (string == null)
return null;
if (string.equals("P1"))
return P1;
if (string.equals("P2"))
return P2;
if (string.equals("P3"))
return P3;
if (string.equals("P4"))
return P4;
if (string.equals("P5"))
return P5;
return null;
}
}
private static ITaskActivityListener CONTEXT_MANAGER_TASK_LISTENER = new ITaskActivityListener() {
public void taskActivated(ITask task) {
MylarPlugin.getContextManager().contextActivated(task.getHandleIdentifier(), task.getPath());
}
public void tasksActivated(List<ITask> tasks) {
for (ITask task : tasks) {
MylarPlugin.getContextManager().contextActivated(task.getHandleIdentifier(), task.getPath());
}
}
public void taskDeactivated(ITask task) {
MylarPlugin.getContextManager().contextDeactivated(task.getHandleIdentifier(), task.getPath());
}
public void tasklistRead() {
// ignore
}
public void tastChanged(ITask task) {
// TODO Auto-generated method stub
}
};
/**
* TODO: move into reminder mechanims
*/
private static ShellListener SHELL_LISTENER = new ShellListener() {
public void shellClosed(ShellEvent arg0) {
// ignore
}
/**
* bug 1002249: too slow to save state here
*/
public void shellDeactivated(ShellEvent arg0) {
shouldAutoSave = false;
}
public void shellActivated(ShellEvent arg0) {
getDefault().checkTaskListBackup();
getDefault().checkReminders();
shouldAutoSave = true;
}
public void shellDeiconified(ShellEvent arg0) {
// ingore
}
public void shellIconified(ShellEvent arg0) {
// ignore
}
};
private static IPropertyChangeListener PREFERENCE_LISTENER = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(MULTIPLE_ACTIVE_TASKS)) {
TaskListView.getDefault().togglePreviousAction(!getPrefs().getBoolean(MULTIPLE_ACTIVE_TASKS));
TaskListView.getDefault().toggleNextAction(!getPrefs().getBoolean(MULTIPLE_ACTIVE_TASKS));
TaskListView.getDefault().clearTaskHistory();
}
}
};
public MylarTasklistPlugin() {
super();
INSTANCE = this;
initializeDefaultPreferences(getPrefs());
externalizer = new TaskListExternalizer();
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
File taskListFile = new File(path);
taskListManager = new TaskListManager(taskListFile);
taskListManager.addListener(CONTEXT_MANAGER_TASK_LISTENER);
saveTimer = new SaveTimer(this);
}
public void earlyStartup() {
final IWorkbench workbench = PlatformUI.getWorkbench();
workbench.getDisplay().asyncExec(new Runnable() {
public void run() {
try {
Workbench.getInstance().getActiveWorkbenchWindow().getShell().addShellListener(SHELL_LISTENER);
Workbench.getInstance().getActiveWorkbenchWindow().getShell().addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
if (getDefault() != null)
getDefault().saveTaskListAndContexts();
}
});
MylarPlugin.getDefault().getPluginPreferences().addPropertyChangeListener(PREFERENCE_LISTENER);
taskListManager.readTaskList();
} catch (Exception e) {
MylarPlugin.fail(e, "Task List initialization failed", true);
}
}
});
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
}
@Override
public void stop(BundleContext context) throws Exception {
super.stop(context);
INSTANCE = null;
resourceBundle = null;
}
@Override
protected void initializeDefaultPreferences(IPreferenceStore store) {
store.setDefault(AUTO_MANAGE_EDITORS, true);
store.setDefault(SELECTED_PRIORITY, "P5");
store.setDefault(REPORT_OPEN_EDITOR, true);
store.setDefault(REPORT_OPEN_INTERNAL, false);
store.setDefault(REPORT_OPEN_EXTERNAL, false);
store.setDefault(MULTIPLE_ACTIVE_TASKS, false);
store.setDefault(COMMIT_PREFIX_COMPLETED, DEFAULT_PREFIX_COMPLETED);
store.setDefault(COMMIT_PREFIX_PROGRESS, DEFAULT_PREFIX_PROGRESS);
store.setDefault(SAVE_TASKLIST_MODE, TaskListSaveMode.THREE_HOURS.toString());
}
public static TaskListManager getTaskListManager() {
return taskListManager;
}
/**
* Returns the shared instance.
*/
public static MylarTasklistPlugin getDefault() {
return INSTANCE;
}
/**
* Returns the string from the INSTANCE's resource bundle,
* or 'key' if not found.
*/
public static String getResourceString(String key) {
ResourceBundle bundle = MylarTasklistPlugin.getDefault().getResourceBundle();
try {
return (bundle != null) ? bundle.getString(key) : key;
} catch (MissingResourceException e) {
return key;
}
}
/**
* Returns the INSTANCE's resource bundle,
*/
public ResourceBundle getResourceBundle() {
try {
if (resourceBundle == null)
resourceBundle = ResourceBundle.getBundle("taskListPlugin.TaskListPluginPluginResources");
} catch (MissingResourceException x) {
resourceBundle = null;
}
return resourceBundle;
}
public static IPreferenceStore getPrefs() {
return MylarPlugin.getDefault().getPreferenceStore();
}
/**
* Sets the directory containing the task list file to use.
* Switches immediately to use the data at that location.
*/
public void setDataDirectory(String newDirPath) {
String taskListFilePath = newDirPath + File.separator + DEFAULT_TASK_LIST_FILE;
getTaskListManager().setTaskListFile(new File(taskListFilePath));
getTaskListManager().createNewTaskList();
getTaskListManager().readTaskList();
TaskListView.getDefault().clearTaskHistory();
}
public void saveTaskListAndContexts() {
taskListManager.saveTaskList();
for (ITask task : taskListManager.getTaskList().getActiveTasks()) {
MylarPlugin.getContextManager().saveContext(task.getHandleIdentifier(), task.getPath());
}
// lastSave = new Date();
// INSTANCE.getPreferenceStore().setValue(PREVIOUS_SAVE_DATE, lastSave.getTime());
}
private void checkTaskListBackup() {
// if (getPrefs().contains(PREVIOUS_SAVE_DATE)) {
// lastSave = new Date(getPrefs().getLong(PREVIOUS_SAVE_DATE));
// } else {
// lastSave = new Date();
// getPrefs().setValue(PREVIOUS_SAVE_DATE, lastSave.getTime());
// }
Date currentTime = new Date();
if (currentTime.getTime() > lastBackup.getTime() + AUTOMATIC_BACKUP_SAVE_INTERVAL) {//TaskListSaveMode.fromStringToLong(getPrefs().getString(SAVE_TASKLIST_MODE))) {
MylarTasklistPlugin.getDefault().createTaskListBackupFile();
lastBackup = new Date();
// INSTANCE.getPreferenceStore().setValue(PREVIOUS_SAVE_DATE, lastSave.getTime());
}
}
private void checkReminders() {
// if (getPrefs().getBoolean(REMINDER_CHECK)) {
// getPrefs().setValue(REMINDER_CHECK, false);
final TaskReportGenerator parser = new TaskReportGenerator(MylarTasklistPlugin.getTaskListManager().getTaskList());
parser.addCollector(new ReminderRequiredCollector());
parser.collectTasks();
if (!parser.getAllCollectedTasks().isEmpty()) {
Workbench.getInstance().getDisplay().asyncExec(new Runnable() {
public void run() {
TasksReminderDialog dialog = new TasksReminderDialog(Workbench.getInstance().getDisplay().getActiveShell(), parser.getAllCollectedTasks());
dialog.setBlockOnOpen(false);
dialog.open();
}
});
}
// }
}
public static void setPriorityLevel(PriorityLevel pl) {
getPrefs().setValue(SELECTED_PRIORITY, pl.toString());
}
public static String getPriorityLevel() {
if (getPrefs().contains(SELECTED_PRIORITY)) {
return getPrefs().getString(SELECTED_PRIORITY);
} else {
return PriorityLevel.P5.toString();
}
}
public void setFilterCompleteMode(boolean isFilterOn) {
getPrefs().setValue(FILTER_COMPLETE_MODE, isFilterOn);
}
public boolean isFilterCompleteMode() {
if (getPrefs().contains(FILTER_COMPLETE_MODE)) {
return getPrefs().getBoolean(FILTER_COMPLETE_MODE);
} else {
return false;
}
}
public void setFilterInCompleteMode(boolean isFilterOn) {
getPrefs().setValue(FILTER_INCOMPLETE_MODE, isFilterOn);
}
public boolean isFilterInCompleteMode() {
if (getPrefs().contains(FILTER_INCOMPLETE_MODE)) {
return getPrefs().getBoolean(FILTER_INCOMPLETE_MODE);
} else {
return false;
}
}
/**
* TODO: remove
*/
public ReportOpenMode getReportMode() {
return ReportOpenMode.EDITOR;
// if (getPrefs().getBoolean(REPORT_OPEN_EDITOR)) {
// return ReportOpenMode.EDITOR;
// } else if (getPrefs().getBoolean(REPORT_OPEN_INTERNAL)) {
// return ReportOpenMode.INTERNAL_BROWSER;
// } else {
// return ReportOpenMode.EXTERNAL_BROWSER;
// }
}
public TaskListExternalizer getTaskListExternalizer() {
return externalizer;
}
public List<ITaskHandler> getTaskHandlers() {
return taskHandlers;
}
public ITaskHandler getTaskHandlerForElement(ITaskListElement element) {
for (ITaskHandler taskHandler : taskHandlers) {
if (taskHandler.acceptsItem(element))
return taskHandler;
}
return null;
}
public void addTaskHandler(ITaskHandler taskHandler) {
taskHandlers.add(taskHandler);
}
public void restoreTaskHandlerState() {
for (ITaskHandler handler : taskHandlers) {
handler.restoreState(TaskListView.getDefault());
}
}
private List<IDynamicSubMenuContributor> menuContributors = new ArrayList<IDynamicSubMenuContributor>();
public List<IDynamicSubMenuContributor> getDynamicMenuContributers() {
return menuContributors;
}
public void addDynamicPopupContributor(IDynamicSubMenuContributor contributor) {
menuContributors.add(contributor);
}
private List<ITaskActivationListener> taskListListeners = new ArrayList<ITaskActivationListener>();
public List<ITaskActivationListener> getTaskListListeners() {
return taskListListeners;
}
public void addTaskListListener(ITaskActivationListener taskListListner) {
taskListListeners.add(taskListListner);
}
public void createTaskListBackupFile() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
File taskListFile = new File(path);
String backup = path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
copy(taskListFile, new File(backup));
}
public String getBackupFilePath() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
return path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
}
public void reverseBackup() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
File taskListFile = new File(path);
String backup = path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
copy(new File(backup), taskListFile);
}
/**
* Copies all files in the current data directory to
* the specified folder. Will overwrite.
*/
public void copyDataDirContentsTo(String targetFolderPath) {
File mainDataDir = new File(MylarPlugin.getDefault().getMylarDataDirectory());
for (File currFile : mainDataDir.listFiles()) {
if (currFile.isFile()) {
File destFile = new File(targetFolderPath + File.separator + currFile.getName());
copy(currFile, destFile);
}
}
}
private boolean copy(File src, File dst) {
try {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (IOException ioe) {
return false;
}
}
public boolean isMultipleMode() {
return getPrefs().getBoolean(MULTIPLE_ACTIVE_TASKS);
}
public String[] getSaveOptions() {
String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() };
return options;
}
public ITaskHighlighter getHighlighter() {
return highlighter;
}
public void setHighlighter(ITaskHighlighter highlighter) {
this.highlighter = highlighter;
}
public List<IContextEditorFactory> getContextEditors() {
return contextEditors;
}
public void addContextEditor(IContextEditorFactory contextEditor) {
if (contextEditor != null)
this.contextEditors.add(contextEditor);
}
/**
* Called periodically by the save timer
*/
public void saveRequested() {
if (shouldAutoSave) {
try {
saveTaskListAndContexts();
- MylarPlugin.log("Automatically saved task list", this);
+// MylarPlugin.log("Automatically saved task list", this);
} catch (Exception e) {
- MylarPlugin.fail(e, "Could not auto save task list", true);
+ MylarPlugin.fail(e, "Could not auto save task list", false);
}
}
}
/** For testing only **/
public SaveTimer getSaveTimer() {
return saveTimer;
}
/**
* For testing.
*/
public void setShouldAutoSave(boolean shellActive) {
MylarTasklistPlugin.shouldAutoSave = shellActive;
}
}
| false | true | private void checkTaskListBackup() {
// if (getPrefs().contains(PREVIOUS_SAVE_DATE)) {
// lastSave = new Date(getPrefs().getLong(PREVIOUS_SAVE_DATE));
// } else {
// lastSave = new Date();
// getPrefs().setValue(PREVIOUS_SAVE_DATE, lastSave.getTime());
// }
Date currentTime = new Date();
if (currentTime.getTime() > lastBackup.getTime() + AUTOMATIC_BACKUP_SAVE_INTERVAL) {//TaskListSaveMode.fromStringToLong(getPrefs().getString(SAVE_TASKLIST_MODE))) {
MylarTasklistPlugin.getDefault().createTaskListBackupFile();
lastBackup = new Date();
// INSTANCE.getPreferenceStore().setValue(PREVIOUS_SAVE_DATE, lastSave.getTime());
}
}
private void checkReminders() {
// if (getPrefs().getBoolean(REMINDER_CHECK)) {
// getPrefs().setValue(REMINDER_CHECK, false);
final TaskReportGenerator parser = new TaskReportGenerator(MylarTasklistPlugin.getTaskListManager().getTaskList());
parser.addCollector(new ReminderRequiredCollector());
parser.collectTasks();
if (!parser.getAllCollectedTasks().isEmpty()) {
Workbench.getInstance().getDisplay().asyncExec(new Runnable() {
public void run() {
TasksReminderDialog dialog = new TasksReminderDialog(Workbench.getInstance().getDisplay().getActiveShell(), parser.getAllCollectedTasks());
dialog.setBlockOnOpen(false);
dialog.open();
}
});
}
// }
}
public static void setPriorityLevel(PriorityLevel pl) {
getPrefs().setValue(SELECTED_PRIORITY, pl.toString());
}
public static String getPriorityLevel() {
if (getPrefs().contains(SELECTED_PRIORITY)) {
return getPrefs().getString(SELECTED_PRIORITY);
} else {
return PriorityLevel.P5.toString();
}
}
public void setFilterCompleteMode(boolean isFilterOn) {
getPrefs().setValue(FILTER_COMPLETE_MODE, isFilterOn);
}
public boolean isFilterCompleteMode() {
if (getPrefs().contains(FILTER_COMPLETE_MODE)) {
return getPrefs().getBoolean(FILTER_COMPLETE_MODE);
} else {
return false;
}
}
public void setFilterInCompleteMode(boolean isFilterOn) {
getPrefs().setValue(FILTER_INCOMPLETE_MODE, isFilterOn);
}
public boolean isFilterInCompleteMode() {
if (getPrefs().contains(FILTER_INCOMPLETE_MODE)) {
return getPrefs().getBoolean(FILTER_INCOMPLETE_MODE);
} else {
return false;
}
}
/**
* TODO: remove
*/
public ReportOpenMode getReportMode() {
return ReportOpenMode.EDITOR;
// if (getPrefs().getBoolean(REPORT_OPEN_EDITOR)) {
// return ReportOpenMode.EDITOR;
// } else if (getPrefs().getBoolean(REPORT_OPEN_INTERNAL)) {
// return ReportOpenMode.INTERNAL_BROWSER;
// } else {
// return ReportOpenMode.EXTERNAL_BROWSER;
// }
}
public TaskListExternalizer getTaskListExternalizer() {
return externalizer;
}
public List<ITaskHandler> getTaskHandlers() {
return taskHandlers;
}
public ITaskHandler getTaskHandlerForElement(ITaskListElement element) {
for (ITaskHandler taskHandler : taskHandlers) {
if (taskHandler.acceptsItem(element))
return taskHandler;
}
return null;
}
public void addTaskHandler(ITaskHandler taskHandler) {
taskHandlers.add(taskHandler);
}
public void restoreTaskHandlerState() {
for (ITaskHandler handler : taskHandlers) {
handler.restoreState(TaskListView.getDefault());
}
}
private List<IDynamicSubMenuContributor> menuContributors = new ArrayList<IDynamicSubMenuContributor>();
public List<IDynamicSubMenuContributor> getDynamicMenuContributers() {
return menuContributors;
}
public void addDynamicPopupContributor(IDynamicSubMenuContributor contributor) {
menuContributors.add(contributor);
}
private List<ITaskActivationListener> taskListListeners = new ArrayList<ITaskActivationListener>();
public List<ITaskActivationListener> getTaskListListeners() {
return taskListListeners;
}
public void addTaskListListener(ITaskActivationListener taskListListner) {
taskListListeners.add(taskListListner);
}
public void createTaskListBackupFile() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
File taskListFile = new File(path);
String backup = path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
copy(taskListFile, new File(backup));
}
public String getBackupFilePath() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
return path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
}
public void reverseBackup() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
File taskListFile = new File(path);
String backup = path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
copy(new File(backup), taskListFile);
}
/**
* Copies all files in the current data directory to
* the specified folder. Will overwrite.
*/
public void copyDataDirContentsTo(String targetFolderPath) {
File mainDataDir = new File(MylarPlugin.getDefault().getMylarDataDirectory());
for (File currFile : mainDataDir.listFiles()) {
if (currFile.isFile()) {
File destFile = new File(targetFolderPath + File.separator + currFile.getName());
copy(currFile, destFile);
}
}
}
private boolean copy(File src, File dst) {
try {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (IOException ioe) {
return false;
}
}
public boolean isMultipleMode() {
return getPrefs().getBoolean(MULTIPLE_ACTIVE_TASKS);
}
public String[] getSaveOptions() {
String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() };
return options;
}
public ITaskHighlighter getHighlighter() {
return highlighter;
}
public void setHighlighter(ITaskHighlighter highlighter) {
this.highlighter = highlighter;
}
public List<IContextEditorFactory> getContextEditors() {
return contextEditors;
}
public void addContextEditor(IContextEditorFactory contextEditor) {
if (contextEditor != null)
this.contextEditors.add(contextEditor);
}
/**
* Called periodically by the save timer
*/
public void saveRequested() {
if (shouldAutoSave) {
try {
saveTaskListAndContexts();
MylarPlugin.log("Automatically saved task list", this);
} catch (Exception e) {
MylarPlugin.fail(e, "Could not auto save task list", true);
}
}
}
/** For testing only **/
public SaveTimer getSaveTimer() {
return saveTimer;
}
/**
* For testing.
*/
public void setShouldAutoSave(boolean shellActive) {
MylarTasklistPlugin.shouldAutoSave = shellActive;
}
}
| private void checkTaskListBackup() {
// if (getPrefs().contains(PREVIOUS_SAVE_DATE)) {
// lastSave = new Date(getPrefs().getLong(PREVIOUS_SAVE_DATE));
// } else {
// lastSave = new Date();
// getPrefs().setValue(PREVIOUS_SAVE_DATE, lastSave.getTime());
// }
Date currentTime = new Date();
if (currentTime.getTime() > lastBackup.getTime() + AUTOMATIC_BACKUP_SAVE_INTERVAL) {//TaskListSaveMode.fromStringToLong(getPrefs().getString(SAVE_TASKLIST_MODE))) {
MylarTasklistPlugin.getDefault().createTaskListBackupFile();
lastBackup = new Date();
// INSTANCE.getPreferenceStore().setValue(PREVIOUS_SAVE_DATE, lastSave.getTime());
}
}
private void checkReminders() {
// if (getPrefs().getBoolean(REMINDER_CHECK)) {
// getPrefs().setValue(REMINDER_CHECK, false);
final TaskReportGenerator parser = new TaskReportGenerator(MylarTasklistPlugin.getTaskListManager().getTaskList());
parser.addCollector(new ReminderRequiredCollector());
parser.collectTasks();
if (!parser.getAllCollectedTasks().isEmpty()) {
Workbench.getInstance().getDisplay().asyncExec(new Runnable() {
public void run() {
TasksReminderDialog dialog = new TasksReminderDialog(Workbench.getInstance().getDisplay().getActiveShell(), parser.getAllCollectedTasks());
dialog.setBlockOnOpen(false);
dialog.open();
}
});
}
// }
}
public static void setPriorityLevel(PriorityLevel pl) {
getPrefs().setValue(SELECTED_PRIORITY, pl.toString());
}
public static String getPriorityLevel() {
if (getPrefs().contains(SELECTED_PRIORITY)) {
return getPrefs().getString(SELECTED_PRIORITY);
} else {
return PriorityLevel.P5.toString();
}
}
public void setFilterCompleteMode(boolean isFilterOn) {
getPrefs().setValue(FILTER_COMPLETE_MODE, isFilterOn);
}
public boolean isFilterCompleteMode() {
if (getPrefs().contains(FILTER_COMPLETE_MODE)) {
return getPrefs().getBoolean(FILTER_COMPLETE_MODE);
} else {
return false;
}
}
public void setFilterInCompleteMode(boolean isFilterOn) {
getPrefs().setValue(FILTER_INCOMPLETE_MODE, isFilterOn);
}
public boolean isFilterInCompleteMode() {
if (getPrefs().contains(FILTER_INCOMPLETE_MODE)) {
return getPrefs().getBoolean(FILTER_INCOMPLETE_MODE);
} else {
return false;
}
}
/**
* TODO: remove
*/
public ReportOpenMode getReportMode() {
return ReportOpenMode.EDITOR;
// if (getPrefs().getBoolean(REPORT_OPEN_EDITOR)) {
// return ReportOpenMode.EDITOR;
// } else if (getPrefs().getBoolean(REPORT_OPEN_INTERNAL)) {
// return ReportOpenMode.INTERNAL_BROWSER;
// } else {
// return ReportOpenMode.EXTERNAL_BROWSER;
// }
}
public TaskListExternalizer getTaskListExternalizer() {
return externalizer;
}
public List<ITaskHandler> getTaskHandlers() {
return taskHandlers;
}
public ITaskHandler getTaskHandlerForElement(ITaskListElement element) {
for (ITaskHandler taskHandler : taskHandlers) {
if (taskHandler.acceptsItem(element))
return taskHandler;
}
return null;
}
public void addTaskHandler(ITaskHandler taskHandler) {
taskHandlers.add(taskHandler);
}
public void restoreTaskHandlerState() {
for (ITaskHandler handler : taskHandlers) {
handler.restoreState(TaskListView.getDefault());
}
}
private List<IDynamicSubMenuContributor> menuContributors = new ArrayList<IDynamicSubMenuContributor>();
public List<IDynamicSubMenuContributor> getDynamicMenuContributers() {
return menuContributors;
}
public void addDynamicPopupContributor(IDynamicSubMenuContributor contributor) {
menuContributors.add(contributor);
}
private List<ITaskActivationListener> taskListListeners = new ArrayList<ITaskActivationListener>();
public List<ITaskActivationListener> getTaskListListeners() {
return taskListListeners;
}
public void addTaskListListener(ITaskActivationListener taskListListner) {
taskListListeners.add(taskListListner);
}
public void createTaskListBackupFile() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
File taskListFile = new File(path);
String backup = path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
copy(taskListFile, new File(backup));
}
public String getBackupFilePath() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
return path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
}
public void reverseBackup() {
String path = MylarPlugin.getDefault().getMylarDataDirectory() + File.separator + DEFAULT_TASK_LIST_FILE;
File taskListFile = new File(path);
String backup = path.substring(0, path.lastIndexOf('.')) + "-backup.xml";
copy(new File(backup), taskListFile);
}
/**
* Copies all files in the current data directory to
* the specified folder. Will overwrite.
*/
public void copyDataDirContentsTo(String targetFolderPath) {
File mainDataDir = new File(MylarPlugin.getDefault().getMylarDataDirectory());
for (File currFile : mainDataDir.listFiles()) {
if (currFile.isFile()) {
File destFile = new File(targetFolderPath + File.separator + currFile.getName());
copy(currFile, destFile);
}
}
}
private boolean copy(File src, File dst) {
try {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (IOException ioe) {
return false;
}
}
public boolean isMultipleMode() {
return getPrefs().getBoolean(MULTIPLE_ACTIVE_TASKS);
}
public String[] getSaveOptions() {
String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(), TaskListSaveMode.DAY.toString() };
return options;
}
public ITaskHighlighter getHighlighter() {
return highlighter;
}
public void setHighlighter(ITaskHighlighter highlighter) {
this.highlighter = highlighter;
}
public List<IContextEditorFactory> getContextEditors() {
return contextEditors;
}
public void addContextEditor(IContextEditorFactory contextEditor) {
if (contextEditor != null)
this.contextEditors.add(contextEditor);
}
/**
* Called periodically by the save timer
*/
public void saveRequested() {
if (shouldAutoSave) {
try {
saveTaskListAndContexts();
// MylarPlugin.log("Automatically saved task list", this);
} catch (Exception e) {
MylarPlugin.fail(e, "Could not auto save task list", false);
}
}
}
/** For testing only **/
public SaveTimer getSaveTimer() {
return saveTimer;
}
/**
* For testing.
*/
public void setShouldAutoSave(boolean shellActive) {
MylarTasklistPlugin.shouldAutoSave = shellActive;
}
}
|
diff --git a/sandbox/myrestaurants/src/test/java/com/springone/myrestaurants/domain/TopRatedRestaurantFinderTest.java b/sandbox/myrestaurants/src/test/java/com/springone/myrestaurants/domain/TopRatedRestaurantFinderTest.java
index e29b393..1dea00f 100644
--- a/sandbox/myrestaurants/src/test/java/com/springone/myrestaurants/domain/TopRatedRestaurantFinderTest.java
+++ b/sandbox/myrestaurants/src/test/java/com/springone/myrestaurants/domain/TopRatedRestaurantFinderTest.java
@@ -1,111 +1,111 @@
package com.springone.myrestaurants.domain;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.neo4j.graphdb.Node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.datastore.graph.neo4j.spi.node.Neo4jHelper;
import org.springframework.datastore.graph.neo4j.support.GraphDatabaseContext;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
/**
* @author Michael Hunger
* @since 02.10.2010
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@DirtiesContext
@Transactional
public class TopRatedRestaurantFinderTest {
@Autowired
private GraphDatabaseContext graphDatabaseContext;
@PersistenceContext
EntityManager em;
@Autowired
DataSource dataSource;
@Autowired
PlatformTransactionManager transactionManager;
@Before
@BeforeTransaction
public void cleanDb() {
Neo4jHelper.cleanDb(graphDatabaseContext);
}
@Test
public void returnsFriendsInOrder() {
final Restaurant a = restaurant("a");
final Restaurant b = restaurant("b");
final Restaurant c = restaurant("c");
final UserAccount A = user("A");
final UserAccount B1 = user("B1");
final UserAccount B2 = user("B2");
final UserAccount C1 = user("C1");
Assert.assertNotNull("user has node", node(A));
A.knows(B1);
A.knows(B2);
B1.knows(C1);
C1.rate(a, 1, "");
- C1.rate(b, 3, "");
- C1.rate(c, 5, "");
+ C1.rate(b, 5, "");
+ C1.rate(c, 3, "");
final Node node = node(A);
final Collection<RatedRestaurant> topNRatedRestaurants = new TopRatedRestaurantFinder().getTopNRatedRestaurants(A, 5);
Collection<Restaurant> result = new ArrayList<Restaurant>();
for (RatedRestaurant ratedRestaurant : topNRatedRestaurants) {
result.add(ratedRestaurant.getRestaurant());
}
final Restaurant b2 = em.find(Restaurant.class, 2L);
Assert.assertNotNull(b2);
- Assert.assertEquals(asList(b, c, a), result);
+ Assert.assertEquals(asList(b,c, a), result);
}
private Node node(UserAccount a) {
return a.getUnderlyingState();
}
private UserAccount user(String name) {
UserAccount userAccount = new UserAccount();
//userAccount.setId((long) name.hashCode());
em.persist(userAccount);
em.flush();
userAccount.getId();
userAccount.setNickname(name);
return userAccount;
}
private Restaurant restaurant(String name) {
Restaurant restaurant = new Restaurant();
restaurant.setName(name);
//restaurant.setId((long) name.hashCode());
em.persist(restaurant);
em.flush();
restaurant.getId();
return restaurant;
}
private void dumpResults(String sql) {
final List<Map<String, Object>> result = new SimpleJdbcTemplate(dataSource).queryForList(sql);
System.out.println("result = " + result);
}
}
| false | true | public void returnsFriendsInOrder() {
final Restaurant a = restaurant("a");
final Restaurant b = restaurant("b");
final Restaurant c = restaurant("c");
final UserAccount A = user("A");
final UserAccount B1 = user("B1");
final UserAccount B2 = user("B2");
final UserAccount C1 = user("C1");
Assert.assertNotNull("user has node", node(A));
A.knows(B1);
A.knows(B2);
B1.knows(C1);
C1.rate(a, 1, "");
C1.rate(b, 3, "");
C1.rate(c, 5, "");
final Node node = node(A);
final Collection<RatedRestaurant> topNRatedRestaurants = new TopRatedRestaurantFinder().getTopNRatedRestaurants(A, 5);
Collection<Restaurant> result = new ArrayList<Restaurant>();
for (RatedRestaurant ratedRestaurant : topNRatedRestaurants) {
result.add(ratedRestaurant.getRestaurant());
}
final Restaurant b2 = em.find(Restaurant.class, 2L);
Assert.assertNotNull(b2);
Assert.assertEquals(asList(b, c, a), result);
}
| public void returnsFriendsInOrder() {
final Restaurant a = restaurant("a");
final Restaurant b = restaurant("b");
final Restaurant c = restaurant("c");
final UserAccount A = user("A");
final UserAccount B1 = user("B1");
final UserAccount B2 = user("B2");
final UserAccount C1 = user("C1");
Assert.assertNotNull("user has node", node(A));
A.knows(B1);
A.knows(B2);
B1.knows(C1);
C1.rate(a, 1, "");
C1.rate(b, 5, "");
C1.rate(c, 3, "");
final Node node = node(A);
final Collection<RatedRestaurant> topNRatedRestaurants = new TopRatedRestaurantFinder().getTopNRatedRestaurants(A, 5);
Collection<Restaurant> result = new ArrayList<Restaurant>();
for (RatedRestaurant ratedRestaurant : topNRatedRestaurants) {
result.add(ratedRestaurant.getRestaurant());
}
final Restaurant b2 = em.find(Restaurant.class, 2L);
Assert.assertNotNull(b2);
Assert.assertEquals(asList(b,c, a), result);
}
|
diff --git a/rxjava-core/src/main/java/rx/concurrency/SleepingAction.java b/rxjava-core/src/main/java/rx/concurrency/SleepingAction.java
index db7ece246..62d3f399f 100644
--- a/rxjava-core/src/main/java/rx/concurrency/SleepingAction.java
+++ b/rxjava-core/src/main/java/rx/concurrency/SleepingAction.java
@@ -1,48 +1,52 @@
/**
* Copyright 2013 Netflix, 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 rx.concurrency;
import java.util.concurrent.TimeUnit;
import rx.Scheduler;
import rx.Subscription;
import rx.util.functions.Func2;
/* package */class SleepingAction<T> implements Func2<Scheduler, T, Subscription> {
private final Func2<Scheduler, T, Subscription> underlying;
private final Scheduler scheduler;
private final long execTime;
public SleepingAction(Func2<Scheduler, T, Subscription> underlying, Scheduler scheduler, long timespan, TimeUnit timeUnit) {
this.underlying = underlying;
this.scheduler = scheduler;
this.execTime = scheduler.now() + timeUnit.toMillis(timespan);
}
@Override
public Subscription call(Scheduler s, T state) {
- if (execTime < scheduler.now()) {
+ if (execTime > scheduler.now()) {
+ long delay = execTime - scheduler.now();
+ if (delay> 0) {
try {
- Thread.sleep(scheduler.now() - execTime);
- } catch (InterruptedException e) {
+ Thread.sleep(delay);
+ }
+ catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
+ }
}
return underlying.call(s, state);
}
}
| false | true | public Subscription call(Scheduler s, T state) {
if (execTime < scheduler.now()) {
try {
Thread.sleep(scheduler.now() - execTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
return underlying.call(s, state);
}
| public Subscription call(Scheduler s, T state) {
if (execTime > scheduler.now()) {
long delay = execTime - scheduler.now();
if (delay> 0) {
try {
Thread.sleep(delay);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
return underlying.call(s, state);
}
|
diff --git a/src/main/java/HashMap.java b/src/main/java/HashMap.java
index ce70271..3b3e989 100644
--- a/src/main/java/HashMap.java
+++ b/src/main/java/HashMap.java
@@ -1,90 +1,91 @@
public class HashMap {
private int size = 0;
private Entry[] entries;
public HashMap() {
this(30);
}
public HashMap(int length) {
entries = new Entry[length];
}
public String get(Hashable key) {
return entries[collisionResolvedIndexFor(key)].value;
}
public void put(Hashable key, String value) {
int index = collisionResolvedIndexFor(key);
if (entryExistsAt(index)) {
updateValueAt(index, value);
+ } else {
+ addEntryAt(index, createEntryFor(key, value));
}
- addEntryAt(index, createEntryFor(key, value));
}
int collisionResolvedIndexFor(Hashable key) {
int index = indexFor(key);
while (entryExistsAtIndexWithDifferent(key, index)) {
index = nextIndexAfterCollisionAt(index);
}
return index;
}
private void addEntryAt(int index, Entry entry) {
entries[index] = entry;
size++;
resizeEntriesIfRequired();
}
private void resizeEntriesIfRequired() {
if (size >= entries.length) {
resize();
}
}
private void resize() {
Entry[] replacement = new Entry[entries.length * 2];
for (Entry entry : entries) {
replacement[collisionResolvedIndexFor(entry.key)] = entry;
}
entries = replacement;
}
private boolean entryExistsAtIndexWithDifferent(Hashable key, int index) {
return entryExistsAt(index) && !keyAt(index).equals(key);
}
private void updateValueAt(int index, String value) {
entries[index].value = value;
}
private int nextIndexAfterCollisionAt(int index) {
return (index + 1) % entries.length;
}
int indexFor(Hashable key) {
return key.hash() % entries.length;
}
private Hashable keyAt(int index) {
return entries[index].key;
}
private boolean entryExistsAt(int index) {
return entries[index] != null;
}
private Entry createEntryFor(Hashable key, String value) {
return new Entry(key, value);
}
private class Entry {
private Hashable key;
private String value;
public Entry(Hashable key, String value) {
this.key = key;
this.value = value;
}
}
}
| false | true | public void put(Hashable key, String value) {
int index = collisionResolvedIndexFor(key);
if (entryExistsAt(index)) {
updateValueAt(index, value);
}
addEntryAt(index, createEntryFor(key, value));
}
| public void put(Hashable key, String value) {
int index = collisionResolvedIndexFor(key);
if (entryExistsAt(index)) {
updateValueAt(index, value);
} else {
addEntryAt(index, createEntryFor(key, value));
}
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java
index fd3f8c1f8..86eb3fe3e 100644
--- a/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java
+++ b/astrid/plugin-src/com/todoroo/astrid/gcal/CalendarAlarmScheduler.java
@@ -1,81 +1,82 @@
package com.todoroo.astrid.gcal;
import java.util.Date;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import com.timsu.astrid.R;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.utility.Constants;
@SuppressWarnings("nls")
public class CalendarAlarmScheduler {
public static final String TAG = "calendar-alarm";
public static final String URI_PREFIX = "cal-reminder";
public static final String URI_PREFIX_POSTPONE = "cal-postpone";
public static void scheduleAllCalendarAlarms(Context context) {
if (!Preferences.getBoolean(R.string.p_calendar_reminders, true))
return;
ContentResolver cr = context.getContentResolver();
long now = DateUtilities.now();
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Cursor events = cr.query(Calendars.getCalendarContentUri(Calendars.CALENDAR_CONTENT_EVENTS),
new String[] { Calendars.ID_COLUMN_NAME, Calendars.EVENTS_DTSTART_COL },
Calendars.EVENTS_DTSTART_COL + " > ? AND " + Calendars.EVENTS_DTSTART_COL + " < ?",
new String[] { Long.toString(now + DateUtilities.ONE_MINUTE * 15), Long.toString(now + DateUtilities.ONE_DAY) },
null);
try {
- if (events.getCount() > 0) {
+ if (events != null && events.getCount() > 0) {
int idIndex = events.getColumnIndex(Calendars.ID_COLUMN_NAME);
int dtstartIndex = events.getColumnIndexOrThrow(Calendars.EVENTS_DTSTART_COL);
for (events.moveToFirst(); !events.isAfterLast(); events.moveToNext()) {
Intent eventAlarm = new Intent(context, CalendarAlarmReceiver.class);
eventAlarm.setAction(CalendarAlarmReceiver.BROADCAST_CALENDAR_REMINDER);
long start = events.getLong(dtstartIndex);
long id = events.getLong(idIndex);
eventAlarm.setData(Uri.parse(URI_PREFIX + "://" + id));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
CalendarAlarmReceiver.REQUEST_CODE_CAL_REMINDER, eventAlarm, 0);
am.cancel(pendingIntent);
long alarmTime = start - DateUtilities.ONE_MINUTE * 15;
am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
if (Constants.DEBUG)
Log.w(TAG, "Scheduling calendar alarm for " + new Date(alarmTime));
}
}
// Schedule alarm to recheck and reschedule calendar alarms in 12 hours
Intent rescheduleAlarm = new Intent(CalendarStartupReceiver.BROADCAST_RESCHEDULE_CAL_ALARMS);
PendingIntent pendingReschedule = PendingIntent.getBroadcast(context, 0,
rescheduleAlarm, 0);
am.cancel(pendingReschedule);
am.set(AlarmManager.RTC, DateUtilities.now() + DateUtilities.ONE_HOUR * 12, pendingReschedule);
} finally {
- events.close();
+ if (events != null)
+ events.close();
}
}
}
| false | true | public static void scheduleAllCalendarAlarms(Context context) {
if (!Preferences.getBoolean(R.string.p_calendar_reminders, true))
return;
ContentResolver cr = context.getContentResolver();
long now = DateUtilities.now();
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Cursor events = cr.query(Calendars.getCalendarContentUri(Calendars.CALENDAR_CONTENT_EVENTS),
new String[] { Calendars.ID_COLUMN_NAME, Calendars.EVENTS_DTSTART_COL },
Calendars.EVENTS_DTSTART_COL + " > ? AND " + Calendars.EVENTS_DTSTART_COL + " < ?",
new String[] { Long.toString(now + DateUtilities.ONE_MINUTE * 15), Long.toString(now + DateUtilities.ONE_DAY) },
null);
try {
if (events.getCount() > 0) {
int idIndex = events.getColumnIndex(Calendars.ID_COLUMN_NAME);
int dtstartIndex = events.getColumnIndexOrThrow(Calendars.EVENTS_DTSTART_COL);
for (events.moveToFirst(); !events.isAfterLast(); events.moveToNext()) {
Intent eventAlarm = new Intent(context, CalendarAlarmReceiver.class);
eventAlarm.setAction(CalendarAlarmReceiver.BROADCAST_CALENDAR_REMINDER);
long start = events.getLong(dtstartIndex);
long id = events.getLong(idIndex);
eventAlarm.setData(Uri.parse(URI_PREFIX + "://" + id));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
CalendarAlarmReceiver.REQUEST_CODE_CAL_REMINDER, eventAlarm, 0);
am.cancel(pendingIntent);
long alarmTime = start - DateUtilities.ONE_MINUTE * 15;
am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
if (Constants.DEBUG)
Log.w(TAG, "Scheduling calendar alarm for " + new Date(alarmTime));
}
}
// Schedule alarm to recheck and reschedule calendar alarms in 12 hours
Intent rescheduleAlarm = new Intent(CalendarStartupReceiver.BROADCAST_RESCHEDULE_CAL_ALARMS);
PendingIntent pendingReschedule = PendingIntent.getBroadcast(context, 0,
rescheduleAlarm, 0);
am.cancel(pendingReschedule);
am.set(AlarmManager.RTC, DateUtilities.now() + DateUtilities.ONE_HOUR * 12, pendingReschedule);
} finally {
events.close();
}
}
| public static void scheduleAllCalendarAlarms(Context context) {
if (!Preferences.getBoolean(R.string.p_calendar_reminders, true))
return;
ContentResolver cr = context.getContentResolver();
long now = DateUtilities.now();
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Cursor events = cr.query(Calendars.getCalendarContentUri(Calendars.CALENDAR_CONTENT_EVENTS),
new String[] { Calendars.ID_COLUMN_NAME, Calendars.EVENTS_DTSTART_COL },
Calendars.EVENTS_DTSTART_COL + " > ? AND " + Calendars.EVENTS_DTSTART_COL + " < ?",
new String[] { Long.toString(now + DateUtilities.ONE_MINUTE * 15), Long.toString(now + DateUtilities.ONE_DAY) },
null);
try {
if (events != null && events.getCount() > 0) {
int idIndex = events.getColumnIndex(Calendars.ID_COLUMN_NAME);
int dtstartIndex = events.getColumnIndexOrThrow(Calendars.EVENTS_DTSTART_COL);
for (events.moveToFirst(); !events.isAfterLast(); events.moveToNext()) {
Intent eventAlarm = new Intent(context, CalendarAlarmReceiver.class);
eventAlarm.setAction(CalendarAlarmReceiver.BROADCAST_CALENDAR_REMINDER);
long start = events.getLong(dtstartIndex);
long id = events.getLong(idIndex);
eventAlarm.setData(Uri.parse(URI_PREFIX + "://" + id));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
CalendarAlarmReceiver.REQUEST_CODE_CAL_REMINDER, eventAlarm, 0);
am.cancel(pendingIntent);
long alarmTime = start - DateUtilities.ONE_MINUTE * 15;
am.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
if (Constants.DEBUG)
Log.w(TAG, "Scheduling calendar alarm for " + new Date(alarmTime));
}
}
// Schedule alarm to recheck and reschedule calendar alarms in 12 hours
Intent rescheduleAlarm = new Intent(CalendarStartupReceiver.BROADCAST_RESCHEDULE_CAL_ALARMS);
PendingIntent pendingReschedule = PendingIntent.getBroadcast(context, 0,
rescheduleAlarm, 0);
am.cancel(pendingReschedule);
am.set(AlarmManager.RTC, DateUtilities.now() + DateUtilities.ONE_HOUR * 12, pendingReschedule);
} finally {
if (events != null)
events.close();
}
}
|
diff --git a/src/org/eclipse/core/tests/internal/localstore/MoveTest.java b/src/org/eclipse/core/tests/internal/localstore/MoveTest.java
index cf5429b..db82db2 100644
--- a/src/org/eclipse/core/tests/internal/localstore/MoveTest.java
+++ b/src/org/eclipse/core/tests/internal/localstore/MoveTest.java
@@ -1,704 +1,705 @@
package org.eclipse.core.tests.internal.localstore;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.internal.resources.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
/**
* Tests the move operation.
*/
public class MoveTest extends LocalStoreTest {
public MoveTest() {
super();
}
public MoveTest(String name) {
super(name);
}
public String[] defineHierarchy() {
return new String[] {
"/",
"/file1",
"/file2",
"/folder1/",
"/folder1/file3",
"/folder1/file4",
"/folder2/",
"/folder2/file5",
"/folder2/file6",
"/folder1/folder3/",
"/folder1/folder3/file7",
"/folder1/folder3/file8" };
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(new MoveTest("testRenameProjects"));
suite.addTest(new MoveTest("testRenameFolder"));
suite.addTest(new MoveTest("testRenameFile"));
suite.addTest(new MoveTest("testMoveFolderBetweenProjects"));
suite.addTest(new MoveTest("testMoveFileBetweenProjects"));
suite.addTest(new MoveTest("testMoveFolderAcrossVolumes"));
suite.addTest(new MoveTest("testMoveFileAcrossVolumes"));
suite.addTest(new MoveTest("testMoveHierarchy"));
suite.addTest(new MoveTest("testMoveHierarchyBetweenProjects"));
suite.addTest(new MoveTest("testMoveResource"));
return suite;
}
/**
* This test has Windows as the target OS. Drives C: and D: should be available.
*/
public void testMoveFileAcrossVolumes() {
/* test if we are in the adequate environment */
if (!new java.io.File("c:\\").exists() || !new java.io.File("d:\\").exists())
return;
// create common objects
IProject source = getWorkspace().getRoot().getProject("SourceProject");
IProject destination = getWorkspace().getRoot().getProject("DestinationProject");
try {
source.create(getMonitor());
source.open(getMonitor());
IProjectDescription description = getWorkspace().newProjectDescription("DestinationProject");
description.setLocation(new Path("d:/temp/destination"));
destination.create(description, getMonitor());
destination.open(getMonitor());
} catch (CoreException e) {
fail("0.0", e);
}
String fileName = "fileToBeMoved.txt";
IFile file = source.getFile(fileName);
try {
file.create(getRandomContents(), true, getMonitor());
} catch (CoreException e) {
fail("1.0", e);
}
// add some properties to file (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
try {
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
file.setPersistentProperty(propNames[j], propValues[j]);
file.setSessionProperty(propNames[j], propValues[j]);
}
} catch (CoreException e) {
fail("2.0", e);
}
// move file
IPath dest = destination.getFile(fileName).getFullPath();
try {
file.move(dest, true, getMonitor());
} catch (CoreException e) {
fail("3.0", e);
}
// assert file was moved
IFile newFile = destination.getFile(fileName);
assertDoesNotExistInWorkspace("4.1", file);
assertDoesNotExistInFileSystem("4.2", file);
assertExistsInWorkspace("4.3", newFile);
assertExistsInFileSystem("4.4", newFile);
// assert properties still exist (server, local and session)
try {
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFile.getPersistentProperty(propNames[j]);
Object sessionValue = newFile.getSessionProperty(propNames[j]);
assertEquals("5.1", persistentValue, propValues[j]);
assertEquals("5.2", sessionValue, propValues[j]);
}
} catch (CoreException e) {
fail("5.3", e);
}
// remove garbage
try {
source.delete(true, true, getMonitor());
destination.delete(true, true, getMonitor());
} catch (CoreException e) {
fail("20.0", e);
}
}
/**
* Move one file from one project to another.
*/
public void testMoveFileBetweenProjects() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// get file instance
String fileName = "newFile.txt";
IFile file = projects[0].getFile(fileName);
ensureExistsInWorkspace(file, true);
// add some properties to file (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
file.setPersistentProperty(propNames[j], propValues[j]);
file.setSessionProperty(propNames[j], propValues[j]);
}
// move file
IPath destination = projects[1].getFile(fileName).getFullPath();
file.move(destination, true, null);
// get new file instance
IFile newFile = projects[1].getFile(fileName);
// assert file was renamed
assertDoesNotExistInWorkspace(file);
assertDoesNotExistInFileSystem(file);
assertExistsInWorkspace(newFile);
assertExistsInFileSystem(newFile);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFile.getPersistentProperty(propNames[j]);
Object sessionValue = newFile.getSessionProperty(propNames[j]);
assertTrue("persistent property value is not the same", propValues[j].equals(persistentValue));
assertTrue("session property value is not the same", propValues[j].equals(sessionValue));
}
}
/**
* This test has Windows as the target OS. Drives C: and D: should be available.
*/
public void testMoveFolderAcrossVolumes() {
/* test if we are in the adequate environment */
if (!new java.io.File("c:\\").exists() || !new java.io.File("d:\\").exists())
return;
// create common objects
IProject source = getWorkspace().getRoot().getProject("SourceProject");
IProject destination = getWorkspace().getRoot().getProject("DestinationProject");
try {
source.create(getMonitor());
source.open(getMonitor());
IProjectDescription description = getWorkspace().newProjectDescription("DestinationProject");
description.setLocation(new Path("d:/temp/destination"));
destination.create(description, getMonitor());
destination.open(getMonitor());
} catch (CoreException e) {
fail("0.0", e);
}
// get folder instance
String folderName = "folderToBeMoved";
IFolder folder = source.getFolder(folderName);
try {
folder.create(true, true, getMonitor());
} catch (CoreException e) {
fail("1.0", e);
}
// add some properties to file (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
try {
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
folder.setPersistentProperty(propNames[j], propValues[j]);
folder.setSessionProperty(propNames[j], propValues[j]);
}
} catch (CoreException e) {
fail("2.0", e);
}
// rename folder
IPath dest = destination.getFile(folderName).getFullPath();
try {
folder.move(dest, true, getMonitor());
} catch (CoreException e) {
fail("3.0", e);
}
// assert folder was renamed
IFolder newFolder = destination.getFolder(folderName);
assertDoesNotExistInWorkspace("4.1", folder);
assertDoesNotExistInFileSystem("4.2", folder);
assertExistsInWorkspace("4.3", newFolder);
assertExistsInFileSystem("4.4", newFolder);
// assert properties still exist (server, local and session)
try {
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFolder.getPersistentProperty(propNames[j]);
Object sessionValue = newFolder.getSessionProperty(propNames[j]);
assertEquals("5.1", persistentValue, propValues[j]);
assertEquals("5.2", sessionValue, propValues[j]);
}
} catch (CoreException e) {
fail("5.3", e);
}
// remove garbage
try {
source.delete(true, true, getMonitor());
destination.delete(true, true, getMonitor());
} catch (CoreException e) {
fail("20.0", e);
}
}
/**
* Move one folder from one project to another.
*/
public void testMoveFolderBetweenProjects() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// get folder instance
String folderName = "newFolder";
IFolder folder = projects[0].getFolder(folderName);
ensureExistsInWorkspace(folder, true);
// add some properties to folder (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
folder.setPersistentProperty(propNames[j], propValues[j]);
folder.setSessionProperty(propNames[j], propValues[j]);
}
// rename folder
IPath destination = projects[1].getFolder(folderName).getFullPath();
folder.move(destination, true, null);
// get new folder instance
IFolder newFolder = projects[1].getFolder(folderName);
// assert folder was renamed
assertDoesNotExistInWorkspace(folder);
assertDoesNotExistInFileSystem(folder);
assertExistsInWorkspace(newFolder);
assertExistsInFileSystem(newFolder);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFolder.getPersistentProperty(propNames[j]);
Object sessionValue = newFolder.getSessionProperty(propNames[j]);
assertTrue("persistent property value is not the same", propValues[j].equals(persistentValue));
assertTrue("session property value is not the same", propValues[j].equals(sessionValue));
}
}
/**
* Move some hierarchy of folders and files.
*/
public void testMoveHierarchy() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// create the source folder
String folderSourceName = "folder source";
IFolder folderSource = projects[0].getFolder(folderSourceName);
ensureExistsInWorkspace(folderSource, true);
// create hierarchy
String[] hierarchy = defineHierarchy();
IResource[] resources = buildResources(folderSource, hierarchy);
ensureExistsInWorkspace(resources, true);
// add some properties to each resource (persistent and session)
String[] propNames = new String[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = "prop" + j;
propValues[j] = "value" + j;
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
QualifiedName propName = new QualifiedName("test", resource.getName() + propNames[j]);
String propValue = resource.getName() + propValues[j];
resource.setPersistentProperty(propName, propValue);
resource.setSessionProperty(propName, propValue);
}
}
// create the destination folder
String folderDestinationName = "folder destination";
IFolder folderDestination = projects[0].getFolder(folderDestinationName);
// move hierarchy
//IProgressMonitor monitor = new LoggingProgressMonitor(System.out);
IProgressMonitor monitor = getMonitor();
folderSource.move(folderDestination.getFullPath(), true, monitor);
// get new hierarchy instance
IResource[] newResources = buildResources(folderDestination, hierarchy);
// assert hierarchy was moved
assertDoesNotExistInWorkspace(resources);
assertDoesNotExistInFileSystem(resources);
assertExistsInWorkspace(newResources);
assertExistsInFileSystem(newResources);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
for (int i = 0; i < newResources.length; i++) {
IResource destResource = newResources[i];
IResource sourceResource = resources[i];
/* The names of the properties will remain the same in both the source and
destination hierarchies. So, be sure to use sourceResource to get the
name or your qualified name will contain 'folder destination' instead of
'folder source' and the property value will be null.
*/
QualifiedName propName = new QualifiedName("test", sourceResource.getName() + propNames[j]);
String propValue = sourceResource.getName() + propValues[j];
String persistentValue = destResource.getPersistentProperty(propName);
Object sessionValue = destResource.getSessionProperty(propName);
assertTrue("persistent property value is not the same", propValue.equals(persistentValue));
assertTrue("session property value is not the same", propValue.equals(sessionValue));
}
}
}
/**
* Move some hierarchy of folders and files between projects. It also test moving a
* hierarchy across volumes.
*/
public void testMoveHierarchyBetweenProjects() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// create the source folder
String folderSourceName = "source";
IFolder folderSource = projects[0].getFolder(folderSourceName);
ensureExistsInWorkspace(folderSource, true);
// build hierarchy
String[] hierarchy = defineHierarchy();
IResource[] resources = buildResources(folderSource, hierarchy);
ensureExistsInWorkspace(resources, true);
// add some properties to each resource
String[] propNames = new String[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = "prop" + j;
propValues[j] = "value" + j;
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
QualifiedName propName = new QualifiedName("test", resource.getName() + propNames[j]);
String propValue = resource.getName() + propValues[j];
resource.setPersistentProperty(propName, propValue);
resource.setSessionProperty(propName, propValue);
}
}
// create the destination folder
String folderDestinationName = "destination";
IFolder folderDestination = projects[1].getFolder(folderDestinationName);
// move hierarchy
folderSource.move(folderDestination.getFullPath(), true, null);
// get new hierarchy instance
IResource[] newResources = buildResources(folderDestination, hierarchy);
// assert hierarchy was moved
assertDoesNotExistInWorkspace(resources);
assertDoesNotExistInFileSystem(resources);
assertExistsInWorkspace(newResources);
assertExistsInFileSystem(newResources);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
for (int i = 0; i < newResources.length; i++) {
IResource destResource = newResources[i];
IResource sourceResource = resources[i];
/* The names of the properties will remain the same in both the source and
destination hierarchies. So, be sure to use sourceResource to get the
name or your qualified name will contain 'destination' instead of
'source' and the property value will be null.
*/
QualifiedName propName = new QualifiedName("test", sourceResource.getName() + propNames[j]);
String propValue = sourceResource.getName() + propValues[j];
String persistentValue = destResource.getPersistentProperty(propName);
Object sessionValue = destResource.getSessionProperty(propName);
assertTrue("persistent property value is not the same", propValue.equals(persistentValue));
assertTrue("session property value is not the same", propValue.equals(sessionValue));
}
}
}
public void testMoveResource() throws Exception {
/* create common objects */
IProject[] projects = getWorkspace().getRoot().getProjects();
/* create folder and file */
IFolder folder = projects[0].getFolder("folder");
IFile file = folder.getFile("file.txt");
ensureExistsInWorkspace(folder, true);
ensureExistsInWorkspace(file, true);
/* move to absolute destination */
IResource destination = projects[0].getFile("file.txt");
file.move(destination.getFullPath(), true, null);
assertTrue("1.1", !file.exists());
assertTrue("1.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("1.3", file.exists());
assertTrue("1.4", !destination.exists());
/* move to relative destination */
IPath path = new Path("destination");
destination = folder.getFile(path);
file.move(path, true, null);
assertTrue("2.1", !file.exists());
assertTrue("2.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("2.3", file.exists());
assertTrue("2.4", !destination.exists());
/* move folder to destination under its hierarchy */
destination = folder.getFolder("subfolder");
boolean ok = false;
try {
folder.move(destination.getFullPath(), true, null);
} catch (RuntimeException e) {
ok = true;
}
assertTrue("3.1", ok);
/* test flag force = false */
projects[0].refreshLocal(IResource.DEPTH_INFINITE, null);
IFolder subfolder = folder.getFolder("aaa");
ensureExistsInFileSystem(subfolder);
IFile anotherFile = folder.getFile("bbb");
ensureExistsInFileSystem(anotherFile);
destination = projects[0].getFolder("destination");
ok = false;
try {
folder.move(destination.getFullPath(), false, null);
} catch (CoreException e) {
ok = true;
// FIXME: remove this check?
// assertTrue("4.1", e.getStatus().getChildren().length == 2);
}
assertTrue("4.2", ok);
try {
folder.move(destination.getFullPath(), false, null);
fail("4.2.1");
} catch (CoreException e) {
}
assertTrue("4.3", folder.exists());
+ // FIXME: should #move be a best effort operation?
// its ok for the root to be moved but ensure the destination child wasn't moved
IResource destChild = ((IContainer) destination).getFile(new Path(anotherFile.getName()));
- assertTrue("4.4", destination.exists());
+ assertTrue("4.4", !destination.exists());
assertTrue("4.5", !destChild.exists());
// cleanup and delete the destination
try {
destination.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
} catch (CoreException e) {
fail("4.6", e);
}
try {
destination.delete(true, getMonitor());
} catch (CoreException e) {
fail("4.7", e);
}
folder.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
try {
folder.move(destination.getFullPath(), false, getMonitor());
} catch (CoreException e) {
fail("4.8");
}
destination.move(folder.getFullPath(), true, null);
assertTrue("4.9", folder.exists());
assertTrue("4.10", !destination.exists());
/* move a file that is not local but exists in the workspace */
file = projects[0].getFile("ghost");
final IFile hackFile = file;
final Workspace workspace = (Workspace) this.getWorkspace();
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
workspace.createResource(hackFile, false);
}
};
workspace.run(operation, null);
destination = projects[0].getFile("destination");
ok = false;
try {
file.move(destination.getFullPath(), true, null);
} catch (CoreException e) {
ok = true;
}
assertTrue("5.1", ok);
/* move file over a phantom */
assertTrue("6.1", file.exists());
operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
((Resource) hackFile).convertToPhantom();
}
};
workspace.run(operation, null);
assertTrue("6.2", !file.exists());
ResourceInfo info = ((File) file).getResourceInfo(true, false);
int flags = ((File) file).getFlags(info);
assertTrue("6.3", ((Resource) file).exists(flags, true));
anotherFile = folder.getFile("anotherFile");
ensureExistsInWorkspace(anotherFile, true);
anotherFile.move(file.getFullPath(), true, null);
assertTrue("6.4", file.exists());
}
/**
* A simple test that renames a file.
*/
public void testRenameFile() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// create a folder
String fileName = "file.txt";
IFile file = projects[0].getFile(fileName);
ensureExistsInWorkspace(file, true);
// add some properties to file (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
file.setPersistentProperty(propNames[j], propValues[j]);
file.setSessionProperty(propNames[j], propValues[j]);
}
// rename file
String newFileName = "newFile.txt";
IPath destination = projects[0].getFile(newFileName).getFullPath();
file.move(destination, true, null);
// get new folder instance
IFile newFile = projects[0].getFile(newFileName);
// assert file was renamed
assertDoesNotExistInWorkspace(file);
assertDoesNotExistInFileSystem(file);
assertExistsInWorkspace(newFile);
assertExistsInFileSystem(newFile);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFile.getPersistentProperty(propNames[j]);
Object sessionValue = newFile.getSessionProperty(propNames[j]);
assertTrue("persistent property value is not the same", propValues[j].equals(persistentValue));
assertTrue("session property value is not the same", propValues[j].equals(sessionValue));
}
}
/**
* A simple test that renames a folder.
*
* - creates a folder
* - set properties (server, local and session)
* - rename folder
* - assert rename worked
* - assert properties still exist
*/
public void testRenameFolder() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// create a folder
String folderName = "folder";
IFolder folder = projects[0].getFolder(folderName);
ensureExistsInWorkspace(folder, true);
// add some properties to folder (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
folder.setPersistentProperty(propNames[j], propValues[j]);
folder.setSessionProperty(propNames[j], propValues[j]);
}
// rename folder
String newFolderName = "newFolder";
IPath destination = projects[0].getFolder(newFolderName).getFullPath();
folder.move(destination, true, null);
// get new folder instance
IFolder newFolder = projects[0].getFolder(newFolderName);
// assert folder was renamed
assertDoesNotExistInWorkspace(folder);
assertDoesNotExistInFileSystem(folder);
assertExistsInWorkspace(newFolder);
assertExistsInFileSystem(newFolder);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFolder.getPersistentProperty(propNames[j]);
Object sessionValue = newFolder.getSessionProperty(propNames[j]);
assertTrue("persistent property value is not the same", propValues[j].equals(persistentValue));
assertTrue("session property value is not the same", propValues[j].equals(sessionValue));
}
}
/**
* Renames 3 projects using their names.
*
* - add properties to projects (server, local and session)
* - rename projects
* - assert properties are correct
* - assert resources are correct
*/
public void testRenameProjects() throws Exception {
/* create common objects */
IProject[] projects = getWorkspace().getRoot().getProjects();
// add some properties to projects (persistent and session)
numberOfProperties = numberOfProjects;
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int i = 0; i < numberOfProjects; i++) {
propNames[i] = new QualifiedName("test", "prop" + i);
propValues[i] = "value" + i;
projects[i].setPersistentProperty(propNames[i], propValues[i]);
projects[i].setSessionProperty(propNames[i], propValues[i]);
}
// assert properties exist (persistent and session)
for (int i = 0; i < numberOfProjects; i++) {
String persistentValue = projects[i].getPersistentProperty(propNames[i]);
Object sessionValue = projects[i].getSessionProperty(propNames[i]);
assertTrue("1.0." + i, propValues[i].equals(persistentValue));
assertTrue("1.1." + i, propValues[i].equals(sessionValue));
}
// move (rename) projects
String prefix = "Renamed_PrOjEcT";
for (int i = 0; i < numberOfProjects; i++) {
String projectName = prefix + i;
IPath destination = getWorkspace().getRoot().getProject(projectName).getFullPath();
projects[i].move(destination, true, null);
projectNames[i] = projectName;
}
// get new projects instances
for (int i = 0; i < numberOfProjects; i++)
projects[i] = getWorkspace().getRoot().getProject(projectNames[i]);
// assert properties still exist (persistent and session)
for (int i = 0; i < numberOfProjects; i++) {
String persistentValue = projects[i].getPersistentProperty(propNames[i]);
Object sessionValue = projects[i].getSessionProperty(propNames[i]);
assertTrue("2.0." + i, propValues[i].equals(persistentValue));
assertTrue("2.1." + i, propValues[i].equals(sessionValue));
}
}
}
| false | true | public void testMoveResource() throws Exception {
/* create common objects */
IProject[] projects = getWorkspace().getRoot().getProjects();
/* create folder and file */
IFolder folder = projects[0].getFolder("folder");
IFile file = folder.getFile("file.txt");
ensureExistsInWorkspace(folder, true);
ensureExistsInWorkspace(file, true);
/* move to absolute destination */
IResource destination = projects[0].getFile("file.txt");
file.move(destination.getFullPath(), true, null);
assertTrue("1.1", !file.exists());
assertTrue("1.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("1.3", file.exists());
assertTrue("1.4", !destination.exists());
/* move to relative destination */
IPath path = new Path("destination");
destination = folder.getFile(path);
file.move(path, true, null);
assertTrue("2.1", !file.exists());
assertTrue("2.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("2.3", file.exists());
assertTrue("2.4", !destination.exists());
/* move folder to destination under its hierarchy */
destination = folder.getFolder("subfolder");
boolean ok = false;
try {
folder.move(destination.getFullPath(), true, null);
} catch (RuntimeException e) {
ok = true;
}
assertTrue("3.1", ok);
/* test flag force = false */
projects[0].refreshLocal(IResource.DEPTH_INFINITE, null);
IFolder subfolder = folder.getFolder("aaa");
ensureExistsInFileSystem(subfolder);
IFile anotherFile = folder.getFile("bbb");
ensureExistsInFileSystem(anotherFile);
destination = projects[0].getFolder("destination");
ok = false;
try {
folder.move(destination.getFullPath(), false, null);
} catch (CoreException e) {
ok = true;
// FIXME: remove this check?
// assertTrue("4.1", e.getStatus().getChildren().length == 2);
}
assertTrue("4.2", ok);
try {
folder.move(destination.getFullPath(), false, null);
fail("4.2.1");
} catch (CoreException e) {
}
assertTrue("4.3", folder.exists());
// its ok for the root to be moved but ensure the destination child wasn't moved
IResource destChild = ((IContainer) destination).getFile(new Path(anotherFile.getName()));
assertTrue("4.4", destination.exists());
assertTrue("4.5", !destChild.exists());
// cleanup and delete the destination
try {
destination.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
} catch (CoreException e) {
fail("4.6", e);
}
try {
destination.delete(true, getMonitor());
} catch (CoreException e) {
fail("4.7", e);
}
folder.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
try {
folder.move(destination.getFullPath(), false, getMonitor());
} catch (CoreException e) {
fail("4.8");
}
destination.move(folder.getFullPath(), true, null);
assertTrue("4.9", folder.exists());
assertTrue("4.10", !destination.exists());
/* move a file that is not local but exists in the workspace */
file = projects[0].getFile("ghost");
final IFile hackFile = file;
final Workspace workspace = (Workspace) this.getWorkspace();
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
workspace.createResource(hackFile, false);
}
};
workspace.run(operation, null);
destination = projects[0].getFile("destination");
ok = false;
try {
file.move(destination.getFullPath(), true, null);
} catch (CoreException e) {
ok = true;
}
assertTrue("5.1", ok);
/* move file over a phantom */
assertTrue("6.1", file.exists());
operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
((Resource) hackFile).convertToPhantom();
}
};
workspace.run(operation, null);
assertTrue("6.2", !file.exists());
ResourceInfo info = ((File) file).getResourceInfo(true, false);
int flags = ((File) file).getFlags(info);
assertTrue("6.3", ((Resource) file).exists(flags, true));
anotherFile = folder.getFile("anotherFile");
ensureExistsInWorkspace(anotherFile, true);
anotherFile.move(file.getFullPath(), true, null);
assertTrue("6.4", file.exists());
}
| public void testMoveResource() throws Exception {
/* create common objects */
IProject[] projects = getWorkspace().getRoot().getProjects();
/* create folder and file */
IFolder folder = projects[0].getFolder("folder");
IFile file = folder.getFile("file.txt");
ensureExistsInWorkspace(folder, true);
ensureExistsInWorkspace(file, true);
/* move to absolute destination */
IResource destination = projects[0].getFile("file.txt");
file.move(destination.getFullPath(), true, null);
assertTrue("1.1", !file.exists());
assertTrue("1.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("1.3", file.exists());
assertTrue("1.4", !destination.exists());
/* move to relative destination */
IPath path = new Path("destination");
destination = folder.getFile(path);
file.move(path, true, null);
assertTrue("2.1", !file.exists());
assertTrue("2.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("2.3", file.exists());
assertTrue("2.4", !destination.exists());
/* move folder to destination under its hierarchy */
destination = folder.getFolder("subfolder");
boolean ok = false;
try {
folder.move(destination.getFullPath(), true, null);
} catch (RuntimeException e) {
ok = true;
}
assertTrue("3.1", ok);
/* test flag force = false */
projects[0].refreshLocal(IResource.DEPTH_INFINITE, null);
IFolder subfolder = folder.getFolder("aaa");
ensureExistsInFileSystem(subfolder);
IFile anotherFile = folder.getFile("bbb");
ensureExistsInFileSystem(anotherFile);
destination = projects[0].getFolder("destination");
ok = false;
try {
folder.move(destination.getFullPath(), false, null);
} catch (CoreException e) {
ok = true;
// FIXME: remove this check?
// assertTrue("4.1", e.getStatus().getChildren().length == 2);
}
assertTrue("4.2", ok);
try {
folder.move(destination.getFullPath(), false, null);
fail("4.2.1");
} catch (CoreException e) {
}
assertTrue("4.3", folder.exists());
// FIXME: should #move be a best effort operation?
// its ok for the root to be moved but ensure the destination child wasn't moved
IResource destChild = ((IContainer) destination).getFile(new Path(anotherFile.getName()));
assertTrue("4.4", !destination.exists());
assertTrue("4.5", !destChild.exists());
// cleanup and delete the destination
try {
destination.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
} catch (CoreException e) {
fail("4.6", e);
}
try {
destination.delete(true, getMonitor());
} catch (CoreException e) {
fail("4.7", e);
}
folder.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
try {
folder.move(destination.getFullPath(), false, getMonitor());
} catch (CoreException e) {
fail("4.8");
}
destination.move(folder.getFullPath(), true, null);
assertTrue("4.9", folder.exists());
assertTrue("4.10", !destination.exists());
/* move a file that is not local but exists in the workspace */
file = projects[0].getFile("ghost");
final IFile hackFile = file;
final Workspace workspace = (Workspace) this.getWorkspace();
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
workspace.createResource(hackFile, false);
}
};
workspace.run(operation, null);
destination = projects[0].getFile("destination");
ok = false;
try {
file.move(destination.getFullPath(), true, null);
} catch (CoreException e) {
ok = true;
}
assertTrue("5.1", ok);
/* move file over a phantom */
assertTrue("6.1", file.exists());
operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
((Resource) hackFile).convertToPhantom();
}
};
workspace.run(operation, null);
assertTrue("6.2", !file.exists());
ResourceInfo info = ((File) file).getResourceInfo(true, false);
int flags = ((File) file).getFlags(info);
assertTrue("6.3", ((Resource) file).exists(flags, true));
anotherFile = folder.getFile("anotherFile");
ensureExistsInWorkspace(anotherFile, true);
anotherFile.move(file.getFullPath(), true, null);
assertTrue("6.4", file.exists());
}
|
diff --git a/user/test/com/google/gwt/uibinder/elementparsers/MockUiBinderWriter.java b/user/test/com/google/gwt/uibinder/elementparsers/MockUiBinderWriter.java
index a2984bccd..ac4621119 100644
--- a/user/test/com/google/gwt/uibinder/elementparsers/MockUiBinderWriter.java
+++ b/user/test/com/google/gwt/uibinder/elementparsers/MockUiBinderWriter.java
@@ -1,55 +1,55 @@
/*
* Copyright 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.google.gwt.uibinder.elementparsers;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.uibinder.rebind.DesignTimeUtilsStub;
import com.google.gwt.uibinder.rebind.FieldManager;
import com.google.gwt.uibinder.rebind.MortalLogger;
import com.google.gwt.uibinder.rebind.HtmlElementFactory;
import com.google.gwt.uibinder.rebind.UiBinderContext;
import com.google.gwt.uibinder.rebind.UiBinderWriter;
import com.google.gwt.uibinder.rebind.XMLElement;
import com.google.gwt.uibinder.rebind.messages.MessagesWriter;
import java.util.ArrayList;
import java.util.List;
class MockUiBinderWriter extends UiBinderWriter {
final List<String> statements = new ArrayList<String>();
public MockUiBinderWriter(JClassType baseClass, String implClassName,
String templatePath, TypeOracle oracle, MortalLogger logger,
FieldManager fieldManager, MessagesWriter messagesWriter,
HtmlElementFactory factory) throws UnableToCompleteException {
super(baseClass, implClassName, templatePath, oracle, logger, fieldManager,
- messagesWriter, DesignTimeUtilsStub.EMPTY, new UiBinderContext(),
+ messagesWriter, DesignTimeUtilsStub.EMPTY, new UiBinderContext(),
factory);
}
@Override
public void addStatement(String format, Object... args) {
statements.add(String.format(format, args));
}
@Override
public String parseElementToField(XMLElement elem)
throws UnableToCompleteException {
return elem.consumeOpeningTag();
}
}
| true | true | public MockUiBinderWriter(JClassType baseClass, String implClassName,
String templatePath, TypeOracle oracle, MortalLogger logger,
FieldManager fieldManager, MessagesWriter messagesWriter,
HtmlElementFactory factory) throws UnableToCompleteException {
super(baseClass, implClassName, templatePath, oracle, logger, fieldManager,
messagesWriter, DesignTimeUtilsStub.EMPTY, new UiBinderContext(),
factory);
}
| public MockUiBinderWriter(JClassType baseClass, String implClassName,
String templatePath, TypeOracle oracle, MortalLogger logger,
FieldManager fieldManager, MessagesWriter messagesWriter,
HtmlElementFactory factory) throws UnableToCompleteException {
super(baseClass, implClassName, templatePath, oracle, logger, fieldManager,
messagesWriter, DesignTimeUtilsStub.EMPTY, new UiBinderContext(),
factory);
}
|
diff --git a/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIGroupEditMembershipForm.java b/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIGroupEditMembershipForm.java
index 23bf7f5b0..6cdc7f1ea 100644
--- a/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIGroupEditMembershipForm.java
+++ b/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIGroupEditMembershipForm.java
@@ -1,112 +1,119 @@
/*
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* 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, see<http://www.gnu.org/licenses/>.
*/
package org.exoplatform.organization.webui.component;
import java.util.ArrayList;
import java.util.List;
import org.exoplatform.services.organization.Group;
import org.exoplatform.services.organization.Membership;
import org.exoplatform.services.organization.MembershipHandler;
import org.exoplatform.services.organization.MembershipType;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.organization.User;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIApplication;
import org.exoplatform.webui.core.UIPopupWindow;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.core.model.SelectItemOption;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormSelectBox;
import org.exoplatform.webui.form.UIFormStringInput;
/**
* Created by The eXo Platform SARL
* Author : dang.tung
* [email protected]
* Dec 2, 2008
*/
@ComponentConfig(
lifecycle = UIFormLifecycle.class,
template = "system:/groovy/webui/form/UIForm.gtmpl",
events = {
@EventConfig(listeners = UIGroupEditMembershipForm.SaveActionListener.class),
@EventConfig(listeners = UIGroupEditMembershipForm.CancelActionListener.class)
}
)
public class UIGroupEditMembershipForm extends UIForm {
private List<SelectItemOption<String>> listOption = new ArrayList<SelectItemOption<String>>();
private final static String USER_NAME = "username";
private final static String MEMBER_SHIP = "membership";
private Membership membership;
private Group group;
public UIGroupEditMembershipForm() throws Exception {
addUIFormInput(new UIFormStringInput(USER_NAME, USER_NAME, null).setEditable(false));
addUIFormInput(new UIFormSelectBox(MEMBER_SHIP,MEMBER_SHIP, listOption).setSize(1));
}
public void setValue(Membership memberShip, Group selectedGroup) throws Exception {
this.membership = memberShip;
this.group = selectedGroup;
getUIStringInput(USER_NAME).setValue(memberShip.getUserName());
OrganizationService service = getApplicationComponent(OrganizationService.class) ;
List<?> collection = (List<?>) service.getMembershipTypeHandler().findMembershipTypes();
for(Object ele : collection){
MembershipType mt = (MembershipType) ele;
SelectItemOption<String> option = new SelectItemOption<String>(mt.getName(), mt.getName(), mt.getDescription());
if(mt.getName().equals(memberShip.getMembershipType())) option.setSelected(true);
listOption.add(option);
}
}
static public class SaveActionListener extends EventListener<UIGroupEditMembershipForm> {
public void execute(Event<UIGroupEditMembershipForm> event) throws Exception {
UIGroupEditMembershipForm uiForm = event.getSource();
UIApplication uiApp = event.getRequestContext().getUIApplication() ;
+ UIPopupWindow uiPopup = uiForm.getParent();
OrganizationService service = uiForm.getApplicationComponent(OrganizationService.class);
- User user = service.getUserHandler().findUserByName(uiForm.membership.getUserName()) ;
+ String userName = uiForm.membership.getUserName();
+ Group group = uiForm.group;
+ User user = service.getUserHandler().findUserByName(userName) ;
MembershipHandler memberShipHandler = service.getMembershipHandler();
String memberShipType = uiForm.getUIFormSelectBox(MEMBER_SHIP).getValue();
MembershipType membershipType = service.getMembershipTypeHandler().findMembershipType(memberShipType);
+ Membership membership = memberShipHandler.findMembershipByUserGroupAndType(userName, group.getId(), membershipType.getName());
+ if(membership != null){
+ uiApp.addMessage(new ApplicationMessage("UIGroupEditMembershipForm.msg.membership-exist", null)) ;
+ return ;
+ }
try {
memberShipHandler.removeMembership(uiForm.membership.getId(), true);
- memberShipHandler.linkMembership(user,uiForm.group,membershipType,true);
+ memberShipHandler.linkMembership(user,group,membershipType,true);
} catch (Exception e) {
// membership removed
uiApp.addMessage(new ApplicationMessage("UIGroupEditMembershipForm.msg.membership-delete", null)) ;
}
- UIPopupWindow uiPopup = uiForm.getParent();
uiPopup.setUIComponent(null);
uiPopup.setShow(false);
}
}
static public class CancelActionListener extends EventListener<UIGroupEditMembershipForm> {
public void execute(Event<UIGroupEditMembershipForm> event) throws Exception {
UIGroupEditMembershipForm uiForm = event.getSource();
UIPopupWindow uiPopup = uiForm.getParent();
uiPopup.setUIComponent(null);
uiPopup.setShow(false);
}
}
}
| false | true | public void execute(Event<UIGroupEditMembershipForm> event) throws Exception {
UIGroupEditMembershipForm uiForm = event.getSource();
UIApplication uiApp = event.getRequestContext().getUIApplication() ;
OrganizationService service = uiForm.getApplicationComponent(OrganizationService.class);
User user = service.getUserHandler().findUserByName(uiForm.membership.getUserName()) ;
MembershipHandler memberShipHandler = service.getMembershipHandler();
String memberShipType = uiForm.getUIFormSelectBox(MEMBER_SHIP).getValue();
MembershipType membershipType = service.getMembershipTypeHandler().findMembershipType(memberShipType);
try {
memberShipHandler.removeMembership(uiForm.membership.getId(), true);
memberShipHandler.linkMembership(user,uiForm.group,membershipType,true);
} catch (Exception e) {
// membership removed
uiApp.addMessage(new ApplicationMessage("UIGroupEditMembershipForm.msg.membership-delete", null)) ;
}
UIPopupWindow uiPopup = uiForm.getParent();
uiPopup.setUIComponent(null);
uiPopup.setShow(false);
}
| public void execute(Event<UIGroupEditMembershipForm> event) throws Exception {
UIGroupEditMembershipForm uiForm = event.getSource();
UIApplication uiApp = event.getRequestContext().getUIApplication() ;
UIPopupWindow uiPopup = uiForm.getParent();
OrganizationService service = uiForm.getApplicationComponent(OrganizationService.class);
String userName = uiForm.membership.getUserName();
Group group = uiForm.group;
User user = service.getUserHandler().findUserByName(userName) ;
MembershipHandler memberShipHandler = service.getMembershipHandler();
String memberShipType = uiForm.getUIFormSelectBox(MEMBER_SHIP).getValue();
MembershipType membershipType = service.getMembershipTypeHandler().findMembershipType(memberShipType);
Membership membership = memberShipHandler.findMembershipByUserGroupAndType(userName, group.getId(), membershipType.getName());
if(membership != null){
uiApp.addMessage(new ApplicationMessage("UIGroupEditMembershipForm.msg.membership-exist", null)) ;
return ;
}
try {
memberShipHandler.removeMembership(uiForm.membership.getId(), true);
memberShipHandler.linkMembership(user,group,membershipType,true);
} catch (Exception e) {
// membership removed
uiApp.addMessage(new ApplicationMessage("UIGroupEditMembershipForm.msg.membership-delete", null)) ;
}
uiPopup.setUIComponent(null);
uiPopup.setShow(false);
}
|
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index f578cc8de..1436a10ac 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -1,2440 +1,2435 @@
/*
* 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.inputmethod.latin;
import static com.android.inputmethod.latin.Constants.ImeOption.FORCE_ASCII;
import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE;
import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE_COMPAT;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.inputmethodservice.InputMethodService;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.os.Debug;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodSubtype;
import com.android.inputmethod.accessibility.AccessibilityUtils;
import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy;
import com.android.inputmethod.compat.CompatUtils;
import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
import com.android.inputmethod.compat.InputMethodServiceCompatUtils;
import com.android.inputmethod.compat.SuggestionSpanUtils;
import com.android.inputmethod.keyboard.KeyDetector;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardActionListener;
import com.android.inputmethod.keyboard.KeyboardId;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.keyboard.MainKeyboardView;
import com.android.inputmethod.latin.LocaleUtils.RunInLocale;
import com.android.inputmethod.latin.Utils.Stats;
import com.android.inputmethod.latin.define.ProductionFlag;
import com.android.inputmethod.latin.suggestions.SuggestionStripView;
import com.android.inputmethod.research.ResearchLogger;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Locale;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public final class LatinIME extends InputMethodService implements KeyboardActionListener,
SuggestionStripView.Listener, TargetApplicationGetter.OnTargetApplicationKnownListener,
Suggest.SuggestInitializationListener {
private static final String TAG = LatinIME.class.getSimpleName();
private static final boolean TRACE = false;
private static boolean DEBUG;
private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
private static final int PENDING_IMS_CALLBACK_DURATION = 800;
/**
* The name of the scheme used by the Package Manager to warn of a new package installation,
* replacement or removal.
*/
private static final String SCHEME_PACKAGE = "package";
private static final int SPACE_STATE_NONE = 0;
// Double space: the state where the user pressed space twice quickly, which LatinIME
// resolved as period-space. Undoing this converts the period to a space.
private static final int SPACE_STATE_DOUBLE = 1;
// Swap punctuation: the state where a weak space and a punctuation from the suggestion strip
// have just been swapped. Undoing this swaps them back; the space is still considered weak.
private static final int SPACE_STATE_SWAP_PUNCTUATION = 2;
// Weak space: a space that should be swapped only by suggestion strip punctuation. Weak
// spaces happen when the user presses space, accepting the current suggestion (whether
// it's an auto-correction or not).
private static final int SPACE_STATE_WEAK = 3;
// Phantom space: a not-yet-inserted space that should get inserted on the next input,
// character provided it's not a separator. If it's a separator, the phantom space is dropped.
// Phantom spaces happen when a user chooses a word from the suggestion strip.
private static final int SPACE_STATE_PHANTOM = 4;
// Current space state of the input method. This can be any of the above constants.
private int mSpaceState;
private SettingsValues mCurrentSettings;
private View mExtractArea;
private View mKeyPreviewBackingView;
private View mSuggestionsContainer;
private SuggestionStripView mSuggestionStripView;
/* package for tests */ Suggest mSuggest;
private CompletionInfo[] mApplicationSpecifiedCompletions;
private ApplicationInfo mTargetApplicationInfo;
private InputMethodManagerCompatWrapper mImm;
private Resources mResources;
private SharedPreferences mPrefs;
/* package for tests */ final KeyboardSwitcher mKeyboardSwitcher;
private final SubtypeSwitcher mSubtypeSwitcher;
private boolean mShouldSwitchToLastSubtype = true;
private boolean mIsMainDictionaryAvailable;
private UserBinaryDictionary mUserDictionary;
private UserHistoryDictionary mUserHistoryDictionary;
private boolean mIsUserDictionaryAvailable;
private LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
private final WordComposer mWordComposer = new WordComposer();
private RichInputConnection mConnection = new RichInputConnection(this);
// Keep track of the last selection range to decide if we need to show word alternatives
private static final int NOT_A_CURSOR_POSITION = -1;
private int mLastSelectionStart = NOT_A_CURSOR_POSITION;
private int mLastSelectionEnd = NOT_A_CURSOR_POSITION;
// Whether we are expecting an onUpdateSelection event to fire. If it does when we don't
// "expect" it, it means the user actually moved the cursor.
private boolean mExpectingUpdateSelection;
private int mDeleteCount;
private long mLastKeyTime;
private AudioAndHapticFeedbackManager mFeedbackManager;
// Member variables for remembering the current device orientation.
private int mDisplayOrientation;
// Object for reacting to adding/removing a dictionary pack.
private BroadcastReceiver mDictionaryPackInstallReceiver =
new DictionaryPackInstallBroadcastReceiver(this);
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
private boolean mIsAutoCorrectionIndicatorOn;
private AlertDialog mOptionsDialog;
private final boolean mIsHardwareAcceleratedDrawingEnabled;
public final UIHandler mHandler = new UIHandler(this);
public static final class UIHandler extends StaticInnerHandlerWrapper<LatinIME> {
private static final int MSG_UPDATE_SHIFT_STATE = 0;
private static final int MSG_PENDING_IMS_CALLBACK = 1;
private static final int MSG_UPDATE_SUGGESTION_STRIP = 2;
private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3;
private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1;
private int mDelayUpdateSuggestions;
private int mDelayUpdateShiftState;
private long mDoubleSpacesTurnIntoPeriodTimeout;
private long mDoubleSpaceTimerStart;
public UIHandler(final LatinIME outerInstance) {
super(outerInstance);
}
public void onCreate() {
final Resources res = getOuterInstance().getResources();
mDelayUpdateSuggestions =
res.getInteger(R.integer.config_delay_update_suggestions);
mDelayUpdateShiftState =
res.getInteger(R.integer.config_delay_update_shift_state);
mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger(
R.integer.config_double_spaces_turn_into_period_timeout);
}
@Override
public void handleMessage(final Message msg) {
final LatinIME latinIme = getOuterInstance();
final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher;
switch (msg.what) {
case MSG_UPDATE_SUGGESTION_STRIP:
latinIme.updateSuggestionStrip();
break;
case MSG_UPDATE_SHIFT_STATE:
switcher.updateShiftState();
break;
case MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP:
latinIme.showGesturePreviewAndSuggestionStrip((SuggestedWords)msg.obj,
msg.arg1 == ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT);
break;
}
}
public void postUpdateSuggestionStrip() {
sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP), mDelayUpdateSuggestions);
}
public void cancelUpdateSuggestionStrip() {
removeMessages(MSG_UPDATE_SUGGESTION_STRIP);
}
public boolean hasPendingUpdateSuggestions() {
return hasMessages(MSG_UPDATE_SUGGESTION_STRIP);
}
public void postUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState);
}
public void cancelUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
}
public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
final boolean dismissGestureFloatingPreviewText) {
removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP);
final int arg1 = dismissGestureFloatingPreviewText
? ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT : 0;
obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, arg1, 0, suggestedWords)
.sendToTarget();
}
public void startDoubleSpacesTimer() {
mDoubleSpaceTimerStart = SystemClock.uptimeMillis();
}
public void cancelDoubleSpacesTimer() {
mDoubleSpaceTimerStart = 0;
}
public boolean isAcceptingDoubleSpaces() {
return SystemClock.uptimeMillis() - mDoubleSpaceTimerStart
< mDoubleSpacesTurnIntoPeriodTimeout;
}
// Working variables for the following methods.
private boolean mIsOrientationChanging;
private boolean mPendingSuccessiveImsCallback;
private boolean mHasPendingStartInput;
private boolean mHasPendingFinishInputView;
private boolean mHasPendingFinishInput;
private EditorInfo mAppliedEditorInfo;
public void startOrientationChanging() {
removeMessages(MSG_PENDING_IMS_CALLBACK);
resetPendingImsCallback();
mIsOrientationChanging = true;
final LatinIME latinIme = getOuterInstance();
if (latinIme.isInputViewShown()) {
latinIme.mKeyboardSwitcher.saveKeyboardState();
}
}
private void resetPendingImsCallback() {
mHasPendingFinishInputView = false;
mHasPendingFinishInput = false;
mHasPendingStartInput = false;
}
private void executePendingImsCallback(final LatinIME latinIme, final EditorInfo editorInfo,
boolean restarting) {
if (mHasPendingFinishInputView)
latinIme.onFinishInputViewInternal(mHasPendingFinishInput);
if (mHasPendingFinishInput)
latinIme.onFinishInputInternal();
if (mHasPendingStartInput)
latinIme.onStartInputInternal(editorInfo, restarting);
resetPendingImsCallback();
}
public void onStartInput(final EditorInfo editorInfo, final boolean restarting) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the second onStartInput after orientation changed.
mHasPendingStartInput = true;
} else {
if (mIsOrientationChanging && restarting) {
// This is the first onStartInput after orientation changed.
mIsOrientationChanging = false;
mPendingSuccessiveImsCallback = true;
}
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, editorInfo, restarting);
latinIme.onStartInputInternal(editorInfo, restarting);
}
}
public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)
&& KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) {
// Typically this is the second onStartInputView after orientation changed.
resetPendingImsCallback();
} else {
if (mPendingSuccessiveImsCallback) {
// This is the first onStartInputView after orientation changed.
mPendingSuccessiveImsCallback = false;
resetPendingImsCallback();
sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK),
PENDING_IMS_CALLBACK_DURATION);
}
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, editorInfo, restarting);
latinIme.onStartInputViewInternal(editorInfo, restarting);
mAppliedEditorInfo = editorInfo;
}
}
public void onFinishInputView(final boolean finishingInput) {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the first onFinishInputView after orientation changed.
mHasPendingFinishInputView = true;
} else {
final LatinIME latinIme = getOuterInstance();
latinIme.onFinishInputViewInternal(finishingInput);
mAppliedEditorInfo = null;
}
}
public void onFinishInput() {
if (hasMessages(MSG_PENDING_IMS_CALLBACK)) {
// Typically this is the first onFinishInput after orientation changed.
mHasPendingFinishInput = true;
} else {
final LatinIME latinIme = getOuterInstance();
executePendingImsCallback(latinIme, null, false);
latinIme.onFinishInputInternal();
}
}
}
public LatinIME() {
super();
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mIsHardwareAcceleratedDrawingEnabled =
InputMethodServiceCompatUtils.enableHardwareAcceleration(this);
Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled);
}
@Override
public void onCreate() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs = prefs;
LatinImeLogger.init(this, prefs);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().init(this, prefs);
}
InputMethodManagerCompatWrapper.init(this);
SubtypeSwitcher.init(this);
KeyboardSwitcher.init(this, prefs);
AccessibilityUtils.init(this);
super.onCreate();
mImm = InputMethodManagerCompatWrapper.getInstance();
mHandler.onCreate();
DEBUG = LatinImeLogger.sDBG;
final Resources res = getResources();
mResources = res;
loadSettings();
ImfUtils.setAdditionalInputMethodSubtypes(this, mCurrentSettings.getAdditionalSubtypes());
initSuggest();
mDisplayOrientation = res.getConfiguration().orientation;
// Register to receive ringer mode change and network state change.
// Also receive installation and removal of a dictionary pack.
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
final IntentFilter packageFilter = new IntentFilter();
packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
packageFilter.addDataScheme(SCHEME_PACKAGE);
registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
final IntentFilter newDictFilter = new IntentFilter();
newDictFilter.addAction(
DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION);
registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
}
// Has to be package-visible for unit tests
/* package for test */
void loadSettings() {
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
final InputAttributes inputAttributes =
new InputAttributes(getCurrentInputEditorInfo(), isFullscreenMode());
final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() {
@Override
protected SettingsValues job(Resources res) {
return new SettingsValues(mPrefs, inputAttributes, LatinIME.this);
}
};
mCurrentSettings = job.runInLocale(mResources, mSubtypeSwitcher.getCurrentSubtypeLocale());
mFeedbackManager = new AudioAndHapticFeedbackManager(this, mCurrentSettings);
resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary());
}
// Note that this method is called from a non-UI thread.
@Override
public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) {
mIsMainDictionaryAvailable = isMainDictionaryAvailable;
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable);
}
}
private void initSuggest() {
final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
final String localeStr = subtypeLocale.toString();
final ContactsBinaryDictionary oldContactsDictionary;
if (mSuggest != null) {
oldContactsDictionary = mSuggest.getContactsDictionary();
mSuggest.close();
} else {
oldContactsDictionary = null;
}
mSuggest = new Suggest(this /* Context */, subtypeLocale,
this /* SuggestInitializationListener */);
if (mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().initSuggest(mSuggest);
}
mUserDictionary = new UserBinaryDictionary(this, localeStr);
mIsUserDictionaryAvailable = mUserDictionary.isEnabled();
mSuggest.setUserDictionary(mUserDictionary);
resetContactsDictionary(oldContactsDictionary);
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, mPrefs);
mSuggest.setUserHistoryDictionary(mUserHistoryDictionary);
}
/**
* Resets the contacts dictionary in mSuggest according to the user settings.
*
* This method takes an optional contacts dictionary to use when the locale hasn't changed
* since the contacts dictionary can be opened or closed as necessary depending on the settings.
*
* @param oldContactsDictionary an optional dictionary to use, or null
*/
private void resetContactsDictionary(final ContactsBinaryDictionary oldContactsDictionary) {
final boolean shouldSetDictionary = (null != mSuggest && mCurrentSettings.mUseContactsDict);
final ContactsBinaryDictionary dictionaryToUse;
if (!shouldSetDictionary) {
// Make sure the dictionary is closed. If it is already closed, this is a no-op,
// so it's safe to call it anyways.
if (null != oldContactsDictionary) oldContactsDictionary.close();
dictionaryToUse = null;
} else {
final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale();
if (null != oldContactsDictionary) {
if (!oldContactsDictionary.mLocale.equals(locale)) {
// If the locale has changed then recreate the contacts dictionary. This
// allows locale dependent rules for handling bigram name predictions.
oldContactsDictionary.close();
dictionaryToUse = new ContactsBinaryDictionary(this, locale);
} else {
// Make sure the old contacts dictionary is opened. If it is already open,
// this is a no-op, so it's safe to call it anyways.
oldContactsDictionary.reopen(this);
dictionaryToUse = oldContactsDictionary;
}
} else {
dictionaryToUse = new ContactsBinaryDictionary(this, locale);
}
}
if (null != mSuggest) {
mSuggest.setContactsDictionary(dictionaryToUse);
}
}
/* package private */ void resetSuggestMainDict() {
final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale();
mSuggest.resetMainDict(this, subtypeLocale, this /* SuggestInitializationListener */);
mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale);
}
@Override
public void onDestroy() {
if (mSuggest != null) {
mSuggest.close();
mSuggest = null;
}
unregisterReceiver(mReceiver);
unregisterReceiver(mDictionaryPackInstallReceiver);
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(final Configuration conf) {
// System locale has been changed. Needs to reload keyboard.
if (mSubtypeSwitcher.onConfigurationChanged(conf, this)) {
loadKeyboard();
}
// If orientation changed while predicting, commit the change
if (mDisplayOrientation != conf.orientation) {
mDisplayOrientation = conf.orientation;
mHandler.startOrientationChanging();
mConnection.beginBatchEdit();
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
mConnection.finishComposingText();
mConnection.endBatchEdit();
if (isShowingOptionDialog()) {
mOptionsDialog.dismiss();
}
}
super.onConfigurationChanged(conf);
}
@Override
public View onCreateInputView() {
return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled);
}
@Override
public void setInputView(final View view) {
super.setInputView(view);
mExtractArea = getWindow().getWindow().getDecorView()
.findViewById(android.R.id.extractArea);
mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing);
mSuggestionsContainer = view.findViewById(R.id.suggestions_container);
mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view);
if (mSuggestionStripView != null)
mSuggestionStripView.setListener(this, view);
if (LatinImeLogger.sVISUALDEBUG) {
mKeyPreviewBackingView.setBackgroundColor(0x10FF0000);
}
}
@Override
public void setCandidatesView(final View view) {
// To ensure that CandidatesView will never be set.
return;
}
@Override
public void onStartInput(final EditorInfo editorInfo, final boolean restarting) {
mHandler.onStartInput(editorInfo, restarting);
}
@Override
public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) {
mHandler.onStartInputView(editorInfo, restarting);
}
@Override
public void onFinishInputView(final boolean finishingInput) {
mHandler.onFinishInputView(finishingInput);
}
@Override
public void onFinishInput() {
mHandler.onFinishInput();
}
@Override
public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) {
// Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged()
// is not guaranteed. It may even be called at the same time on a different thread.
mSubtypeSwitcher.updateSubtype(subtype);
loadKeyboard();
}
private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInput(editorInfo, restarting);
}
@SuppressWarnings("deprecation")
private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInputView(editorInfo, restarting);
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
if (editorInfo == null) {
Log.e(TAG, "Null EditorInfo in onStartInputView()");
if (LatinImeLogger.sDBG) {
throw new NullPointerException("Null EditorInfo in onStartInputView()");
}
return;
}
if (DEBUG) {
Log.d(TAG, "onStartInputView: editorInfo:"
+ String.format("inputType=0x%08x imeOptions=0x%08x",
editorInfo.inputType, editorInfo.imeOptions));
Log.d(TAG, "All caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
+ ", sentence caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
+ ", word caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
}
if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
}
if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
}
mTargetApplicationInfo =
TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName);
if (null == mTargetApplicationInfo) {
new TargetApplicationGetter(this /* context */, this /* listener */)
.execute(editorInfo.packageName);
}
LatinImeLogger.onStartInputView(editorInfo);
// In landscape mode, this method gets called without the input view being created.
if (mainKeyboardView == null) {
return;
}
// Forward this event to the accessibility utilities, if enabled.
final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
if (accessUtils.isTouchExplorationEnabled()) {
accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
}
- final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart
- || mLastSelectionEnd != editorInfo.initialSelEnd;
final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo);
final boolean isDifferentTextField = !restarting || inputTypeChanged;
if (isDifferentTextField) {
final boolean currentSubtypeEnabled = mSubtypeSwitcher
.updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
if (!currentSubtypeEnabled) {
// Current subtype is disabled. Needs to update subtype and keyboard.
final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype(
this, mSubtypeSwitcher.getNoLanguageSubtype());
mSubtypeSwitcher.updateSubtype(newSubtype);
loadKeyboard();
}
}
// The EditorInfo might have a flag that affects fullscreen mode.
// Note: This call should be done by InputMethodService?
updateFullscreenMode();
mApplicationSpecifiedCompletions = null;
// The app calling setText() has the effect of clearing the composing
// span, so we should reset our state unconditionally, even if restarting is true.
mEnteredText = null;
resetComposingState(true /* alsoResetLastComposedWord */);
mDeleteCount = 0;
mSpaceState = SPACE_STATE_NONE;
if (mSuggestionStripView != null) {
// This will set the punctuation suggestions if next word suggestion is off;
// otherwise it will clear the suggestion strip.
setPunctuationSuggestions();
}
mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart);
if (isDifferentTextField) {
mainKeyboardView.closing();
loadSettings();
if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
switcher.loadKeyboard(editorInfo, mCurrentSettings);
} else if (restarting) {
// TODO: Come up with a more comprehensive way to reset the keyboard layout when
// a keyboard layout set doesn't get reloaded in this method.
switcher.resetKeyboardStateToAlphabet();
+ // In apps like Talk, we come here when the text is sent and the field gets emptied and
+ // we need to re-evaluate the shift state, but not the whole layout which would be
+ // disruptive.
+ // Space state must be updated before calling updateShiftState
+ switcher.updateShiftState();
}
setSuggestionStripShownInternal(
isSuggestionsStripVisible(), /* needsInputViewShown */ false);
mLastSelectionStart = editorInfo.initialSelStart;
mLastSelectionEnd = editorInfo.initialSelEnd;
- // If we come here something in the text state is very likely to have changed.
- // We should update the shift state regardless of whether we are restarting or not, because
- // this is not perceived as a layout change that may be disruptive like we may have with
- // switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the
- // field gets emptied and we need to re-evaluate the shift state, but not the whole layout
- // which would be disruptive.
- // Space state must be updated before calling updateShiftState
- mKeyboardSwitcher.updateShiftState();
mHandler.cancelUpdateSuggestionStrip();
mHandler.cancelDoubleSpacesTimer();
mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable);
mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
mCurrentSettings.mKeyPreviewPopupDismissDelay);
mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled);
mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled,
mCurrentSettings.mGestureFloatingPreviewTextEnabled);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
// Callback for the TargetApplicationGetter
@Override
public void onTargetApplicationKnown(final ApplicationInfo info) {
mTargetApplicationInfo = info;
}
@Override
public void onWindowHidden() {
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onWindowHidden(mLastSelectionStart, mLastSelectionEnd,
getCurrentInputConnection());
}
super.onWindowHidden();
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
private void onFinishInputInternal() {
super.onFinishInput();
LatinImeLogger.commit();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().latinIME_onFinishInputInternal();
}
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
private void onFinishInputViewInternal(final boolean finishingInput) {
super.onFinishInputView(finishingInput);
mKeyboardSwitcher.onFinishInputView();
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.cancelAllMessages();
}
// Remove pending messages related to update suggestions
mHandler.cancelUpdateSuggestionStrip();
}
@Override
public void onUpdateSelection(final int oldSelStart, final int oldSelEnd,
final int newSelStart, final int newSelEnd,
final int composingSpanStart, final int composingSpanEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
composingSpanStart, composingSpanEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", lss=" + mLastSelectionStart
+ ", lse=" + mLastSelectionEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + composingSpanStart
+ ", ce=" + composingSpanEnd);
}
if (ProductionFlag.IS_EXPERIMENTAL) {
final boolean expectingUpdateSelectionFromLogger =
ResearchLogger.getAndClearLatinIMEExpectingUpdateSelection();
ResearchLogger.latinIME_onUpdateSelection(mLastSelectionStart, mLastSelectionEnd,
oldSelStart, oldSelEnd, newSelStart, newSelEnd, composingSpanStart,
composingSpanEnd, mExpectingUpdateSelection,
expectingUpdateSelectionFromLogger, mConnection);
if (expectingUpdateSelectionFromLogger) {
// TODO: Investigate. Quitting now sounds wrong - we won't do the resetting work
return;
}
}
// TODO: refactor the following code to be less contrived.
// "newSelStart != composingSpanEnd" || "newSelEnd != composingSpanEnd" means
// that the cursor is not at the end of the composing span, or there is a selection.
// "mLastSelectionStart != newSelStart" means that the cursor is not in the same place
// as last time we were called (if there is a selection, it means the start hasn't
// changed, so it's the end that did).
final boolean selectionChanged = (newSelStart != composingSpanEnd
|| newSelEnd != composingSpanEnd) && mLastSelectionStart != newSelStart;
// if composingSpanStart and composingSpanEnd are -1, it means there is no composing
// span in the view - we can use that to narrow down whether the cursor was moved
// by us or not. If we are composing a word but there is no composing span, then
// we know for sure the cursor moved while we were composing and we should reset
// the state.
final boolean noComposingSpan = composingSpanStart == -1 && composingSpanEnd == -1;
if (!mExpectingUpdateSelection
&& !mConnection.isBelatedExpectedUpdate(oldSelStart, newSelStart)) {
// TAKE CARE: there is a race condition when we enter this test even when the user
// did not explicitly move the cursor. This happens when typing fast, where two keys
// turn this flag on in succession and both onUpdateSelection() calls arrive after
// the second one - the first call successfully avoids this test, but the second one
// enters. For the moment we rely on noComposingSpan to further reduce the impact.
// TODO: the following is probably better done in resetEntireInputState().
// it should only happen when the cursor moved, and the very purpose of the
// test below is to narrow down whether this happened or not. Likewise with
// the call to updateShiftState.
// We set this to NONE because after a cursor move, we don't want the space
// state-related special processing to kick in.
mSpaceState = SPACE_STATE_NONE;
if ((!mWordComposer.isComposingWord()) || selectionChanged || noComposingSpan) {
// If we are composing a word and moving the cursor, we would want to set a
// suggestion span for recorrection to work correctly. Unfortunately, that
// would involve the keyboard committing some new text, which would move the
// cursor back to where it was. Latin IME could then fix the position of the cursor
// again, but the asynchronous nature of the calls results in this wreaking havoc
// with selection on double tap and the like.
// Another option would be to send suggestions each time we set the composing
// text, but that is probably too expensive to do, so we decided to leave things
// as is.
resetEntireInputState(newSelStart);
}
mKeyboardSwitcher.updateShiftState();
}
mExpectingUpdateSelection = false;
// TODO: Decide to call restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() or not
// here. It would probably be too expensive to call directly here but we may want to post a
// message to delay it. The point would be to unify behavior between backspace to the
// end of a word and manually put the pointer at the end of the word.
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
}
/**
* This is called when the user has clicked on the extracted text view,
* when running in fullscreen mode. The default implementation hides
* the suggestions view when this happens, but only if the extracted text
* editor has a vertical scroll bar because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the suggestions strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the suggestions view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the suggestions strip to disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(final int dx, final int dy) {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
mKeyboardSwitcher.onHideWindow();
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
super.hideWindow();
}
@Override
public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) {
if (DEBUG) {
Log.i(TAG, "Received completions:");
if (applicationSpecifiedCompletions != null) {
for (int i = 0; i < applicationSpecifiedCompletions.length; i++) {
Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]);
}
}
}
if (!mCurrentSettings.isApplicationSpecifiedCompletionsOn()) return;
mApplicationSpecifiedCompletions = applicationSpecifiedCompletions;
if (applicationSpecifiedCompletions == null) {
clearSuggestionStrip();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onDisplayCompletions(null);
}
return;
}
final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords =
SuggestedWords.getFromApplicationSpecifiedCompletions(
applicationSpecifiedCompletions);
final SuggestedWords suggestedWords = new SuggestedWords(
applicationSuggestedWords,
false /* typedWordValid */,
false /* hasAutoCorrectionCandidate */,
false /* isPunctuationSuggestions */,
false /* isObsoleteSuggestions */,
false /* isPrediction */);
// When in fullscreen mode, show completions generated by the application
final boolean isAutoCorrection = false;
setSuggestionStrip(suggestedWords, isAutoCorrection);
setAutoCorrectionIndicator(isAutoCorrection);
// TODO: is this the right thing to do? What should we auto-correct to in
// this case? This says to keep whatever the user typed.
mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
setSuggestionStripShown(true);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onDisplayCompletions(applicationSpecifiedCompletions);
}
}
private void setSuggestionStripShownInternal(final boolean shown,
final boolean needsInputViewShown) {
// TODO: Modify this if we support suggestions with hard keyboard
if (onEvaluateInputViewShown() && mSuggestionsContainer != null) {
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
final boolean inputViewShown = (mainKeyboardView != null)
? mainKeyboardView.isShown() : false;
final boolean shouldShowSuggestions = shown
&& (needsInputViewShown ? inputViewShown : true);
if (isFullscreenMode()) {
mSuggestionsContainer.setVisibility(
shouldShowSuggestions ? View.VISIBLE : View.GONE);
} else {
mSuggestionsContainer.setVisibility(
shouldShowSuggestions ? View.VISIBLE : View.INVISIBLE);
}
}
}
private void setSuggestionStripShown(final boolean shown) {
setSuggestionStripShownInternal(shown, /* needsInputViewShown */true);
}
private int getAdjustedBackingViewHeight() {
final int currentHeight = mKeyPreviewBackingView.getHeight();
if (currentHeight > 0) {
return currentHeight;
}
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView == null) {
return 0;
}
final int keyboardHeight = mainKeyboardView.getHeight();
final int suggestionsHeight = mSuggestionsContainer.getHeight();
final int displayHeight = mResources.getDisplayMetrics().heightPixels;
final Rect rect = new Rect();
mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect);
final int notificationBarHeight = rect.top;
final int remainingHeight = displayHeight - notificationBarHeight - suggestionsHeight
- keyboardHeight;
final LayoutParams params = mKeyPreviewBackingView.getLayoutParams();
params.height = mSuggestionStripView.setMoreSuggestionsHeight(remainingHeight);
mKeyPreviewBackingView.setLayoutParams(params);
return params.height;
}
@Override
public void onComputeInsets(final InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView == null || mSuggestionsContainer == null) {
return;
}
final int adjustedBackingHeight = getAdjustedBackingViewHeight();
final boolean backingGone = (mKeyPreviewBackingView.getVisibility() == View.GONE);
final int backingHeight = backingGone ? 0 : adjustedBackingHeight;
// In fullscreen mode, the height of the extract area managed by InputMethodService should
// be considered.
// See {@link android.inputmethodservice.InputMethodService#onComputeInsets}.
final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0;
final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0
: mSuggestionsContainer.getHeight();
final int extraHeight = extractHeight + backingHeight + suggestionsHeight;
int touchY = extraHeight;
// Need to set touchable region only if input view is being shown
if (mainKeyboardView.isShown()) {
if (mSuggestionsContainer.getVisibility() == View.VISIBLE) {
touchY -= suggestionsHeight;
}
final int touchWidth = mainKeyboardView.getWidth();
final int touchHeight = mainKeyboardView.getHeight() + extraHeight
// Extend touchable region below the keyboard.
+ EXTENDED_TOUCHABLE_REGION_HEIGHT;
outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION;
outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight);
}
outInsets.contentTopInsets = touchY;
outInsets.visibleTopInsets = touchY;
}
@Override
public boolean onEvaluateFullscreenMode() {
// Reread resource value here, because this method is called by framework anytime as needed.
final boolean isFullscreenModeAllowed =
mCurrentSettings.isFullscreenModeAllowed(getResources());
if (super.onEvaluateFullscreenMode() && isFullscreenModeAllowed) {
// TODO: Remove this hack. Actually we should not really assume NO_EXTRACT_UI
// implies NO_FULLSCREEN. However, the framework mistakenly does. i.e. NO_EXTRACT_UI
// without NO_FULLSCREEN doesn't work as expected. Because of this we need this
// hack for now. Let's get rid of this once the framework gets fixed.
final EditorInfo ei = getCurrentInputEditorInfo();
return !(ei != null && ((ei.imeOptions & EditorInfo.IME_FLAG_NO_EXTRACT_UI) != 0));
} else {
return false;
}
}
@Override
public void updateFullscreenMode() {
super.updateFullscreenMode();
if (mKeyPreviewBackingView == null) return;
// In fullscreen mode, no need to have extra space to show the key preview.
// If not, we should have extra space above the keyboard to show the key preview.
mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE);
}
// This will reset the whole input state to the starting state. It will clear
// the composing word, reset the last composed word, tell the inputconnection about it.
private void resetEntireInputState(final int newCursorPosition) {
resetComposingState(true /* alsoResetLastComposedWord */);
if (mCurrentSettings.mBigramPredictionEnabled) {
clearSuggestionStrip();
} else {
setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
}
mConnection.resetCachesUponCursorMove(newCursorPosition);
}
private void resetComposingState(final boolean alsoResetLastComposedWord) {
mWordComposer.reset();
if (alsoResetLastComposedWord)
mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
}
private void commitTyped(final String separatorString) {
if (!mWordComposer.isComposingWord()) return;
final CharSequence typedWord = mWordComposer.getTypedWord();
if (typedWord.length() > 0) {
commitChosenWord(typedWord, LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD,
separatorString);
}
}
// Called from the KeyboardSwitcher which needs to know auto caps state to display
// the right layout.
public int getCurrentAutoCapsState() {
if (!mCurrentSettings.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF;
final EditorInfo ei = getCurrentInputEditorInfo();
if (ei == null) return Constants.TextUtils.CAP_MODE_OFF;
final int inputType = ei.inputType;
// Warning: this depends on mSpaceState, which may not be the most current value. If
// mSpaceState gets updated later, whoever called this may need to be told about it.
return mConnection.getCursorCapsMode(inputType, mSubtypeSwitcher.getCurrentSubtypeLocale(),
SPACE_STATE_PHANTOM == mSpaceState);
}
// Factor in auto-caps and manual caps and compute the current caps mode.
private int getActualCapsMode() {
final int keyboardShiftMode = mKeyboardSwitcher.getKeyboardShiftMode();
if (keyboardShiftMode != WordComposer.CAPS_MODE_AUTO_SHIFTED) return keyboardShiftMode;
final int auto = getCurrentAutoCapsState();
if (0 != (auto & TextUtils.CAP_MODE_CHARACTERS)) {
return WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED;
}
if (0 != auto) return WordComposer.CAPS_MODE_AUTO_SHIFTED;
return WordComposer.CAPS_MODE_OFF;
}
private void swapSwapperAndSpace() {
CharSequence lastTwo = mConnection.getTextBeforeCursor(2, 0);
// It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called.
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == Keyboard.CODE_SPACE) {
mConnection.deleteSurroundingText(2, 0);
mConnection.commitText(lastTwo.charAt(1) + " ", 1);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_swapSwapperAndSpace();
}
mKeyboardSwitcher.updateShiftState();
}
}
private boolean maybeDoubleSpace() {
if (!mCurrentSettings.mCorrectionEnabled) return false;
if (!mHandler.isAcceptingDoubleSpaces()) return false;
final CharSequence lastThree = mConnection.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& canBeFollowedByPeriod(lastThree.charAt(0))
&& lastThree.charAt(1) == Keyboard.CODE_SPACE
&& lastThree.charAt(2) == Keyboard.CODE_SPACE) {
mHandler.cancelDoubleSpacesTimer();
mConnection.deleteSurroundingText(2, 0);
mConnection.commitText(". ", 1);
mKeyboardSwitcher.updateShiftState();
return true;
}
return false;
}
private static boolean canBeFollowedByPeriod(final int codePoint) {
// TODO: Check again whether there really ain't a better way to check this.
// TODO: This should probably be language-dependant...
return Character.isLetterOrDigit(codePoint)
|| codePoint == Keyboard.CODE_SINGLE_QUOTE
|| codePoint == Keyboard.CODE_DOUBLE_QUOTE
|| codePoint == Keyboard.CODE_CLOSING_PARENTHESIS
|| codePoint == Keyboard.CODE_CLOSING_SQUARE_BRACKET
|| codePoint == Keyboard.CODE_CLOSING_CURLY_BRACKET
|| codePoint == Keyboard.CODE_CLOSING_ANGLE_BRACKET;
}
// Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is
// pressed.
@Override
public boolean addWordToUserDictionary(final String word) {
mUserDictionary.addWordToUserDictionary(word, 128);
return true;
}
private static boolean isAlphabet(final int code) {
return Character.isLetter(code);
}
private void onSettingsKeyPressed() {
if (isShowingOptionDialog()) return;
showSubtypeSelectorAndSettings();
}
// Virtual codes representing custom requests. These are used in onCustomRequest() below.
public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1;
@Override
public boolean onCustomRequest(final int requestCode) {
if (isShowingOptionDialog()) return false;
switch (requestCode) {
case CODE_SHOW_INPUT_METHOD_PICKER:
if (ImfUtils.hasMultipleEnabledIMEsOrSubtypes(
this, true /* include aux subtypes */)) {
mImm.showInputMethodPicker();
return true;
}
return false;
}
return false;
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
private static int getActionId(final Keyboard keyboard) {
return keyboard != null ? keyboard.mId.imeActionId() : EditorInfo.IME_ACTION_NONE;
}
private void performEditorAction(final int actionId) {
mConnection.performEditorAction(actionId);
}
// TODO: Revise the language switch key behavior to make it much smarter and more reasonable.
private void handleLanguageSwitchKey() {
final IBinder token = getWindow().getWindow().getAttributes().token;
if (mCurrentSettings.mIncludesOtherImesInLanguageSwitchList) {
mImm.switchToNextInputMethod(token, false /* onlyCurrentIme */);
return;
}
if (mShouldSwitchToLastSubtype) {
final InputMethodSubtype lastSubtype = mImm.getLastInputMethodSubtype();
final boolean lastSubtypeBelongsToThisIme =
ImfUtils.checkIfSubtypeBelongsToThisImeAndEnabled(this, lastSubtype);
if (lastSubtypeBelongsToThisIme && mImm.switchToLastInputMethod(token)) {
mShouldSwitchToLastSubtype = false;
} else {
mImm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
mShouldSwitchToLastSubtype = true;
}
} else {
mImm.switchToNextInputMethod(token, true /* onlyCurrentIme */);
}
}
private void sendDownUpKeyEventForBackwardCompatibility(final int code) {
final long eventTime = SystemClock.uptimeMillis();
mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime,
KeyEvent.ACTION_DOWN, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE));
mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime,
KeyEvent.ACTION_UP, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE));
}
private void sendKeyCodePoint(final int code) {
// TODO: Remove this special handling of digit letters.
// For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}.
if (code >= '0' && code <= '9') {
sendDownUpKeyEventForBackwardCompatibility(code - '0' + KeyEvent.KEYCODE_0);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_sendKeyCodePoint(code);
}
return;
}
// 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
// we want to be able to compile against the Ice Cream Sandwich SDK.
if (Keyboard.CODE_ENTER == code && mTargetApplicationInfo != null
&& mTargetApplicationInfo.targetSdkVersion < 16) {
// Backward compatibility mode. Before Jelly bean, the keyboard would simulate
// a hardware keyboard event on pressing enter or delete. This is bad for many
// reasons (there are race conditions with commits) but some applications are
// relying on this behavior so we continue to support it for older apps.
sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_ENTER);
} else {
final String text = new String(new int[] { code }, 0, 1);
mConnection.commitText(text, text.length());
}
}
// Implementation of {@link KeyboardActionListener}.
@Override
public void onCodeInput(final int primaryCode, final int x, final int y) {
final long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
mConnection.beginBatchEdit();
final KeyboardSwitcher switcher = mKeyboardSwitcher;
// The space state depends only on the last character pressed and its own previous
// state. Here, we revert the space state to neutral if the key is actually modifying
// the input contents (any non-shift key), which is what we should do for
// all inputs that do not result in a special state. Each character handling is then
// free to override the state as they see fit.
final int spaceState = mSpaceState;
if (!mWordComposer.isComposingWord()) mIsAutoCorrectionIndicatorOn = false;
// TODO: Consolidate the double space timer, mLastKeyTime, and the space state.
if (primaryCode != Keyboard.CODE_SPACE) {
mHandler.cancelDoubleSpacesTimer();
}
boolean didAutoCorrect = false;
switch (primaryCode) {
case Keyboard.CODE_DELETE:
mSpaceState = SPACE_STATE_NONE;
handleBackspace(spaceState);
mDeleteCount++;
mExpectingUpdateSelection = true;
mShouldSwitchToLastSubtype = true;
LatinImeLogger.logOnDelete(x, y);
break;
case Keyboard.CODE_SHIFT:
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
// Shift and symbol key is handled in onPressKey() and onReleaseKey().
break;
case Keyboard.CODE_SETTINGS:
onSettingsKeyPressed();
break;
case Keyboard.CODE_SHORTCUT:
mSubtypeSwitcher.switchToShortcutIME(this);
break;
case Keyboard.CODE_ACTION_ENTER:
performEditorAction(getActionId(switcher.getKeyboard()));
break;
case Keyboard.CODE_ACTION_NEXT:
performEditorAction(EditorInfo.IME_ACTION_NEXT);
break;
case Keyboard.CODE_ACTION_PREVIOUS:
performEditorAction(EditorInfo.IME_ACTION_PREVIOUS);
break;
case Keyboard.CODE_LANGUAGE_SWITCH:
handleLanguageSwitchKey();
break;
case Keyboard.CODE_RESEARCH:
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.getInstance().onResearchKeySelected(this);
}
break;
default:
mSpaceState = SPACE_STATE_NONE;
if (mCurrentSettings.isWordSeparator(primaryCode)) {
didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState);
} else {
if (SPACE_STATE_PHANTOM == spaceState) {
if (ProductionFlag.IS_INTERNAL) {
if (mWordComposer.isComposingWord() && mWordComposer.isBatchMode()) {
Stats.onAutoCorrection(
"", mWordComposer.getTypedWord(), " ", mWordComposer);
}
}
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
}
final int keyX, keyY;
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
if (keyboard != null && keyboard.hasProximityCharsCorrection(primaryCode)) {
keyX = x;
keyY = y;
} else {
keyX = Constants.NOT_A_COORDINATE;
keyY = Constants.NOT_A_COORDINATE;
}
handleCharacter(primaryCode, keyX, keyY, spaceState);
}
mExpectingUpdateSelection = true;
mShouldSwitchToLastSubtype = true;
break;
}
switcher.onCodeInput(primaryCode);
// Reset after any single keystroke, except shift and symbol-shift
if (!didAutoCorrect && primaryCode != Keyboard.CODE_SHIFT
&& primaryCode != Keyboard.CODE_SWITCH_ALPHA_SYMBOL)
mLastComposedWord.deactivate();
if (Keyboard.CODE_DELETE != primaryCode) {
mEnteredText = null;
}
mConnection.endBatchEdit();
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onCodeInput(primaryCode, x, y);
}
}
// Called from PointerTracker through the KeyboardActionListener interface
@Override
public void onTextInput(final CharSequence rawText) {
mConnection.beginBatchEdit();
if (mWordComposer.isComposingWord()) {
commitCurrentAutoCorrection(rawText.toString());
} else {
resetComposingState(true /* alsoResetLastComposedWord */);
}
mHandler.postUpdateSuggestionStrip();
final CharSequence text = specificTldProcessingOnTextInput(rawText);
if (SPACE_STATE_PHANTOM == mSpaceState) {
promotePhantomSpace();
}
mConnection.commitText(text, 1);
mConnection.endBatchEdit();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_NONE;
mKeyboardSwitcher.updateShiftState();
mKeyboardSwitcher.onCodeInput(Keyboard.CODE_OUTPUT_TEXT);
mEnteredText = text;
}
@Override
public void onStartBatchInput() {
BatchInputUpdater.getInstance().onStartBatchInput();
mConnection.beginBatchEdit();
if (mWordComposer.isComposingWord()) {
if (ProductionFlag.IS_INTERNAL) {
if (mWordComposer.isBatchMode()) {
Stats.onAutoCorrection("", mWordComposer.getTypedWord(), " ", mWordComposer);
}
}
if (mWordComposer.size() <= 1) {
// We auto-correct the previous (typed, not gestured) string iff it's one character
// long. The reason for this is, even in the middle of gesture typing, you'll still
// tap one-letter words and you want them auto-corrected (typically, "i" in English
// should become "I"). However for any longer word, we assume that the reason for
// tapping probably is that the word you intend to type is not in the dictionary,
// so we do not attempt to correct, on the assumption that if that was a dictionary
// word, the user would probably have gestured instead.
commitCurrentAutoCorrection(LastComposedWord.NOT_A_SEPARATOR);
} else {
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
}
mExpectingUpdateSelection = true;
// The following is necessary for the case where the user typed something but didn't
// manual pick it and didn't input any separator.
mSpaceState = SPACE_STATE_PHANTOM;
} else {
final int codePointBeforeCursor = mConnection.getCodePointBeforeCursor();
// TODO: reverse this logic. We should have the means to determine whether a character
// should usually be followed by a space, and it should be more readable.
if (Constants.NOT_A_CODE != codePointBeforeCursor
&& !Character.isWhitespace(codePointBeforeCursor)
&& !mCurrentSettings.isPhantomSpacePromotingSymbol(codePointBeforeCursor)
&& !mCurrentSettings.isWeakSpaceStripper(codePointBeforeCursor)) {
mSpaceState = SPACE_STATE_PHANTOM;
}
}
mConnection.endBatchEdit();
mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode());
}
private static final class BatchInputUpdater implements Handler.Callback {
private final Handler mHandler;
private LatinIME mLatinIme;
private boolean mInBatchInput; // synchornized using "this".
private BatchInputUpdater() {
final HandlerThread handlerThread = new HandlerThread(
BatchInputUpdater.class.getSimpleName());
handlerThread.start();
mHandler = new Handler(handlerThread.getLooper(), this);
}
// Initialization-on-demand holder
private static final class OnDemandInitializationHolder {
public static final BatchInputUpdater sInstance = new BatchInputUpdater();
}
public static BatchInputUpdater getInstance() {
return OnDemandInitializationHolder.sInstance;
}
private static final int MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 1;
@Override
public boolean handleMessage(final Message msg) {
switch (msg.what) {
case MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP:
updateBatchInput((InputPointers)msg.obj, mLatinIme);
break;
}
return true;
}
// Run in the UI thread.
public synchronized void onStartBatchInput() {
mInBatchInput = true;
}
// Run in the Handler thread.
private synchronized void updateBatchInput(final InputPointers batchPointers,
final LatinIME latinIme) {
if (!mInBatchInput) {
// Batch input has ended while the message was being delivered.
return;
}
final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(
batchPointers, latinIme);
latinIme.mHandler.showGesturePreviewAndSuggestionStrip(
suggestedWords, false /* dismissGestureFloatingPreviewText */);
}
// Run in the UI thread.
public void onUpdateBatchInput(final InputPointers batchPointers, final LatinIME latinIme) {
mLatinIme = latinIme;
if (mHandler.hasMessages(MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP)) {
return;
}
mHandler.obtainMessage(
MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, batchPointers)
.sendToTarget();
}
// Run in the UI thread.
public synchronized SuggestedWords onEndBatchInput(final InputPointers batchPointers,
final LatinIME latinIme) {
mInBatchInput = false;
final SuggestedWords suggestedWords = getSuggestedWordsGestureLocked(
batchPointers, latinIme);
latinIme.mHandler.showGesturePreviewAndSuggestionStrip(
suggestedWords, true /* dismissGestureFloatingPreviewText */);
return suggestedWords;
}
// {@link LatinIME#getSuggestedWords(int)} method calls with same session id have to
// be synchronized.
private static SuggestedWords getSuggestedWordsGestureLocked(
final InputPointers batchPointers, final LatinIME latinIme) {
latinIme.mWordComposer.setBatchInputPointers(batchPointers);
return latinIme.getSuggestedWords(Suggest.SESSION_GESTURE);
}
}
private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords,
final boolean dismissGestureFloatingPreviewText) {
final String batchInputText = (suggestedWords.size() > 0)
? suggestedWords.getWord(0) : null;
final KeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
mainKeyboardView.showGestureFloatingPreviewText(batchInputText);
showSuggestionStrip(suggestedWords, null);
if (dismissGestureFloatingPreviewText) {
mainKeyboardView.dismissGestureFloatingPreviewText();
}
}
@Override
public void onUpdateBatchInput(final InputPointers batchPointers) {
BatchInputUpdater.getInstance().onUpdateBatchInput(batchPointers, this);
}
@Override
public void onEndBatchInput(final InputPointers batchPointers) {
final SuggestedWords suggestedWords = BatchInputUpdater.getInstance().onEndBatchInput(
batchPointers, this);
final String batchInputText = (suggestedWords.size() > 0)
? suggestedWords.getWord(0) : null;
if (TextUtils.isEmpty(batchInputText)) {
return;
}
mWordComposer.setBatchInputWord(batchInputText);
mConnection.beginBatchEdit();
if (SPACE_STATE_PHANTOM == mSpaceState) {
promotePhantomSpace();
}
mConnection.setComposingText(batchInputText, 1);
mExpectingUpdateSelection = true;
mConnection.endBatchEdit();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_PHANTOM;
mKeyboardSwitcher.updateShiftState();
}
private CharSequence specificTldProcessingOnTextInput(final CharSequence text) {
if (text.length() <= 1 || text.charAt(0) != Keyboard.CODE_PERIOD
|| !Character.isLetter(text.charAt(1))) {
// Not a tld: do nothing.
return text;
}
// We have a TLD (or something that looks like this): make sure we don't add
// a space even if currently in phantom mode.
mSpaceState = SPACE_STATE_NONE;
// TODO: use getCodePointBeforeCursor instead to improve performance and simplify the code
final CharSequence lastOne = mConnection.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == Keyboard.CODE_PERIOD) {
return text.subSequence(1, text.length());
} else {
return text;
}
}
// Called from PointerTracker through the KeyboardActionListener interface
@Override
public void onCancelInput() {
// User released a finger outside any key
mKeyboardSwitcher.onCancelInput();
}
private void handleBackspace(final int spaceState) {
// In many cases, we may have to put the keyboard in auto-shift state again. However
// we want to wait a few milliseconds before doing it to avoid the keyboard flashing
// during key repeat.
mHandler.postUpdateShiftState();
if (mWordComposer.isComposingWord()) {
final int length = mWordComposer.size();
if (length > 0) {
// Immediately after a batch input.
if (SPACE_STATE_PHANTOM == spaceState) {
mWordComposer.reset();
} else {
mWordComposer.deleteLast();
}
mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
mHandler.postUpdateSuggestionStrip();
} else {
mConnection.deleteSurroundingText(1, 0);
}
} else {
if (mLastComposedWord.canRevertCommit()) {
if (ProductionFlag.IS_INTERNAL) {
Stats.onAutoCorrectionCancellation();
}
revertCommit();
return;
}
if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) {
// Cancel multi-character input: remove the text we just entered.
// This is triggered on backspace after a key that inputs multiple characters,
// like the smiley key or the .com key.
final int length = mEnteredText.length();
mConnection.deleteSurroundingText(length, 0);
mEnteredText = null;
// If we have mEnteredText, then we know that mHasUncommittedTypedChars == false.
// In addition we know that spaceState is false, and that we should not be
// reverting any autocorrect at this point. So we can safely return.
return;
}
if (SPACE_STATE_DOUBLE == spaceState) {
mHandler.cancelDoubleSpacesTimer();
if (mConnection.revertDoubleSpace()) {
// No need to reset mSpaceState, it has already be done (that's why we
// receive it as a parameter)
return;
}
} else if (SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
if (mConnection.revertSwapPunctuation()) {
// Likewise
return;
}
}
// No cancelling of commit/double space/swap: we have a regular backspace.
// We should backspace one char and restart suggestion if at the end of a word.
if (mLastSelectionStart != mLastSelectionEnd) {
// If there is a selection, remove it.
final int lengthToDelete = mLastSelectionEnd - mLastSelectionStart;
mConnection.setSelection(mLastSelectionEnd, mLastSelectionEnd);
mConnection.deleteSurroundingText(lengthToDelete, 0);
} else {
// There is no selection, just delete one character.
if (NOT_A_CURSOR_POSITION == mLastSelectionEnd) {
// This should never happen.
Log.e(TAG, "Backspace when we don't know the selection position");
}
// 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because
// we want to be able to compile against the Ice Cream Sandwich SDK.
if (mTargetApplicationInfo != null
&& mTargetApplicationInfo.targetSdkVersion < 16) {
// Backward compatibility mode. Before Jelly bean, the keyboard would simulate
// a hardware keyboard event on pressing enter or delete. This is bad for many
// reasons (there are race conditions with commits) but some applications are
// relying on this behavior so we continue to support it for older apps.
sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_DEL);
} else {
mConnection.deleteSurroundingText(1, 0);
}
if (mDeleteCount > DELETE_ACCELERATE_AT) {
mConnection.deleteSurroundingText(1, 0);
}
}
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
restartSuggestionsOnWordBeforeCursorIfAtEndOfWord();
}
}
}
private boolean maybeStripSpace(final int code,
final int spaceState, final boolean isFromSuggestionStrip) {
if (Keyboard.CODE_ENTER == code && SPACE_STATE_SWAP_PUNCTUATION == spaceState) {
mConnection.removeTrailingSpace();
return false;
} else if ((SPACE_STATE_WEAK == spaceState
|| SPACE_STATE_SWAP_PUNCTUATION == spaceState)
&& isFromSuggestionStrip) {
if (mCurrentSettings.isWeakSpaceSwapper(code)) {
return true;
} else {
if (mCurrentSettings.isWeakSpaceStripper(code)) {
mConnection.removeTrailingSpace();
}
return false;
}
} else {
return false;
}
}
private void handleCharacter(final int primaryCode, final int x,
final int y, final int spaceState) {
boolean isComposingWord = mWordComposer.isComposingWord();
if (SPACE_STATE_PHANTOM == spaceState &&
!mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) {
if (isComposingWord) {
// Sanity check
throw new RuntimeException("Should not be composing here");
}
promotePhantomSpace();
}
// NOTE: isCursorTouchingWord() is a blocking IPC call, so it often takes several
// dozen milliseconds. Avoid calling it as much as possible, since we are on the UI
// thread here.
if (!isComposingWord && (isAlphabet(primaryCode)
|| mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode))
&& mCurrentSettings.isSuggestionsRequested(mDisplayOrientation) &&
!mConnection.isCursorTouchingWord(mCurrentSettings)) {
// Reset entirely the composing state anyway, then start composing a new word unless
// the character is a single quote. The idea here is, single quote is not a
// separator and it should be treated as a normal character, except in the first
// position where it should not start composing a word.
isComposingWord = (Keyboard.CODE_SINGLE_QUOTE != primaryCode);
// Here we don't need to reset the last composed word. It will be reset
// when we commit this one, if we ever do; if on the other hand we backspace
// it entirely and resume suggestions on the previous word, we'd like to still
// have touch coordinates for it.
resetComposingState(false /* alsoResetLastComposedWord */);
}
if (isComposingWord) {
final int keyX, keyY;
if (KeyboardActionListener.Adapter.isInvalidCoordinate(x)
|| KeyboardActionListener.Adapter.isInvalidCoordinate(y)) {
keyX = x;
keyY = y;
} else {
final KeyDetector keyDetector =
mKeyboardSwitcher.getMainKeyboardView().getKeyDetector();
keyX = keyDetector.getTouchX(x);
keyY = keyDetector.getTouchY(y);
}
mWordComposer.add(primaryCode, keyX, keyY);
// If it's the first letter, make note of auto-caps state
if (mWordComposer.size() == 1) {
mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode());
}
mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1);
} else {
final boolean swapWeakSpace = maybeStripSpace(primaryCode,
spaceState, Constants.SUGGESTION_STRIP_COORDINATE == x);
sendKeyCodePoint(primaryCode);
if (swapWeakSpace) {
swapSwapperAndSpace();
mSpaceState = SPACE_STATE_WEAK;
}
// In case the "add to dictionary" hint was still displayed.
if (null != mSuggestionStripView) mSuggestionStripView.dismissAddToDictionaryHint();
}
mHandler.postUpdateSuggestionStrip();
if (ProductionFlag.IS_INTERNAL) {
Utils.Stats.onNonSeparator((char)primaryCode, x, y);
}
}
// Returns true if we did an autocorrection, false otherwise.
private boolean handleSeparator(final int primaryCode, final int x, final int y,
final int spaceState) {
boolean didAutoCorrect = false;
// Handle separator
if (mWordComposer.isComposingWord()) {
if (mCurrentSettings.mCorrectionEnabled) {
// TODO: maybe cache Strings in an <String> sparse array or something
commitCurrentAutoCorrection(new String(new int[]{primaryCode}, 0, 1));
didAutoCorrect = true;
} else {
commitTyped(new String(new int[]{primaryCode}, 0, 1));
}
}
final boolean swapWeakSpace = maybeStripSpace(primaryCode, spaceState,
Constants.SUGGESTION_STRIP_COORDINATE == x);
if (SPACE_STATE_PHANTOM == spaceState &&
mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
promotePhantomSpace();
}
sendKeyCodePoint(primaryCode);
if (Keyboard.CODE_SPACE == primaryCode) {
if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
if (maybeDoubleSpace()) {
mSpaceState = SPACE_STATE_DOUBLE;
} else if (!isShowingPunctuationList()) {
mSpaceState = SPACE_STATE_WEAK;
}
}
mHandler.startDoubleSpacesTimer();
if (!mConnection.isCursorTouchingWord(mCurrentSettings)) {
mHandler.postUpdateSuggestionStrip();
}
} else {
if (swapWeakSpace) {
swapSwapperAndSpace();
mSpaceState = SPACE_STATE_SWAP_PUNCTUATION;
} else if (SPACE_STATE_PHANTOM == spaceState
&& !mCurrentSettings.isWeakSpaceStripper(primaryCode)
&& !mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) {
// If we are in phantom space state, and the user presses a separator, we want to
// stay in phantom space state so that the next keypress has a chance to add the
// space. For example, if I type "Good dat", pick "day" from the suggestion strip
// then insert a comma and go on to typing the next word, I want the space to be
// inserted automatically before the next word, the same way it is when I don't
// input the comma.
// The case is a little different if the separator is a space stripper. Such a
// separator does not normally need a space on the right (that's the difference
// between swappers and strippers), so we should not stay in phantom space state if
// the separator is a stripper. Hence the additional test above.
mSpaceState = SPACE_STATE_PHANTOM;
}
// Set punctuation right away. onUpdateSelection will fire but tests whether it is
// already displayed or not, so it's okay.
setPunctuationSuggestions();
}
if (ProductionFlag.IS_INTERNAL) {
Utils.Stats.onSeparator((char)primaryCode, x, y);
}
mKeyboardSwitcher.updateShiftState();
return didAutoCorrect;
}
private CharSequence getTextWithUnderline(final CharSequence text) {
return mIsAutoCorrectionIndicatorOn
? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text)
: text;
}
private void handleClose() {
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
requestHideSelf(0);
final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView();
if (mainKeyboardView != null) {
mainKeyboardView.closing();
}
}
// TODO: make this private
// Outside LatinIME, only used by the test suite.
/* package for tests */
boolean isShowingPunctuationList() {
if (mSuggestionStripView == null) return false;
return mCurrentSettings.mSuggestPuncList == mSuggestionStripView.getSuggestions();
}
private boolean isSuggestionsStripVisible() {
if (mSuggestionStripView == null)
return false;
if (mSuggestionStripView.isShowingAddToDictionaryHint())
return true;
if (!mCurrentSettings.isSuggestionStripVisibleInOrientation(mDisplayOrientation))
return false;
if (mCurrentSettings.isApplicationSpecifiedCompletionsOn())
return true;
return mCurrentSettings.isSuggestionsRequested(mDisplayOrientation);
}
private void clearSuggestionStrip() {
setSuggestionStrip(SuggestedWords.EMPTY, false);
setAutoCorrectionIndicator(false);
}
private void setSuggestionStrip(final SuggestedWords words, final boolean isAutoCorrection) {
if (mSuggestionStripView != null) {
mSuggestionStripView.setSuggestions(words);
mKeyboardSwitcher.onAutoCorrectionStateChanged(isAutoCorrection);
}
}
private void setAutoCorrectionIndicator(final boolean newAutoCorrectionIndicator) {
// Put a blue underline to a word in TextView which will be auto-corrected.
if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator
&& mWordComposer.isComposingWord()) {
mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator;
final CharSequence textWithUnderline =
getTextWithUnderline(mWordComposer.getTypedWord());
// TODO: when called from an updateSuggestionStrip() call that results from a posted
// message, this is called outside any batch edit. Potentially, this may result in some
// janky flickering of the screen, although the display speed makes it unlikely in
// the practice.
mConnection.setComposingText(textWithUnderline, 1);
}
}
private void updateSuggestionStrip() {
mHandler.cancelUpdateSuggestionStrip();
// Check if we have a suggestion engine attached.
if (mSuggest == null || !mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) {
if (mWordComposer.isComposingWord()) {
Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not "
+ "requested!");
mWordComposer.setAutoCorrection(mWordComposer.getTypedWord());
}
return;
}
if (!mWordComposer.isComposingWord() && !mCurrentSettings.mBigramPredictionEnabled) {
setPunctuationSuggestions();
return;
}
final SuggestedWords suggestedWords = getSuggestedWords(Suggest.SESSION_TYPING);
final String typedWord = mWordComposer.getTypedWord();
showSuggestionStrip(suggestedWords, typedWord);
}
private SuggestedWords getSuggestedWords(final int sessionId) {
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
if (keyboard == null) {
return SuggestedWords.EMPTY;
}
final String typedWord = mWordComposer.getTypedWord();
// Get the word on which we should search the bigrams. If we are composing a word, it's
// whatever is *before* the half-committed word in the buffer, hence 2; if we aren't, we
// should just skip whitespace if any, so 1.
// TODO: this is slow (2-way IPC) - we should probably cache this instead.
final CharSequence prevWord =
mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators,
mWordComposer.isComposingWord() ? 2 : 1);
final SuggestedWords suggestedWords = mSuggest.getSuggestedWords(mWordComposer,
prevWord, keyboard.getProximityInfo(), mCurrentSettings.mCorrectionEnabled,
sessionId);
return maybeRetrieveOlderSuggestions(typedWord, suggestedWords);
}
private SuggestedWords maybeRetrieveOlderSuggestions(final CharSequence typedWord,
final SuggestedWords suggestedWords) {
// TODO: consolidate this into getSuggestedWords
// We update the suggestion strip only when we have some suggestions to show, i.e. when
// the suggestion count is > 1; else, we leave the old suggestions, with the typed word
// replaced with the new one. However, when the word is a dictionary word, or when the
// length of the typed word is 1 or 0 (after a deletion typically), we do want to remove the
// old suggestions. Also, if we are showing the "add to dictionary" hint, we need to
// revert to suggestions - although it is unclear how we can come here if it's displayed.
if (suggestedWords.size() > 1 || typedWord.length() <= 1
|| !suggestedWords.mTypedWordValid
|| mSuggestionStripView.isShowingAddToDictionaryHint()) {
return suggestedWords;
} else {
SuggestedWords previousSuggestions = mSuggestionStripView.getSuggestions();
if (previousSuggestions == mCurrentSettings.mSuggestPuncList) {
previousSuggestions = SuggestedWords.EMPTY;
}
final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions =
SuggestedWords.getTypedWordAndPreviousSuggestions(
typedWord, previousSuggestions);
return new SuggestedWords(typedWordAndPreviousSuggestions,
false /* typedWordValid */,
false /* hasAutoCorrectionCandidate */,
false /* isPunctuationSuggestions */,
true /* isObsoleteSuggestions */,
false /* isPrediction */);
}
}
private void showSuggestionStrip(final SuggestedWords suggestedWords,
final CharSequence typedWord) {
if (null == suggestedWords || suggestedWords.size() <= 0) {
clearSuggestionStrip();
return;
}
final CharSequence autoCorrection;
if (suggestedWords.size() > 0) {
if (suggestedWords.mWillAutoCorrect) {
autoCorrection = suggestedWords.getWord(1);
} else {
autoCorrection = typedWord;
}
} else {
autoCorrection = null;
}
mWordComposer.setAutoCorrection(autoCorrection);
final boolean isAutoCorrection = suggestedWords.willAutoCorrect();
setSuggestionStrip(suggestedWords, isAutoCorrection);
setAutoCorrectionIndicator(isAutoCorrection);
setSuggestionStripShown(isSuggestionsStripVisible());
}
private void commitCurrentAutoCorrection(final String separatorString) {
// Complete any pending suggestions query first
if (mHandler.hasPendingUpdateSuggestions()) {
updateSuggestionStrip();
}
final CharSequence typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull();
final String typedWord = mWordComposer.getTypedWord();
final CharSequence autoCorrection = (typedAutoCorrection != null)
? typedAutoCorrection : typedWord;
if (autoCorrection != null) {
if (TextUtils.isEmpty(typedWord)) {
throw new RuntimeException("We have an auto-correction but the typed word "
+ "is empty? Impossible! I must commit suicide.");
}
if (ProductionFlag.IS_INTERNAL) {
Stats.onAutoCorrection(
typedWord, autoCorrection.toString(), separatorString, mWordComposer);
}
mExpectingUpdateSelection = true;
commitChosenWord(autoCorrection, LastComposedWord.COMMIT_TYPE_DECIDED_WORD,
separatorString);
if (!typedWord.equals(autoCorrection)) {
// This will make the correction flash for a short while as a visual clue
// to the user that auto-correction happened. It has no other effect; in particular
// note that this won't affect the text inside the text field AT ALL: it only makes
// the segment of text starting at the supplied index and running for the length
// of the auto-correction flash. At this moment, the "typedWord" argument is
// ignored by TextView.
mConnection.commitCorrection(
new CorrectionInfo(mLastSelectionEnd - typedWord.length(),
typedWord, autoCorrection));
}
}
}
// Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener}
// interface
@Override
public void pickSuggestionManually(final int index, final CharSequence suggestion) {
final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
// If this is a punctuation picked from the suggestion strip, pass it to onCodeInput
if (suggestion.length() == 1 && isShowingPunctuationList()) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion("", suggestion.toString(), index, suggestedWords);
// Rely on onCodeInput to do the complicated swapping/stripping logic consistently.
final int primaryCode = suggestion.charAt(0);
onCodeInput(primaryCode,
Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_punctuationSuggestion(index, suggestion);
}
return;
}
mConnection.beginBatchEdit();
if (SPACE_STATE_PHANTOM == mSpaceState && suggestion.length() > 0
// In the batch input mode, a manually picked suggested word should just replace
// the current batch input text and there is no need for a phantom space.
&& !mWordComposer.isBatchMode()) {
int firstChar = Character.codePointAt(suggestion, 0);
if ((!mCurrentSettings.isWeakSpaceStripper(firstChar))
&& (!mCurrentSettings.isWeakSpaceSwapper(firstChar))) {
promotePhantomSpace();
}
}
if (mCurrentSettings.isApplicationSpecifiedCompletionsOn()
&& mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
if (mSuggestionStripView != null) {
mSuggestionStripView.clear();
}
mKeyboardSwitcher.updateShiftState();
resetComposingState(true /* alsoResetLastComposedWord */);
final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index];
mConnection.commitCompletion(completionInfo);
mConnection.endBatchEdit();
return;
}
// We need to log before we commit, because the word composer will store away the user
// typed word.
final String replacedWord = mWordComposer.getTypedWord().toString();
LatinImeLogger.logOnManualSuggestion(replacedWord,
suggestion.toString(), index, suggestedWords);
mExpectingUpdateSelection = true;
commitChosenWord(suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK,
LastComposedWord.NOT_A_SEPARATOR);
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion);
}
mConnection.endBatchEdit();
// Don't allow cancellation of manual pick
mLastComposedWord.deactivate();
// Space state must be updated before calling updateShiftState
mSpaceState = SPACE_STATE_PHANTOM;
mKeyboardSwitcher.updateShiftState();
// We should show the "Touch again to save" hint if the user pressed the first entry
// AND it's in none of our current dictionaries (main, user or otherwise).
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If the suggestion is not in the dictionary, the hint should be shown.
&& !AutoCorrection.isValidWord(mSuggest.getUnigramDictionaries(), suggestion, true);
if (ProductionFlag.IS_INTERNAL) {
Stats.onSeparator((char)Keyboard.CODE_SPACE,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
if (showingAddToDictionaryHint && mIsUserDictionaryAvailable) {
mSuggestionStripView.showAddToDictionaryHint(
suggestion, mCurrentSettings.mHintToSaveText);
} else {
// If we're not showing the "Touch again to save", then update the suggestion strip.
mHandler.postUpdateSuggestionStrip();
}
}
/**
* Commits the chosen word to the text field and saves it for later retrieval.
*/
private void commitChosenWord(final CharSequence chosenWord, final int commitType,
final String separatorString) {
final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions();
mConnection.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan(
this, chosenWord, suggestedWords, mIsMainDictionaryAvailable), 1);
// Add the word to the user history dictionary
final CharSequence prevWord = addToUserHistoryDictionary(chosenWord);
// TODO: figure out here if this is an auto-correct or if the best word is actually
// what user typed. Note: currently this is done much later in
// LastComposedWord#didCommitTypedWord by string equality of the remembered
// strings.
mLastComposedWord = mWordComposer.commitWord(commitType, chosenWord.toString(),
separatorString, prevWord);
}
private void setPunctuationSuggestions() {
if (mCurrentSettings.mBigramPredictionEnabled) {
clearSuggestionStrip();
} else {
setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false);
}
setAutoCorrectionIndicator(false);
setSuggestionStripShown(isSuggestionsStripVisible());
}
private CharSequence addToUserHistoryDictionary(final CharSequence suggestion) {
if (TextUtils.isEmpty(suggestion)) return null;
if (mSuggest == null) return null;
// If correction is not enabled, we don't add words to the user history dictionary.
// That's to avoid unintended additions in some sensitive fields, or fields that
// expect to receive non-words.
if (!mCurrentSettings.mCorrectionEnabled) return null;
final UserHistoryDictionary userHistoryDictionary = mUserHistoryDictionary;
if (userHistoryDictionary != null) {
final CharSequence prevWord
= mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, 2);
final String secondWord;
if (mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps()) {
secondWord = suggestion.toString().toLowerCase(
mSubtypeSwitcher.getCurrentSubtypeLocale());
} else {
secondWord = suggestion.toString();
}
// We demote unrecognized words (frequency < 0, below) by specifying them as "invalid".
// We don't add words with 0-frequency (assuming they would be profanity etc.).
final int maxFreq = AutoCorrection.getMaxFrequency(
mSuggest.getUnigramDictionaries(), suggestion);
if (maxFreq == 0) return null;
userHistoryDictionary.addToUserHistory(null == prevWord ? null : prevWord.toString(),
secondWord, maxFreq > 0);
return prevWord;
}
return null;
}
/**
* Check if the cursor is actually at the end of a word. If so, restart suggestions on this
* word, else do nothing.
*/
private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() {
final CharSequence word = mConnection.getWordBeforeCursorIfAtEndOfWord(mCurrentSettings);
if (null != word) {
restartSuggestionsOnWordBeforeCursor(word);
}
}
private void restartSuggestionsOnWordBeforeCursor(final CharSequence word) {
mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard());
final int length = word.length();
mConnection.deleteSurroundingText(length, 0);
mConnection.setComposingText(word, 1);
mHandler.postUpdateSuggestionStrip();
}
private void revertCommit() {
final CharSequence previousWord = mLastComposedWord.mPrevWord;
final String originallyTypedWord = mLastComposedWord.mTypedWord;
final CharSequence committedWord = mLastComposedWord.mCommittedWord;
final int cancelLength = committedWord.length();
final int separatorLength = LastComposedWord.getSeparatorLength(
mLastComposedWord.mSeparatorString);
// TODO: should we check our saved separator against the actual contents of the text view?
final int deleteLength = cancelLength + separatorLength;
if (DEBUG) {
if (mWordComposer.isComposingWord()) {
throw new RuntimeException("revertCommit, but we are composing a word");
}
final String wordBeforeCursor =
mConnection.getTextBeforeCursor(deleteLength, 0)
.subSequence(0, cancelLength).toString();
if (!TextUtils.equals(committedWord, wordBeforeCursor)) {
throw new RuntimeException("revertCommit check failed: we thought we were "
+ "reverting \"" + committedWord
+ "\", but before the cursor we found \"" + wordBeforeCursor + "\"");
}
}
mConnection.deleteSurroundingText(deleteLength, 0);
if (!TextUtils.isEmpty(previousWord) && !TextUtils.isEmpty(committedWord)) {
mUserHistoryDictionary.cancelAddingUserHistory(
previousWord.toString(), committedWord.toString());
}
mConnection.commitText(originallyTypedWord + mLastComposedWord.mSeparatorString, 1);
if (ProductionFlag.IS_INTERNAL) {
Stats.onSeparator(mLastComposedWord.mSeparatorString,
Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE);
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_revertCommit(originallyTypedWord);
}
// Don't restart suggestion yet. We'll restart if the user deletes the
// separator.
mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD;
// We have a separator between the word and the cursor: we should show predictions.
mHandler.postUpdateSuggestionStrip();
}
// This essentially inserts a space, and that's it.
public void promotePhantomSpace() {
sendKeyCodePoint(Keyboard.CODE_SPACE);
}
// Used by the RingCharBuffer
public boolean isWordSeparator(final int code) {
return mCurrentSettings.isWordSeparator(code);
}
// TODO: Make this private
// Outside LatinIME, only used by the {@link InputTestsBase} test suite.
/* package for test */
void loadKeyboard() {
// When the device locale is changed in SetupWizard etc., this method may get called via
// onConfigurationChanged before SoftInputWindow is shown.
initSuggest();
loadSettings();
if (mKeyboardSwitcher.getMainKeyboardView() != null) {
// Reload keyboard because the current language has been changed.
mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mCurrentSettings);
}
// Since we just changed languages, we should re-evaluate suggestions with whatever word
// we are currently composing. If we are not composing anything, we may want to display
// predictions or punctuation signs (which is done by the updateSuggestionStrip anyway).
mHandler.postUpdateSuggestionStrip();
}
// TODO: Remove this method from {@link LatinIME} and move {@link FeedbackManager} to
// {@link KeyboardSwitcher}. Called from KeyboardSwitcher
public void hapticAndAudioFeedback(final int primaryCode) {
mFeedbackManager.hapticAndAudioFeedback(
primaryCode, mKeyboardSwitcher.getMainKeyboardView());
}
// Callback called by PointerTracker through the KeyboardActionListener. This is called when a
// key is depressed; release matching call is onReleaseKey below.
@Override
public void onPressKey(final int primaryCode) {
mKeyboardSwitcher.onPressKey(primaryCode);
}
// Callback by PointerTracker through the KeyboardActionListener. This is called when a key
// is released; press matching call is onPressKey above.
@Override
public void onReleaseKey(final int primaryCode, final boolean withSliding) {
mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding);
// If accessibility is on, ensure the user receives keyboard state updates.
if (AccessibilityUtils.getInstance().isTouchExplorationEnabled()) {
switch (primaryCode) {
case Keyboard.CODE_SHIFT:
AccessibleKeyboardViewProxy.getInstance().notifyShiftState();
break;
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
AccessibleKeyboardViewProxy.getInstance().notifySymbolsState();
break;
}
}
if (Keyboard.CODE_DELETE == primaryCode) {
// This is a stopgap solution to avoid leaving a high surrogate alone in a text view.
// In the future, we need to deprecate deteleSurroundingText() and have a surrogate
// pair-friendly way of deleting characters in InputConnection.
// TODO: use getCodePointBeforeCursor instead to improve performance
final CharSequence lastChar = mConnection.getTextBeforeCursor(1, 0);
if (!TextUtils.isEmpty(lastChar) && Character.isHighSurrogate(lastChar.charAt(0))) {
mConnection.deleteSurroundingText(1, 0);
}
}
}
// receive ringer mode change and network state change.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mSubtypeSwitcher.onNetworkStateChanged(intent);
} else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
mFeedbackManager.onRingerModeChanged();
}
}
};
private void launchSettings() {
handleClose();
launchSubActivity(SettingsActivity.class);
}
// Called from debug code only
public void launchDebugSettings() {
handleClose();
launchSubActivity(DebugSettingsActivity.class);
}
public void launchKeyboardedDialogActivity(final Class<? extends Activity> activityClass) {
// Put the text in the attached EditText into a safe, saved state before switching to a
// new activity that will also use the soft keyboard.
commitTyped(LastComposedWord.NOT_A_SEPARATOR);
launchSubActivity(activityClass);
}
private void launchSubActivity(final Class<? extends Activity> activityClass) {
Intent intent = new Intent();
intent.setClass(LatinIME.this, activityClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showSubtypeSelectorAndSettings() {
final CharSequence title = getString(R.string.english_ime_input_options);
final CharSequence[] items = new CharSequence[] {
// TODO: Should use new string "Select active input modes".
getString(R.string.language_selection_title),
getString(R.string.english_ime_settings),
};
final Context context = this;
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case 0:
Intent intent = CompatUtils.getInputLanguageSelectionIntent(
ImfUtils.getInputMethodIdOfThisIme(context),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case 1:
launchSettings();
break;
}
}
};
final AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setItems(items, listener)
.setTitle(title);
showOptionDialog(builder.create());
}
public void showOptionDialog(final AlertDialog dialog) {
final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken();
if (windowToken == null) {
return;
}
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
final Window window = dialog.getWindow();
final WindowManager.LayoutParams lp = window.getAttributes();
lp.token = windowToken;
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog = dialog;
dialog.show();
}
public void debugDumpStateAndCrashWithException(final String context) {
final StringBuilder s = new StringBuilder();
s.append("Target application : ").append(mTargetApplicationInfo.name)
.append("\nPackage : ").append(mTargetApplicationInfo.packageName)
.append("\nTarget app sdk version : ")
.append(mTargetApplicationInfo.targetSdkVersion)
.append("\nAttributes : ").append(mCurrentSettings.getInputAttributesDebugString())
.append("\nContext : ").append(context);
throw new RuntimeException(s.toString());
}
@Override
protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
final Keyboard keyboard = mKeyboardSwitcher.getKeyboard();
final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1;
p.println(" Keyboard mode = " + keyboardMode);
p.println(" mIsSuggestionsSuggestionsRequested = "
+ mCurrentSettings.isSuggestionsRequested(mDisplayOrientation));
p.println(" mCorrectionEnabled=" + mCurrentSettings.mCorrectionEnabled);
p.println(" isComposingWord=" + mWordComposer.isComposingWord());
p.println(" mSoundOn=" + mCurrentSettings.mSoundOn);
p.println(" mVibrateOn=" + mCurrentSettings.mVibrateOn);
p.println(" mKeyPreviewPopupOn=" + mCurrentSettings.mKeyPreviewPopupOn);
p.println(" inputAttributes=" + mCurrentSettings.getInputAttributesDebugString());
}
}
| false | true | private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInputView(editorInfo, restarting);
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
if (editorInfo == null) {
Log.e(TAG, "Null EditorInfo in onStartInputView()");
if (LatinImeLogger.sDBG) {
throw new NullPointerException("Null EditorInfo in onStartInputView()");
}
return;
}
if (DEBUG) {
Log.d(TAG, "onStartInputView: editorInfo:"
+ String.format("inputType=0x%08x imeOptions=0x%08x",
editorInfo.inputType, editorInfo.imeOptions));
Log.d(TAG, "All caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
+ ", sentence caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
+ ", word caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
}
if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
}
if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
}
mTargetApplicationInfo =
TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName);
if (null == mTargetApplicationInfo) {
new TargetApplicationGetter(this /* context */, this /* listener */)
.execute(editorInfo.packageName);
}
LatinImeLogger.onStartInputView(editorInfo);
// In landscape mode, this method gets called without the input view being created.
if (mainKeyboardView == null) {
return;
}
// Forward this event to the accessibility utilities, if enabled.
final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
if (accessUtils.isTouchExplorationEnabled()) {
accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
}
final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart
|| mLastSelectionEnd != editorInfo.initialSelEnd;
final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo);
final boolean isDifferentTextField = !restarting || inputTypeChanged;
if (isDifferentTextField) {
final boolean currentSubtypeEnabled = mSubtypeSwitcher
.updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
if (!currentSubtypeEnabled) {
// Current subtype is disabled. Needs to update subtype and keyboard.
final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype(
this, mSubtypeSwitcher.getNoLanguageSubtype());
mSubtypeSwitcher.updateSubtype(newSubtype);
loadKeyboard();
}
}
// The EditorInfo might have a flag that affects fullscreen mode.
// Note: This call should be done by InputMethodService?
updateFullscreenMode();
mApplicationSpecifiedCompletions = null;
// The app calling setText() has the effect of clearing the composing
// span, so we should reset our state unconditionally, even if restarting is true.
mEnteredText = null;
resetComposingState(true /* alsoResetLastComposedWord */);
mDeleteCount = 0;
mSpaceState = SPACE_STATE_NONE;
if (mSuggestionStripView != null) {
// This will set the punctuation suggestions if next word suggestion is off;
// otherwise it will clear the suggestion strip.
setPunctuationSuggestions();
}
mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart);
if (isDifferentTextField) {
mainKeyboardView.closing();
loadSettings();
if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
switcher.loadKeyboard(editorInfo, mCurrentSettings);
} else if (restarting) {
// TODO: Come up with a more comprehensive way to reset the keyboard layout when
// a keyboard layout set doesn't get reloaded in this method.
switcher.resetKeyboardStateToAlphabet();
}
setSuggestionStripShownInternal(
isSuggestionsStripVisible(), /* needsInputViewShown */ false);
mLastSelectionStart = editorInfo.initialSelStart;
mLastSelectionEnd = editorInfo.initialSelEnd;
// If we come here something in the text state is very likely to have changed.
// We should update the shift state regardless of whether we are restarting or not, because
// this is not perceived as a layout change that may be disruptive like we may have with
// switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the
// field gets emptied and we need to re-evaluate the shift state, but not the whole layout
// which would be disruptive.
// Space state must be updated before calling updateShiftState
mKeyboardSwitcher.updateShiftState();
mHandler.cancelUpdateSuggestionStrip();
mHandler.cancelDoubleSpacesTimer();
mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable);
mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
mCurrentSettings.mKeyPreviewPopupDismissDelay);
mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled);
mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled,
mCurrentSettings.mGestureFloatingPreviewTextEnabled);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
| private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) {
super.onStartInputView(editorInfo, restarting);
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView();
if (editorInfo == null) {
Log.e(TAG, "Null EditorInfo in onStartInputView()");
if (LatinImeLogger.sDBG) {
throw new NullPointerException("Null EditorInfo in onStartInputView()");
}
return;
}
if (DEBUG) {
Log.d(TAG, "onStartInputView: editorInfo:"
+ String.format("inputType=0x%08x imeOptions=0x%08x",
editorInfo.inputType, editorInfo.imeOptions));
Log.d(TAG, "All caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0)
+ ", sentence caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0)
+ ", word caps = "
+ ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0));
}
if (ProductionFlag.IS_EXPERIMENTAL) {
ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs);
}
if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead");
}
if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) {
Log.w(TAG, "Deprecated private IME option specified: "
+ editorInfo.privateImeOptions);
Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead");
}
mTargetApplicationInfo =
TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName);
if (null == mTargetApplicationInfo) {
new TargetApplicationGetter(this /* context */, this /* listener */)
.execute(editorInfo.packageName);
}
LatinImeLogger.onStartInputView(editorInfo);
// In landscape mode, this method gets called without the input view being created.
if (mainKeyboardView == null) {
return;
}
// Forward this event to the accessibility utilities, if enabled.
final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance();
if (accessUtils.isTouchExplorationEnabled()) {
accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting);
}
final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo);
final boolean isDifferentTextField = !restarting || inputTypeChanged;
if (isDifferentTextField) {
final boolean currentSubtypeEnabled = mSubtypeSwitcher
.updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled();
if (!currentSubtypeEnabled) {
// Current subtype is disabled. Needs to update subtype and keyboard.
final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype(
this, mSubtypeSwitcher.getNoLanguageSubtype());
mSubtypeSwitcher.updateSubtype(newSubtype);
loadKeyboard();
}
}
// The EditorInfo might have a flag that affects fullscreen mode.
// Note: This call should be done by InputMethodService?
updateFullscreenMode();
mApplicationSpecifiedCompletions = null;
// The app calling setText() has the effect of clearing the composing
// span, so we should reset our state unconditionally, even if restarting is true.
mEnteredText = null;
resetComposingState(true /* alsoResetLastComposedWord */);
mDeleteCount = 0;
mSpaceState = SPACE_STATE_NONE;
if (mSuggestionStripView != null) {
// This will set the punctuation suggestions if next word suggestion is off;
// otherwise it will clear the suggestion strip.
setPunctuationSuggestions();
}
mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart);
if (isDifferentTextField) {
mainKeyboardView.closing();
loadSettings();
if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) {
mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold);
}
switcher.loadKeyboard(editorInfo, mCurrentSettings);
} else if (restarting) {
// TODO: Come up with a more comprehensive way to reset the keyboard layout when
// a keyboard layout set doesn't get reloaded in this method.
switcher.resetKeyboardStateToAlphabet();
// In apps like Talk, we come here when the text is sent and the field gets emptied and
// we need to re-evaluate the shift state, but not the whole layout which would be
// disruptive.
// Space state must be updated before calling updateShiftState
switcher.updateShiftState();
}
setSuggestionStripShownInternal(
isSuggestionsStripVisible(), /* needsInputViewShown */ false);
mLastSelectionStart = editorInfo.initialSelStart;
mLastSelectionEnd = editorInfo.initialSelEnd;
mHandler.cancelUpdateSuggestionStrip();
mHandler.cancelDoubleSpacesTimer();
mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable);
mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn,
mCurrentSettings.mKeyPreviewPopupDismissDelay);
mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled);
mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled,
mCurrentSettings.mGestureFloatingPreviewTextEnabled);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
|
diff --git a/src/com/urbanairship/octobot/QueueConsumer.java b/src/com/urbanairship/octobot/QueueConsumer.java
index 929e76c..5b1baa3 100644
--- a/src/com/urbanairship/octobot/QueueConsumer.java
+++ b/src/com/urbanairship/octobot/QueueConsumer.java
@@ -1,270 +1,274 @@
package com.urbanairship.octobot;
// AMQP Support
import java.io.IOException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
// Beanstalk Support
import com.surftools.BeanstalkClient.BeanstalkException;
import com.surftools.BeanstalkClient.Job;
import com.surftools.BeanstalkClientImpl.ClientImpl;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
// This thread opens a streaming connection to a queue, which continually
// pushes messages to Octobot queue workers. The tasks contained within these
// messages are invoked, then acknowledged and removed from the queue.
public class QueueConsumer implements Runnable {
Queue queue = null;
Channel channel = null;
Connection connection = null;
QueueingConsumer consumer = null;
private final Logger logger = Logger.getLogger("Queue Consumer");
private boolean enableEmailErrors = Settings.getAsBoolean("Octobot", "email_enabled");
// Initialize the consumer with a queue object (AMQP, Beanstalk, or Redis).
public QueueConsumer(Queue queue) {
this.queue = queue;
}
// Fire up the appropriate queue listener and begin invoking tasks!.
public void run() {
if (queue.queueType.equals("amqp")) {
channel = getAMQPChannel(queue);
consumeFromAMQP();
} else if (queue.queueType.equals("beanstalk")) {
consumeFromBeanstalk();
} else if (queue.queueType.equals("redis")) {
consumeFromRedis();
} else {
logger.error("Invalid queue type specified: " + queue.queueType);
}
}
// Attempts to register to receive streaming messages from RabbitMQ.
// In the event that RabbitMQ is unavailable the call to getChannel()
// will attempt to reconnect. If it fails, the loop simply repeats.
private void consumeFromAMQP() {
while (true) {
QueueingConsumer.Delivery task = null;
try { task = consumer.nextDelivery(); }
catch (Exception e){
logger.error("Error in AMQP connection; reconnecting.", e);
channel = getAMQPChannel(queue);
continue;
}
// If we've got a message, fetch the body and invoke the task.
// Then, send an acknowledgement back to RabbitMQ that we got it.
if (task != null && task.getBody() != null) {
invokeTask(new String(task.getBody()));
try { channel.basicAck(task.getEnvelope().getDeliveryTag(), false); }
catch (IOException e) { logger.error("Error ack'ing message.", e); }
}
}
}
// Attempt to register to receive messages from Beanstalk and invoke tasks.
private void consumeFromBeanstalk() {
ClientImpl beanstalkClient = new ClientImpl(queue.host, queue.port);
beanstalkClient.watch(queue.queueName);
beanstalkClient.useTube(queue.queueName);
logger.info("Connected to Beanstalk; waiting for jobs.");
while (true) {
Job job = null;
try { job = beanstalkClient.reserve(1); }
catch (BeanstalkException e) {
logger.error("Beanstalk connection error.", e);
beanstalkClient = Beanstalk.getBeanstalkChannel(queue.host,
queue.port, queue.queueName);
continue;
}
if (job != null) {
String message = new String(job.getData());
try { invokeTask(message); }
catch (Exception e) { logger.error("Error handling message.", e); }
try { beanstalkClient.delete(job.getJobId()); }
catch (BeanstalkException e) {
logger.error("Error sending message receipt.", e);
beanstalkClient = Beanstalk.getBeanstalkChannel(queue.host,
queue.port, queue.queueName);
}
}
}
}
private void consumeFromRedis() {
logger.info("Connecting to Redis...");
Jedis jedis = new Jedis(queue.host, queue.port);
try {
jedis.connect();
} catch (IOException e) {
logger.error("Unable to connect to Redis.", e);
}
logger.info("Connected to Redis.");
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
invokeTask(message);
}
@Override
public void onPMessage(String string, String string1, String string2) {
logger.info("onPMessage Triggered - Not implemented.");
}
@Override
public void onSubscribe(String string, int i) {
logger.info("onSubscribe called - Not implemented.");
}
@Override
public void onUnsubscribe(String string, int i) {
logger.info("onUnsubscribe Called - Not implemented.");
}
@Override
public void onPUnsubscribe(String string, int i) {
logger.info("onPUnsubscribe called - Not implemented.");
}
@Override
public void onPSubscribe(String string, int i) {
logger.info("onPSubscribe Triggered - Not implemented.");
}
}, queue.queueName);
}
// Invokes a task based on the name of the task passed in the message via
// reflection, accounting for non-existent tasks and errors while running.
public boolean invokeTask(String rawMessage) {
String taskName = "";
JSONObject message;
int retryCount = 0;
long retryTimes = 0;
long startedAt = System.nanoTime();
String errorMessage = null;
Throwable lastException = null;
boolean executedSuccessfully = false;
while (retryCount < retryTimes + 1) {
if (retryCount > 0)
logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes);
try {
message = (JSONObject) JSONValue.parse(rawMessage);
taskName = (String) message.get("task");
if (message.containsKey("retries"))
retryTimes = (Long) message.get("retries");
} catch (Exception e) {
logger.error("Error: Invalid message received: " + rawMessage);
return executedSuccessfully;
}
// Locate the task, then invoke it, supplying our message.
// Cache methods after lookup to avoid unnecessary reflection lookups.
try {
TaskExecutor.execute(taskName, message);
executedSuccessfully = true;
} catch (ClassNotFoundException e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage);
+ } catch (NoClassDefFoundError e) {
+ lastException = e;
+ errorMessage = "Error: Task requested not found: " + taskName;
+ logger.error(errorMessage, e);
} catch (NoSuchMethodException e) {
lastException = e;
errorMessage = "Error: Task requested does not have a static run method.";
logger.error(errorMessage);
} catch (Exception e) {
lastException = e;
errorMessage = "An error occurred while running the task.";
logger.error(errorMessage, e);
}
if (executedSuccessfully) break;
else retryCount++;
}
// Deliver an e-mail error notification if enabled.
if (enableEmailErrors && !executedSuccessfully) {
String email = "Error running task: " + taskName + ".\n\n"
+ "Attempted executing " + retryCount + " times as specified.\n\n"
+ "The original input was: \n\n" + rawMessage + "\n\n"
+ "Here's the error that resulted while running the task:\n\n"
+ stackToString(lastException);
try { MailQueue.put(email); }
catch (InterruptedException e) { }
}
long finishedAt = System.nanoTime();
Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount);
return executedSuccessfully;
}
// Opens up a connection to RabbitMQ, retrying every five seconds
// if the queue server is unavailable.
private Channel getAMQPChannel(Queue queue) {
int attempts = 0;
logger.info("Opening connection to AMQP / " + queue.queueName + "...");
while (true) {
attempts++;
logger.debug("Attempt #" + attempts);
try {
connection = new RabbitMQ(queue).getConnection();
channel = connection.createChannel();
consumer = new QueueingConsumer(channel);
channel.exchangeDeclare(queue.queueName, "direct", true);
channel.queueDeclare(queue.queueName, true, false, false, null);
channel.queueBind(queue.queueName, queue.queueName, queue.queueName);
channel.basicConsume(queue.queueName, false, consumer);
logger.info("Connected to RabbitMQ");
return channel;
} catch (Exception e) {
logger.error("Cannot connect to AMQP. Retrying in 5 sec.", e);
try { Thread.sleep(1000 * 5); }
catch (InterruptedException ex) { }
}
}
}
// Converts a stacktrace from task invocation to a string for error logging.
public String stackToString(Throwable e) {
if (e == null) return "(Null)";
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}
}
| true | true | public boolean invokeTask(String rawMessage) {
String taskName = "";
JSONObject message;
int retryCount = 0;
long retryTimes = 0;
long startedAt = System.nanoTime();
String errorMessage = null;
Throwable lastException = null;
boolean executedSuccessfully = false;
while (retryCount < retryTimes + 1) {
if (retryCount > 0)
logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes);
try {
message = (JSONObject) JSONValue.parse(rawMessage);
taskName = (String) message.get("task");
if (message.containsKey("retries"))
retryTimes = (Long) message.get("retries");
} catch (Exception e) {
logger.error("Error: Invalid message received: " + rawMessage);
return executedSuccessfully;
}
// Locate the task, then invoke it, supplying our message.
// Cache methods after lookup to avoid unnecessary reflection lookups.
try {
TaskExecutor.execute(taskName, message);
executedSuccessfully = true;
} catch (ClassNotFoundException e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage);
} catch (NoSuchMethodException e) {
lastException = e;
errorMessage = "Error: Task requested does not have a static run method.";
logger.error(errorMessage);
} catch (Exception e) {
lastException = e;
errorMessage = "An error occurred while running the task.";
logger.error(errorMessage, e);
}
if (executedSuccessfully) break;
else retryCount++;
}
// Deliver an e-mail error notification if enabled.
if (enableEmailErrors && !executedSuccessfully) {
String email = "Error running task: " + taskName + ".\n\n"
+ "Attempted executing " + retryCount + " times as specified.\n\n"
+ "The original input was: \n\n" + rawMessage + "\n\n"
+ "Here's the error that resulted while running the task:\n\n"
+ stackToString(lastException);
try { MailQueue.put(email); }
catch (InterruptedException e) { }
}
long finishedAt = System.nanoTime();
Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount);
return executedSuccessfully;
}
| public boolean invokeTask(String rawMessage) {
String taskName = "";
JSONObject message;
int retryCount = 0;
long retryTimes = 0;
long startedAt = System.nanoTime();
String errorMessage = null;
Throwable lastException = null;
boolean executedSuccessfully = false;
while (retryCount < retryTimes + 1) {
if (retryCount > 0)
logger.info("Retrying task. Attempt " + retryCount + " of " + retryTimes);
try {
message = (JSONObject) JSONValue.parse(rawMessage);
taskName = (String) message.get("task");
if (message.containsKey("retries"))
retryTimes = (Long) message.get("retries");
} catch (Exception e) {
logger.error("Error: Invalid message received: " + rawMessage);
return executedSuccessfully;
}
// Locate the task, then invoke it, supplying our message.
// Cache methods after lookup to avoid unnecessary reflection lookups.
try {
TaskExecutor.execute(taskName, message);
executedSuccessfully = true;
} catch (ClassNotFoundException e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage);
} catch (NoClassDefFoundError e) {
lastException = e;
errorMessage = "Error: Task requested not found: " + taskName;
logger.error(errorMessage, e);
} catch (NoSuchMethodException e) {
lastException = e;
errorMessage = "Error: Task requested does not have a static run method.";
logger.error(errorMessage);
} catch (Exception e) {
lastException = e;
errorMessage = "An error occurred while running the task.";
logger.error(errorMessage, e);
}
if (executedSuccessfully) break;
else retryCount++;
}
// Deliver an e-mail error notification if enabled.
if (enableEmailErrors && !executedSuccessfully) {
String email = "Error running task: " + taskName + ".\n\n"
+ "Attempted executing " + retryCount + " times as specified.\n\n"
+ "The original input was: \n\n" + rawMessage + "\n\n"
+ "Here's the error that resulted while running the task:\n\n"
+ stackToString(lastException);
try { MailQueue.put(email); }
catch (InterruptedException e) { }
}
long finishedAt = System.nanoTime();
Metrics.update(taskName, finishedAt - startedAt, executedSuccessfully, retryCount);
return executedSuccessfully;
}
|
diff --git a/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java b/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java
index e460c50e..21cda73d 100644
--- a/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java
+++ b/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java
@@ -1,9544 +1,9547 @@
/* @(#)BasicJideTabbedPaneUI.java
*
* Copyright 2002 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.plaf.basic;
import com.jidesoft.plaf.JideTabbedPaneUI;
import com.jidesoft.plaf.UIDefaultsLookup;
import com.jidesoft.popup.JidePopup;
import com.jidesoft.swing.JideSwingUtilities;
import com.jidesoft.swing.JideTabbedPane;
import com.jidesoft.swing.PartialLineBorder;
import com.jidesoft.swing.Sticky;
import com.jidesoft.utils.PortingUtils;
import com.jidesoft.utils.SecurityUtils;
import com.jidesoft.utils.SystemInfo;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;
import java.awt.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Vector;
/**
* A basic L&f implementation of JideTabbedPaneUI
*/
public class BasicJideTabbedPaneUI extends JideTabbedPaneUI implements SwingConstants, DocumentListener {
// pixels
protected int _tabRectPadding;// distance from tab rect to icon/text
protected int _closeButtonMarginHorizon; // when tab is on top or bottom, and each tab has close button, the gap around the close button
protected int _closeButtonMarginVertical;// when tab is on left or right, and each tab has close button, the gap around the close button
protected int _textMarginVertical;// tab area and text area gap
protected int _noIconMargin;// gap around text area when there is no icon
protected int _iconMargin;// distance from icon to tab rect start x
protected int _textPadding;// distance from text to tab rect start
protected int _buttonSize;// scroll button size
protected int _buttonMargin;// scroll button margin
protected int _fitStyleBoundSize;// margin for the whole tab area
protected int _fitStyleFirstTabMargin;// the first tab position
protected int _fitStyleIconMinWidth;// minimum width to display icon
protected int _fitStyleTextMinWidth;// minimum width to display text
protected int _compressedStyleNoIconRectSize;// tab size when there is no icon and tab not selected
protected int _compressedStyleIconMargin;// margin around icon
protected int _compressedStyleCloseButtonMarginHorizon;// the close button margin on the left or right when the tab is on the top or bottom
protected int _compressedStyleCloseButtonMarginVertical;// the close button margin on the top or bottom when the tab is on the left or right
protected int _fixedStyleRectSize;// tab rect size
protected int _closeButtonMargin;// margin around close button
protected int _gripLeftMargin;// left margin
protected int _closeButtonMarginSize;// margin around the close button
protected int _closeButtonLeftMargin;// the close button gap when the tab is on the left
protected int _closeButtonRightMargin;// the close button gap when the tab is on the right
protected Component _tabLeadingComponent = null;
protected Component _tabTrailingComponent = null;
protected JideTabbedPane _tabPane;
protected Color _tabBackground;
protected Color _background;
protected Color _highlight;
protected Color _lightHighlight;
protected Color _shadow;
protected Color _darkShadow;
protected Color _focus;
protected Color _inactiveTabForeground;
protected Color _activeTabForeground;
protected Color _tabListBackground;
protected Color _selectedColor;
protected int _textIconGap;
protected int _tabRunOverlay;
protected boolean _showIconOnTab;
protected boolean _showCloseButtonOnTab;
protected int _closeButtonAlignment = SwingConstants.TRAILING;
protected Insets _tabInsets;
protected Insets _selectedTabPadInsets;
protected Insets _tabAreaInsets;
protected boolean _ignoreContentBorderInsetsIfNoTabs;
// Transient variables (recalculated each time TabbedPane is laid out)
protected int _tabRuns[] = new int[10];
protected int _runCount = 0;
protected int _selectedRun = -1;
protected Rectangle _rects[] = new Rectangle[0];
protected int _maxTabHeight;
protected int _maxTabWidth;
protected int _gripperWidth = 6;
protected int _gripperHeight = 6;
// Listeners
protected ChangeListener _tabChangeListener;
protected FocusListener _tabFocusListener;
protected PropertyChangeListener _propertyChangeListener;
protected MouseListener _mouseListener;
protected MouseMotionListener _mousemotionListener;
protected MouseWheelListener _mouseWheelListener;
// PENDING(api): See comment for ContainerHandler
private ContainerListener _containerListener;
private ComponentListener _componentListener;
// Private instance data
private Insets _currentTabInsets = new Insets(0, 0, 0, 0);
private Insets _currentPadInsets = new Insets(0, 0, 0, 0);
private Insets _currentTabAreaInsets = new Insets(2, 4, 0, 4);
private Insets _currentContentBorderInsets = new Insets(3, 0, 0, 0);
private Component visibleComponent;
// PENDING(api): See comment for ContainerHandler
private Vector htmlViews;
private Hashtable _mnemonicToIndexMap;
/**
* InputMap used for mnemonics. Only non-null if the JTabbedPane has mnemonics associated with it. Lazily created in
* initMnemonics.
*/
private InputMap _mnemonicInputMap;
// For use when tabLayoutPolicy = SCROLL_TAB_LAYOUT
public ScrollableTabSupport _tabScroller;
/**
* A rectangle used for general layout calculations in order to avoid constructing many new Rectangles on the fly.
*/
protected transient Rectangle _calcRect = new Rectangle(0, 0, 0, 0);
/**
* Number of tabs. When the count differs, the mnemonics are updated.
*/
// PENDING: This wouldn't be necessary if JTabbedPane had a better
// way of notifying listeners when the count changed.
protected int _tabCount;
protected TabCloseButton[] _closeButtons;
// UI creation
private ThemePainter _painter;
private Painter _gripperPainter;
private DropTargetListener _dropListener;
public DropTarget _dt;
// the left margin of the first tab according to the style
public static final int DEFAULT_LEFT_MARGIN = 0;
public static final int OFFICE2003_LEFT_MARGIN = 18;
public static final int EXCEL_LEFT_MARGIN = 6;
protected int _rectSizeExtend = 0;//when the style is eclipse,
//we should extend the size of the rects for hold the title
protected Polygon tabRegion = null;
protected Color _selectColor1 = null;
protected Color _selectColor2 = null;
protected Color _selectColor3 = null;
protected Color _unselectColor1 = null;
protected Color _unselectColor2 = null;
protected Color _unselectColor3 = null;
protected Color _officeTabBorderColor;
protected Color _defaultTabBorderShadowColor;
protected boolean _mouseEnter = false;
protected int _indexMouseOver = -1;
protected boolean _alwaysShowLineBorder = false;
protected boolean _showFocusIndicator = false;
public static final String BUTTON_NAME_CLOSE = "JideTabbedPane.close";
public static final String BUTTON_NAME_TAB_LIST = "JideTabbedPane.showList";
public static final String BUTTON_NAME_SCROLL_BACKWARD = "JideTabbedPane.scrollBackward";
public static final String BUTTON_NAME_SCROLL_FORWARD = "JideTabbedPane.scrollForward";
@SuppressWarnings({"UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
return new BasicJideTabbedPaneUI();
}
// UI Installation/De-installation
@Override
public void installUI(JComponent c) {
if (c == null) {
return;
}
_tabPane = (JideTabbedPane) c;
if (_tabPane.isTabShown() && _tabPane.getTabLeadingComponent() != null) {
_tabLeadingComponent = _tabPane.getTabLeadingComponent();
}
if (_tabPane.isTabShown() && _tabPane.getTabTrailingComponent() != null) {
_tabTrailingComponent = _tabPane.getTabTrailingComponent();
}
c.setLayout(createLayoutManager());
installComponents();
installDefaults();
installColorTheme();
installListeners();
installKeyboardActions();
}
public void installColorTheme() {
switch (getTabShape()) {
case JideTabbedPane.SHAPE_EXCEL:
_selectColor1 = _darkShadow;
_selectColor2 = _lightHighlight;
_selectColor3 = _shadow;
_unselectColor1 = _darkShadow;
_unselectColor2 = _lightHighlight;
_unselectColor3 = _shadow;
break;
case JideTabbedPane.SHAPE_WINDOWS:
case JideTabbedPane.SHAPE_WINDOWS_SELECTED:
_selectColor1 = _lightHighlight;
_selectColor2 = _shadow;
_selectColor3 = _defaultTabBorderShadowColor;
_unselectColor1 = _selectColor1;
_unselectColor2 = _selectColor2;
_unselectColor3 = _selectColor3;
break;
case JideTabbedPane.SHAPE_VSNET:
_selectColor1 = _shadow;
_selectColor2 = _shadow;
_unselectColor1 = _selectColor1;
break;
case JideTabbedPane.SHAPE_ROUNDED_VSNET:
_selectColor1 = _shadow;
_selectColor2 = _selectColor1;
_unselectColor1 = _selectColor1;
break;
case JideTabbedPane.SHAPE_FLAT:
_selectColor1 = _shadow;
_unselectColor1 = _selectColor1;
break;
case JideTabbedPane.SHAPE_ROUNDED_FLAT:
_selectColor1 = _shadow;
_selectColor2 = _shadow;
_unselectColor1 = _selectColor1;
_unselectColor2 = _selectColor2;
break;
case JideTabbedPane.SHAPE_BOX:
_selectColor1 = _shadow;
_selectColor2 = _lightHighlight;
_unselectColor1 = getPainter().getControlShadow();
_unselectColor2 = _lightHighlight;
break;
case JideTabbedPane.SHAPE_OFFICE2003:
default:
_selectColor1 = _shadow;
_selectColor2 = _lightHighlight;
_unselectColor1 = _shadow;
_unselectColor2 = null;
_unselectColor3 = null;
}
}
@Override
public void uninstallUI(JComponent c) {
uninstallKeyboardActions();
uninstallListeners();
uninstallColorTheme();
uninstallDefaults();
uninstallComponents();
c.setLayout(null);
_tabTrailingComponent = null;
_tabLeadingComponent = null;
_tabPane = null;
}
public void uninstallColorTheme() {
_selectColor1 = null;
_selectColor2 = null;
_selectColor3 = null;
_unselectColor1 = null;
_unselectColor2 = null;
_unselectColor3 = null;
}
/**
* Invoked by <code>installUI</code> to create a layout manager object to manage the <code>JTabbedPane</code>.
*
* @return a layout manager object
*
* @see TabbedPaneLayout
* @see JTabbedPane#getTabLayoutPolicy
*/
protected LayoutManager createLayoutManager() {
if (_tabPane.getTabLayoutPolicy() == JideTabbedPane.SCROLL_TAB_LAYOUT) {
return new TabbedPaneScrollLayout();
}
else { /* WRAP_TAB_LAYOUT */
return new TabbedPaneLayout();
}
}
/* In an attempt to preserve backward compatibility for programs
* which have extended VsnetJideTabbedPaneUI to do their own layout, the
* UI uses the installed layoutManager (and not tabLayoutPolicy) to
* determine if scrollTabLayout is enabled.
*/
protected boolean scrollableTabLayoutEnabled() {
return (_tabPane.getLayout() instanceof TabbedPaneScrollLayout);
}
/**
* Creates and installs any required subcomponents for the JTabbedPane. Invoked by installUI.
*/
protected void installComponents() {
if (scrollableTabLayoutEnabled()) {
if (_tabScroller == null) {
_tabScroller = new ScrollableTabSupport(_tabPane.getTabPlacement());
_tabPane.add(_tabScroller.viewport);
_tabPane.add(_tabScroller.scrollForwardButton);
_tabPane.add(_tabScroller.scrollBackwardButton);
_tabPane.add(_tabScroller.listButton);
_tabPane.add(_tabScroller.closeButton);
if (_tabLeadingComponent != null) {
_tabPane.add(_tabLeadingComponent);
}
if (_tabTrailingComponent != null) {
_tabPane.add(_tabTrailingComponent);
}
}
}
}
/**
* Removes any installed subcomponents from the JTabbedPane. Invoked by uninstallUI.
*/
protected void uninstallComponents() {
if (scrollableTabLayoutEnabled()) {
_tabPane.remove(_tabScroller.viewport);
_tabPane.remove(_tabScroller.scrollForwardButton);
_tabPane.remove(_tabScroller.scrollBackwardButton);
_tabPane.remove(_tabScroller.listButton);
_tabPane.remove(_tabScroller.closeButton);
if (_tabLeadingComponent != null) {
_tabPane.remove(_tabLeadingComponent);
}
if (_tabTrailingComponent != null) {
_tabPane.remove(_tabTrailingComponent);
}
_tabScroller = null;
}
}
protected void installDefaults() {
_painter = (ThemePainter) UIDefaultsLookup.get("Theme.painter");
_gripperPainter = (Painter) UIDefaultsLookup.get("JideTabbedPane.gripperPainter");
LookAndFeel.installColorsAndFont(_tabPane, "JideTabbedPane.background",
"JideTabbedPane.foreground", "JideTabbedPane.font");
LookAndFeel.installBorder(_tabPane, "JideTabbedPane.border");
Font f = _tabPane.getSelectedTabFont();
if (f == null || f instanceof UIResource) {
_tabPane.setSelectedTabFont(UIDefaultsLookup.getFont("JideTabbedPane.selectedTabFont"));
}
_highlight = UIDefaultsLookup.getColor("JideTabbedPane.light");
_lightHighlight = UIDefaultsLookup.getColor("JideTabbedPane.highlight");
_shadow = UIDefaultsLookup.getColor("JideTabbedPane.shadow");
_darkShadow = UIDefaultsLookup.getColor("JideTabbedPane.darkShadow");
_focus = UIDefaultsLookup.getColor("TabbedPane.focus");
if (getTabShape() == JideTabbedPane.SHAPE_BOX) {
_background = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground");
_tabBackground = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground");
_inactiveTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.foreground"); // text is black
_activeTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.foreground"); // text is black
_selectedColor = _lightHighlight;
}
else {
_background = UIDefaultsLookup.getColor("JideTabbedPane.background");
_tabBackground = UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground");
_inactiveTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.unselectedTabTextForeground");
_activeTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabTextForeground");
_selectedColor = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground");
}
_tabListBackground = UIDefaultsLookup.getColor("JideTabbedPane.tabListBackground");
_textIconGap = UIDefaultsLookup.getInt("JideTabbedPane.textIconGap");
_tabInsets = UIDefaultsLookup.getInsets("JideTabbedPane.tabInsets");
_selectedTabPadInsets = UIDefaultsLookup.getInsets("TabbedPane.selectedTabPadInsets");
if (_selectedTabPadInsets == null) _selectedTabPadInsets = new InsetsUIResource(0, 0, 0, 0);
_tabAreaInsets = UIDefaultsLookup.getInsets("JideTabbedPane.tabAreaInsets");
if (_tabAreaInsets == null) _tabAreaInsets = new InsetsUIResource(0, 0, 0, 0);
Insets insets = _tabPane.getContentBorderInsets();
if (insets == null || insets instanceof UIResource) {
_tabPane.setContentBorderInsets(UIDefaultsLookup.getInsets("JideTabbedPane.contentBorderInsets"));
}
_ignoreContentBorderInsetsIfNoTabs = UIDefaultsLookup.getBoolean("JideTabbedPane.ignoreContentBorderInsetsIfNoTabs");
_tabRunOverlay = UIDefaultsLookup.getInt("JideTabbedPane.tabRunOverlay");
_showIconOnTab = UIDefaultsLookup.getBoolean("JideTabbedPane.showIconOnTab");
_showCloseButtonOnTab = UIDefaultsLookup.getBoolean("JideTabbedPane.showCloseButtonOnTab");
_closeButtonAlignment = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonAlignment");
_gripperWidth = UIDefaultsLookup.getInt("Gripper.size");
_tabRectPadding = UIDefaultsLookup.getInt("JideTabbedPane.tabRectPadding");
_closeButtonMarginHorizon = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginHorizonal");
_closeButtonMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginVertical");
_textMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.textMarginVertical");
_noIconMargin = UIDefaultsLookup.getInt("JideTabbedPane.noIconMargin");
_iconMargin = UIDefaultsLookup.getInt("JideTabbedPane.iconMargin");
_textPadding = UIDefaultsLookup.getInt("JideTabbedPane.textPadding");
_buttonSize = UIDefaultsLookup.getInt("JideTabbedPane.buttonSize");
_buttonMargin = UIDefaultsLookup.getInt("JideTabbedPane.buttonMargin");
_fitStyleBoundSize = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleBoundSize");
_fitStyleFirstTabMargin = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleFirstTabMargin");
_fitStyleIconMinWidth = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleIconMinWidth");
_fitStyleTextMinWidth = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleTextMinWidth");
_compressedStyleNoIconRectSize = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleNoIconRectSize");
_compressedStyleIconMargin = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleIconMargin");
_compressedStyleCloseButtonMarginHorizon = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleCloseButtonMarginHorizontal");
_compressedStyleCloseButtonMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleCloseButtonMarginVertical");
_fixedStyleRectSize = UIDefaultsLookup.getInt("JideTabbedPane.fixedStyleRectSize");
_closeButtonMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMargin");
_gripLeftMargin = UIDefaultsLookup.getInt("JideTabbedPane.gripLeftMargin");
_closeButtonMarginSize = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginSize");
_closeButtonLeftMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonLeftMargin");
_closeButtonRightMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonRightMargin");
_defaultTabBorderShadowColor = UIDefaultsLookup.getColor("JideTabbedPane.defaultTabBorderShadowColor");
_alwaysShowLineBorder = UIDefaultsLookup.getBoolean("JideTabbedPane.alwaysShowLineBorder");
_showFocusIndicator = UIDefaultsLookup.getBoolean("JideTabbedPane.showFocusIndicator");
}
protected void uninstallDefaults() {
_painter = null;
_gripperPainter = null;
_highlight = null;
_lightHighlight = null;
_shadow = null;
_darkShadow = null;
_focus = null;
_inactiveTabForeground = null;
_selectedColor = null;
_tabInsets = null;
_selectedTabPadInsets = null;
_tabAreaInsets = null;
_defaultTabBorderShadowColor = null;
}
protected void installListeners() {
_tabPane.getModel().addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (_tabPane != null) { // in case updateUI() was invoked, it could be null
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount() && _tabScroller != null && _tabScroller.closeButton != null) {
_tabScroller.closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex));
}
}
}
});
if (_propertyChangeListener == null) {
_propertyChangeListener = createPropertyChangeListener();
_tabPane.addPropertyChangeListener(_propertyChangeListener);
}
if (_tabChangeListener == null) {
_tabChangeListener = createChangeListener();
_tabPane.addChangeListener(_tabChangeListener);
}
if (_tabFocusListener == null) {
_tabFocusListener = createFocusListener();
_tabPane.addFocusListener(_tabFocusListener);
}
if (_mouseListener == null) {
_mouseListener = createMouseListener();
_tabPane.addMouseListener(_mouseListener);
}
if (_mousemotionListener == null) {
_mousemotionListener = createMouseMotionListener();
_tabPane.addMouseMotionListener(_mousemotionListener);
}
if (_mouseWheelListener == null) {
_mouseWheelListener = createMouseWheelListener();
_tabPane.addMouseWheelListener(_mouseWheelListener);
}
// PENDING(api) : See comment for ContainerHandler
if (_containerListener == null) {
_containerListener = new ContainerHandler();
_tabPane.addContainerListener(_containerListener);
if (_tabPane.getTabCount() > 0) {
htmlViews = createHTMLVector();
}
}
if (_componentListener == null) {
_componentListener = new ComponentHandler();
_tabPane.addComponentListener(_componentListener);
}
if (!_tabPane.isDragOverDisabled()) {
if (_dropListener == null) {
_dropListener = createDropListener();
_dt = new DropTarget(getTabPanel(), _dropListener);
}
}
}
protected DropListener createDropListener() {
return new DropListener();
}
protected void uninstallListeners() {
// PENDING(api): See comment for ContainerHandler
if (_containerListener != null) {
_tabPane.removeContainerListener(_containerListener);
_containerListener = null;
if (htmlViews != null) {
htmlViews.removeAllElements();
htmlViews = null;
}
}
if (_componentListener != null) {
_tabPane.removeComponentListener(_componentListener);
_componentListener = null;
}
if (_tabChangeListener != null) {
_tabPane.removeChangeListener(_tabChangeListener);
_tabChangeListener = null;
}
if (_tabFocusListener != null) {
_tabPane.removeFocusListener(_tabFocusListener);
_tabFocusListener = null;
}
if (_mouseListener != null) {
_tabPane.removeMouseListener(_mouseListener);
_mouseListener = null;
}
if (_mousemotionListener != null) {
_tabPane.removeMouseMotionListener(_mousemotionListener);
_mousemotionListener = null;
}
if (_mouseWheelListener != null) {
_tabPane.removeMouseWheelListener(_mouseWheelListener);
_mouseWheelListener = null;
}
if (_propertyChangeListener != null) {
_tabPane.removePropertyChangeListener(_propertyChangeListener);
_propertyChangeListener = null;
}
if (_dt != null && _dropListener != null) {
_dt.removeDropTargetListener(_dropListener);
_dropListener = null;
_dt = null;
getTabPanel().setDropTarget(null);
}
}
protected ChangeListener createChangeListener() {
return new TabSelectionHandler();
}
protected FocusListener createFocusListener() {
return new TabFocusListener();
}
protected PropertyChangeListener createPropertyChangeListener() {
return new PropertyChangeHandler();
}
protected void installKeyboardActions() {
InputMap km = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km);
km = getInputMap(JComponent.WHEN_FOCUSED);
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_FOCUSED, km);
ActionMap am = getActionMap();
SwingUtilities.replaceUIActionMap(_tabPane, am);
ensureCloseButtonCreated();
if (scrollableTabLayoutEnabled()) {
_tabScroller.scrollForwardButton.setAction(am.get("scrollTabsForwardAction"));
_tabScroller.scrollBackwardButton.setAction(am.get("scrollTabsBackwardAction"));
_tabScroller.listButton.setAction(am.get("scrollTabsListAction"));
Action action = _tabPane.getCloseAction();
updateButtonFromAction(_tabScroller.closeButton, action);
_tabScroller.closeButton.setAction(am.get("closeTabAction"));
}
}
InputMap getInputMap(int condition) {
if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) {
return (InputMap) UIDefaultsLookup.get("JideTabbedPane.ancestorInputMap");
}
else if (condition == JComponent.WHEN_FOCUSED) {
return (InputMap) UIDefaultsLookup.get("JideTabbedPane.focusInputMap");
}
return null;
}
ActionMap getActionMap() {
ActionMap map = (ActionMap) UIDefaultsLookup.get("JideTabbedPane.actionMap");
if (map == null) {
map = createActionMap();
if (map != null) {
UIManager.getLookAndFeelDefaults().put("JideTabbedPane.actionMap", map);
}
}
return map;
}
ActionMap createActionMap() {
ActionMap map = new ActionMapUIResource();
map.put("navigateNext", new NextAction());
map.put("navigatePrevious", new PreviousAction());
map.put("navigateRight", new RightAction());
map.put("navigateLeft", new LeftAction());
map.put("navigateUp", new UpAction());
map.put("navigateDown", new DownAction());
map.put("navigatePageUp", new PageUpAction());
map.put("navigatePageDown", new PageDownAction());
map.put("requestFocus", new RequestFocusAction());
map.put("requestFocusForVisibleComponent", new RequestFocusForVisibleAction());
map.put("setSelectedIndex", new SetSelectedIndexAction());
map.put("scrollTabsForwardAction", new ScrollTabsForwardAction());
map.put("scrollTabsBackwardAction", new ScrollTabsBackwardAction());
map.put("scrollTabsListAction", new ScrollTabsListAction());
map.put("closeTabAction", new CloseTabAction());
return map;
}
protected void uninstallKeyboardActions() {
SwingUtilities.replaceUIActionMap(_tabPane, null);
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_FOCUSED, null);
if (_closeButtons != null) {
for (int i = 0; i < _closeButtons.length; i++) {
_closeButtons[i] = null;
}
_closeButtons = null;
}
}
/**
* Reloads the mnemonics. This should be invoked when a mnemonic changes, when the title of a mnemonic changes, or
* when tabs are added/removed.
*/
protected void updateMnemonics() {
resetMnemonics();
for (int counter = _tabPane.getTabCount() - 1; counter >= 0; counter--) {
int mnemonic = _tabPane.getMnemonicAt(counter);
if (mnemonic > 0) {
addMnemonic(counter, mnemonic);
}
}
}
/**
* Resets the mnemonics bindings to an empty state.
*/
private void resetMnemonics() {
if (_mnemonicToIndexMap != null) {
_mnemonicToIndexMap.clear();
_mnemonicInputMap.clear();
}
}
/**
* Adds the specified mnemonic at the specified index.
* @param index the index
* @param mnemonic the mnemonic for the index
*/
private void addMnemonic(int index, int mnemonic) {
if (_mnemonicToIndexMap == null) {
initMnemonics();
}
_mnemonicInputMap.put(KeyStroke.getKeyStroke(mnemonic, Event.ALT_MASK), "setSelectedIndex");
_mnemonicToIndexMap.put(mnemonic, index);
}
/**
* Installs the state needed for mnemonics.
*/
private void initMnemonics() {
_mnemonicToIndexMap = new Hashtable();
_mnemonicInputMap = new InputMapUIResource();
_mnemonicInputMap.setParent(SwingUtilities.getUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));
SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, _mnemonicInputMap);
}
// Geometry
@Override
public Dimension getPreferredSize(JComponent c) {
// Default to LayoutManager's preferredLayoutSize
return null;
}
@Override
public Dimension getMinimumSize(JComponent c) {
// Default to LayoutManager's minimumLayoutSize
return null;
}
@Override
public Dimension getMaximumSize(JComponent c) {
// Default to LayoutManager's maximumLayoutSize
return null;
}
// UI Rendering
@Override
public void paint(Graphics g, JComponent c) {
int tc = _tabPane.getTabCount();
paintBackground(g, c);
if (tc == 0) {
return;
}
if (_tabCount != tc) {
_tabCount = tc;
updateMnemonics();
}
int selectedIndex = _tabPane.getSelectedIndex();
int tabPlacement = _tabPane.getTabPlacement();
ensureCurrentLayout();
// Paint tab area
// If scrollable tabs are enabled, the tab area will be
// painted by the scrollable tab panel instead.
//
if (!scrollableTabLayoutEnabled()) { // WRAP_TAB_LAYOUT
paintTabArea(g, tabPlacement, selectedIndex, c);
}
// Paint content border
// if (_tabPane.isTabShown())
paintContentBorder(g, tabPlacement, selectedIndex);
}
public void paintBackground(Graphics g, Component c) {
if (_tabPane.isOpaque()) {
int width = c.getWidth();
int height = c.getHeight();
g.setColor(_background);
g.fillRect(0, 0, width, height);
}
}
/**
* Paints the tabs in the tab area. Invoked by paint(). The graphics parameter must be a valid <code>Graphics</code>
* object. Tab placement may be either: <code>JTabbedPane.TOP</code>, <code>JTabbedPane.BOTTOM</code>,
* <code>JTabbedPane.LEFT</code>, or <code>JTabbedPane.RIGHT</code>. The selected index must be a valid tabbed pane
* tab index (0 to tab count - 1, inclusive) or -1 if no tab is currently selected. The handling of invalid
* parameters is unspecified.
*
* @param g the graphics object to use for rendering
* @param tabPlacement the placement for the tabs within the JTabbedPane
* @param selectedIndex the tab index of the selected component
* @param c the component
*/
protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex, Component c) {
if (!PAINT_TABAREA) {
return;
}
int tabCount = _tabPane.getTabCount();
Rectangle iconRect = new Rectangle(),
textRect = new Rectangle();
Rectangle rect = new Rectangle(0, 0, c.getWidth(), c.getHeight());
paintTabAreaBackground(g, rect, tabPlacement);
boolean leftToRight = tabPlacement == LEFT || tabPlacement == RIGHT || _tabPane.getComponentOrientation().isLeftToRight();
// Paint tabRuns of tabs from back to front
for (int i = _runCount - 1; i >= 0; i--) {
int start = _tabRuns[i];
int next = _tabRuns[(i == _runCount - 1) ? 0 : i + 1];
int end = (next != 0 ? next - 1 : tabCount - 1);
for (int j = start; j <= end; j++) {
if ((_rects[j].intersects(rect) || !leftToRight) && j != selectedIndex) {
paintTab(g, tabPlacement, _rects, j, iconRect, textRect);
}
}
}
// Paint selected tab if its in the front run
// since it may overlap other tabs
if (selectedIndex >= 0 && getRunForTab(tabCount, selectedIndex) == 0) {
if (_rects[selectedIndex].intersects(rect) || !leftToRight) {
paintTab(g, tabPlacement, _rects, selectedIndex, iconRect, textRect);
}
}
}
protected void paintTabAreaBackground(Graphics g, Rectangle rect, int tabPlacement) {
getPainter().paintTabAreaBackground(_tabPane, g, rect,
tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM ? SwingConstants.HORIZONTAL : SwingConstants.VERTICAL,
ThemePainter.STATE_DEFAULT);
}
protected void paintTab(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect) {
if (!PAINT_TAB) {
return;
}
Rectangle tabRect = new Rectangle(rects[tabIndex]);
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
tabRect.x += _tabScroller.viewport.getExpectedViewX();
}
int selectedIndex = _tabPane.getSelectedIndex();
boolean isSelected = selectedIndex == tabIndex;
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
paintTabBackground(g, tabPlacement, tabIndex, tabRect.x, tabRect.y,
tabRect.width, tabRect.height, isSelected);
Object savedHints = JideSwingUtilities.setupShapeAntialiasing(g);
paintTabBorder(g, tabPlacement, tabIndex, tabRect.x, tabRect.y,
tabRect.width, tabRect.height, isSelected);
JideSwingUtilities.restoreShapeAntialiasing(g, savedHints);
Icon icon = _tabPane.getIconForTab(tabIndex);
Rectangle tempTabRect = new Rectangle(tabRect);
if (_tabPane.isShowGripper()) {
if (leftToRight) {
tempTabRect.x += _gripperWidth;
}
tempTabRect.width -= _gripperWidth;
Rectangle gripperRect = new Rectangle(tabRect);
if (leftToRight) {
gripperRect.x += _gripLeftMargin;
}
else {
gripperRect.x = tabRect.x + tabRect.width - _gripLeftMargin - _gripperWidth;
}
gripperRect.width = _gripperWidth;
if (_gripperPainter != null) {
_gripperPainter.paint(_tabPane, g, gripperRect, SwingConstants.HORIZONTAL, isSelected ? ThemePainter.STATE_SELECTED : ThemePainter.STATE_DEFAULT);
}
else {
getPainter().paintGripper(_tabPane, g, gripperRect, SwingConstants.HORIZONTAL, isSelected ? ThemePainter.STATE_SELECTED : ThemePainter.STATE_DEFAULT);
}
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex)
&& (!_tabPane.isShowCloseButtonOnSelectedTab() || isSelected)) {
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int buttonWidth = _closeButtons[tabIndex].getPreferredSize().width + _closeButtonLeftMargin + _closeButtonRightMargin;
if (!(_closeButtonAlignment == SwingConstants.LEADING ^ leftToRight)) {
tempTabRect.x += buttonWidth;
}
tempTabRect.width -= buttonWidth;
}
else {
int buttonHeight = _closeButtons[tabIndex].getPreferredSize().height + _closeButtonLeftMargin + _closeButtonRightMargin;
if (_closeButtonAlignment == SwingConstants.LEADING) {
tempTabRect.y += buttonHeight;
tempTabRect.height -= buttonHeight;
}
else {
tempTabRect.height -= buttonHeight;
}
}
}
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
Font font;
if (isSelected && _tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (isSelected && _tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
FontMetrics metrics = g.getFontMetrics(font);
while (title == null || title.length() < 3)
title += " ";
layoutLabel(tabPlacement, metrics, tabIndex, title, icon,
tempTabRect, iconRect, textRect, isSelected);
if (!_isEditing || (!isSelected))
paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
paintIcon(g, tabPlacement, tabIndex, icon, iconRect, isSelected);
paintFocusIndicator(g, tabPlacement, rects, tabIndex,
iconRect, textRect, isSelected);
}
/* This method will create and return a polygon shape for the given tab rectangle
* which has been cropped at the specified crop line with a torn edge visual.
* e.g. A "File" tab which has cropped been cropped just after the "i":
* -------------
* | ..... |
* | . |
* | ... . |
* | . . |
* | . . |
* | . . |
* --------------
*
* The x, y arrays below define the pattern used to create a "torn" edge
* segment which is repeated to fill the edge of the tab.
* For tabs placed on TOP and BOTTOM, this righthand torn edge is created by
* line segments which are defined by coordinates obtained by
* subtracting xCropLen[i] from (tab.x + tab.width) and adding yCroplen[i]
* to (tab.y).
* For tabs placed on LEFT or RIGHT, the bottom torn edge is created by
* subtracting xCropLen[i] from (tab.y + tab.height) and adding yCropLen[i]
* to (tab.x).
*/
private int xCropLen[] = {1, 1, 0, 0, 1, 1, 2, 2};
private int yCropLen[] = {0, 3, 3, 6, 6, 9, 9, 12};
private static final int CROP_SEGMENT = 12;
/*
private Polygon createCroppedTabClip(int tabPlacement, Rectangle tabRect, int cropline) {
int rlen = 0;
int start = 0;
int end = 0;
int ostart = 0;
switch (tabPlacement) {
case LEFT:
case RIGHT:
rlen = tabRect.width;
start = tabRect.x;
end = tabRect.x + tabRect.width;
ostart = tabRect.y;
break;
case TOP:
case BOTTOM:
default:
rlen = tabRect.height;
start = tabRect.y;
end = tabRect.y + tabRect.height;
ostart = tabRect.x;
}
int rcnt = rlen / CROP_SEGMENT;
if (rlen % CROP_SEGMENT > 0) {
rcnt++;
}
int npts = 2 + (rcnt << 3);
int xp[] = new int[npts];
int yp[] = new int[npts];
int pcnt = 0;
xp[pcnt] = ostart;
yp[pcnt++] = end;
xp[pcnt] = ostart;
yp[pcnt++] = start;
for (int i = 0; i < rcnt; i++) {
for (int j = 0; j < xCropLen.length; j++) {
xp[pcnt] = cropline - xCropLen[j];
yp[pcnt] = start + (i * CROP_SEGMENT) + yCropLen[j];
if (yp[pcnt] >= end) {
yp[pcnt] = end;
pcnt++;
break;
}
pcnt++;
}
}
if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
return new Polygon(xp, yp, pcnt);
}
else { // LEFT or RIGHT
return new Polygon(yp, xp, pcnt);
}
}
*/
/* If tabLayoutPolicy == SCROLL_TAB_LAYOUT, this method will paint an edge
* indicating the tab is cropped in the viewport display
*/
@SuppressWarnings({"UnusedDeclaration"})
private void paintCroppedTabEdge(Graphics g, int tabPlacement, int tabIndex,
boolean isSelected,
int x, int y) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
int xx = x;
g.setColor(_shadow);
while (xx <= x + _rects[tabIndex].width) {
for (int i = 0; i < xCropLen.length; i += 2) {
g.drawLine(xx + yCropLen[i], y - xCropLen[i],
xx + yCropLen[i + 1] - 1, y - xCropLen[i + 1]);
}
xx += CROP_SEGMENT;
}
break;
case TOP:
case BOTTOM:
default:
int yy = y;
g.setColor(_shadow);
while (yy <= y + _rects[tabIndex].height) {
for (int i = 0; i < xCropLen.length; i += 2) {
g.drawLine(x - xCropLen[i], yy + yCropLen[i],
x - xCropLen[i + 1], yy + yCropLen[i + 1] - 1);
}
yy += CROP_SEGMENT;
}
}
}
protected void layoutLabel(int tabPlacement,
FontMetrics metrics, int tabIndex,
String title, Icon icon,
Rectangle tabRect, Rectangle iconRect,
Rectangle textRect, boolean isSelected) {
textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
View v = getTextViewForTab(tabIndex);
if (v != null) {
_tabPane.putClientProperty("html", v);
}
SwingUtilities.layoutCompoundLabel(_tabPane,
metrics, title, icon,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
SwingUtilities.CENTER,
SwingUtilities.TRAILING,
tabRect,
iconRect,
textRect,
_textIconGap);
_tabPane.putClientProperty("html", null);
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
// iconRect.x = tabRect.x + _iconMargin;
// textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding);
// iconRect.width = Math.min(iconRect.width, tabRect.width - _tabRectPadding);
// textRect.width = tabRect.width - _tabRectPadding - iconRect.width - (icon != null ? _textIconGap + _iconMargin : _noIconMargin);
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
if (!_tabPane.isShowCloseButtonOnSelectedTab()) {
if (!isSelected) {
iconRect.width = iconRect.width + _closeButtons[tabIndex].getPreferredSize().width + _closeButtonMarginHorizon;
textRect.width = 0;
}
}
}
}
else {// tabplacement is left or right
iconRect.y = tabRect.y + _iconMargin;
textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding);
iconRect.x = tabRect.x + 2;
textRect.x = tabRect.x + 2;
textRect.width = tabRect.width - _textMarginVertical;
textRect.height = tabRect.height - _tabRectPadding - iconRect.height - (icon != null ? _textIconGap + _iconMargin : _noIconMargin);
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
if (!_tabPane.isShowCloseButtonOnSelectedTab()) {
if (!isSelected) {
iconRect.height = iconRect.height + _closeButtons[tabIndex].getPreferredSize().height + _closeButtonMarginVertical;
textRect.height = 0;
}
}
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintIcon(Graphics g, int tabPlacement,
int tabIndex, Icon icon, Rectangle iconRect,
boolean isSelected) {
if (icon != null && iconRect.width >= icon.getIconWidth()) {
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
icon.paintIcon(_tabPane, g, iconRect.x, iconRect.y);
}
else {
if (iconRect.height < _rects[tabIndex].height - _gripperHeight) {
icon.paintIcon(_tabPane, g, iconRect.x, iconRect.y);
}
}
}
}
protected void paintText(Graphics g, int tabPlacement,
Font font, FontMetrics metrics, int tabIndex,
String title, Rectangle textRect,
boolean isSelected) {
Graphics2D g2d = (Graphics2D) g.create();
if (isSelected && _tabPane.isBoldActiveTab()) {
g2d.setFont(font.deriveFont(Font.BOLD));
}
else {
g2d.setFont(font);
}
String actualText = title;
if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
if (textRect.width <= 0)
return;
while (SwingUtilities.computeStringWidth(metrics, actualText) > textRect.width) {
actualText = actualText.substring(0, actualText.length() - 1);
}
if (!actualText.equals(title)) {
if (actualText.length() >= 2)
actualText = actualText.substring(0, actualText.length() - 2) + "..";
else
actualText = "";
}
}
else {
if (textRect.height <= 0)
return;
while (SwingUtilities.computeStringWidth(metrics, actualText) > textRect.height) {
actualText = actualText.substring(0, actualText.length() - 1);
}
if (!actualText.equals(title)) {
if (actualText.length() >= 2)
actualText = actualText.substring(0, actualText.length() - 2) + "..";
else
actualText = "";
}
}
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
v.paint(g2d, textRect);
}
else {
// plain text
int mnemIndex = _tabPane.getDisplayedMnemonicIndexAt(tabIndex);
JideTabbedPane.ColorProvider colorProvider = _tabPane.getTabColorProvider();
if (_tabPane.isEnabled() && _tabPane.isEnabledAt(tabIndex)) {
if (colorProvider != null) {
g2d.setColor(colorProvider.getForegroudAt(tabIndex));
}
else {
Color color = _tabPane.getForegroundAt(tabIndex);
if (isSelected && showFocusIndicator()) {
if (!(color instanceof ColorUIResource)) {
g2d.setColor(color);
}
else {
g2d.setColor(_activeTabForeground);
}
}
else {
if (!(color instanceof ColorUIResource)) {
g2d.setColor(color);
}
else {
g2d.setColor(_inactiveTabForeground);
}
}
}
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
}
else {// draw string from top to bottom
AffineTransform old = g2d.getTransform();
g2d.translate(textRect.x, textRect.y);
if (tabPlacement == RIGHT) {
g2d.rotate(Math.PI / 2);
g2d.translate(0, -textRect.width);
}
else {
g2d.rotate(-Math.PI / 2);
g2d.translate(-textRect.height + metrics.getHeight() / 2 + _rectSizeExtend, 0); // no idea why i need 7 here
}
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex, 0,
((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent());
g2d.setTransform(old);
}
}
else { // tab disabled
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
g2d.setColor(_tabPane.getBackgroundAt(tabIndex).brighter());
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
g2d.setColor(_tabPane.getBackgroundAt(tabIndex).darker());
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1);
}
else {// draw string from top to bottom
AffineTransform old = g2d.getTransform();
g2d.translate(textRect.x, textRect.y);
if (tabPlacement == RIGHT) {
g2d.rotate(Math.PI / 2);
g2d.translate(0, -textRect.width);
}
else {
g2d.rotate(-Math.PI / 2);
g2d.translate(-textRect.height + metrics.getHeight() / 2 + _rectSizeExtend, 0); // no idea why i need 7 here
}
g2d.setColor(_tabPane.getBackgroundAt(tabIndex).brighter());
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex,
0, ((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent());
g2d.setColor(_tabPane.getBackgroundAt(tabIndex).darker());
JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g2d, actualText, mnemIndex,
tabPlacement == RIGHT ? -1 : 1, ((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent() - 1);
g2d.setTransform(old);
}
}
}
g2d.dispose();
}
/**
* this function draws the border around each tab note that this function does now draw the background of the tab.
* that is done elsewhere
*
* @param g the Graphics instance
* @param tabPlacement the tab placement
* @param tabIndex the tab index
* @param x x
* @param y y
* @param w width
* @param h height
* @param isSelected if the tab is selected
*/
protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
if (!PAINT_TAB_BORDER) {
return;
}
switch (getTabShape()) {
case JideTabbedPane.SHAPE_BOX:
paintBoxTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_EXCEL:
paintExcelTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_WINDOWS:
paintWindowsTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_WINDOWS_SELECTED:
if (isSelected) {
paintWindowsTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
break;
case JideTabbedPane.SHAPE_VSNET:
paintVsnetTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_ROUNDED_VSNET:
paintRoundedVsnetTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_FLAT:
paintFlatTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_ROUNDED_FLAT:
paintRoundedFlatTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_OFFICE2003:
default:
paintOffice2003TabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
int tabShape = getTabShape();
if (tabShape == JideTabbedPane.SHAPE_WINDOWS) {
if (_mouseEnter && _tabPane.getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP
&& tabIndex == _indexMouseOver && !isSelected && _tabPane.isEnabledAt(_indexMouseOver)) {
paintTabBorderMouseOver(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
}
else if (tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
if (_mouseEnter && tabIndex == _indexMouseOver && !isSelected && _tabPane.isEnabledAt(_indexMouseOver)) {
paintTabBorderMouseOver(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
}
}
protected void paintOffice2003TabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:// when the tab on the left
y += 2;
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x, y + 3, x, y + h - 5);// left
g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom
// arc
g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom
g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + 2, y - 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + 3 + i, y - 2 - i, x + 3 + i, y - 2 - i);
}
g.drawLine(x + w - 1, y - w + 1, x + w - 1, y - w + 2);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 3, x + 1, y + h - 5);// left
g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom
g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc
g.drawLine(x + 3, y, x + 3, y - 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + 4 + i, y - 2 - i, x + 4 + i, y - 2 - i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 3, x, y + h - 5);// left
g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom
// arc
g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom
g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + 2, y - 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + 3 + i, y - 2 - i, x + 3 + i, y - 2 - i);
}
g.drawLine(x + w - 1, y - w + 1, x + w - 1, y - w + 2);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 3, x + 1, y + h - 6);// left
g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc
g.drawLine(x + 3, y, x + 3, y - 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + 4 + i, y - 2 - i, x + 4 + i, y - 2 - i);
}
g.setColor(getPainter().getControlDk());
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// bottom
// arc
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x, y + 3, x, y + h - 5);// left
g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom
// arc
g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom
g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + 2, y - 1);
g.drawLine(x + 3, y - 2, x + 3, y - 2);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 3, x + 1, y + h - 6);// left
g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc
g.drawLine(x + 3, y, x + 3, y - 1);
g.drawLine(x + 4, y - 2, x + 4, y - 2);
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);
}
}
}
break;
case RIGHT:
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom
// arc
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + w - 4 - i, y - i, x + w - 4 - i, y - i);
}
g.drawLine(x, y - w + 3, x, y - w + 4);
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 3);// right
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top arc
g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + w - 5 - i, y - i, x + w - 5 - i, y - i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom
// arc
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + w - 4 - i, y - i, x + w - 4 - i, y - i);
}
g.drawLine(x, y - w + 3, x, y - w + 4);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 4);// right
g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top
// arc
g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1);
for (int i = 0; i < w - 4; i++) {// top
g.drawLine(x + w - 5 - i, y - i, x + w - 5 - i, y
- i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom
// arc
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom
// arc
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc
g.drawLine(x + w - 4, y, x + w - 4, y);// top arc
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 4);// right
g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top
// arc
g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1);
g.drawLine(x + w - 5, y, x + w - 5, y);
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom
// arc
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
}
}
}
break;
case BOTTOM:
if (leftToRight) {
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right
// arc
g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc
g.drawLine(x, y + h - 4, x, y + h - 4);// left arc
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + h - 2 - i, x + 2 - i, y + h
- 2 - i);
}
g.drawLine(x - h + 3, y, x - h + 4, y);
g.setColor(_selectColor2);
g.drawLine(x + 5, y + h - 2, x + w - 3, y + h - 2);// bottom
g.drawLine(x + w - 2, y, x + w - 2, y + h - 3);// right
g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left arc
g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left arc
g.drawLine(x, y + h - 5, x, y + h - 5);// left arc
for (int i = 3; i < h - 2; i++) {// left
g.drawLine(x + 2 - i, y + h - 3 - i, x + 2 - i, y + h
- 3 - i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right
// arc
g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc
g.drawLine(x, y + h - 4, x, y + h - 4);// left arc
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + h - 2 - i, x + 2 - i, y + h
- 2 - i);
}
g.drawLine(x - h + 3, y, x - h + 4, y);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left
// arc
g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left
// arc
g.drawLine(x, y + h - 5, x, y + h - 5);// left arc
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + h - 3 - i, x + 2 - i, y
+ h - 3 - i);
}
g.drawLine(x + 5, y + h - 2, x + w - 4, y + h - 2);// bottom
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2);
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y);// right
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right
// arc
g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc
g.drawLine(x, y + h - 4, x, y + h - 4);// left arc
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left
// arc
g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left
// arc
g.drawLine(x, y + h - 5, x, y + h - 5);// left arc
g.drawLine(x + 5, y + h - 2, x + w - 4, y + h - 2);// bottom
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2);
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y);// right
}
}
}
}
else {
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x, y + h - 3, x, y);// left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// left
// arc
g.drawLine(x + w - 6, y + h - 1, x + 2, y + h - 1);// bottom
g.drawLine(x + w - 4, y + h - 2, x + w - 5, y + h - 2);// right arc
g.drawLine(x + w - 2, y + h - 3, x + w - 3, y + h - 3);// right arc
g.drawLine(x + w - 1, y + h - 4, x + w - 1, y + h - 4);// right arc
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + h - 2 - i, x + w - 3 + i, y + h - 2 - i);
}
g.drawLine(x + w - 4 + h, y, x + w - 5 + h, y);
g.setColor(_selectColor2);
g.drawLine(x + w - 6, y + h - 2, x + 2, y + h - 2);// bottom
g.drawLine(x + 1, y, x + 1, y + h - 3);// left
g.drawLine(x + w - 4, y + h - 3, x + w - 5, y + h - 3);// right arc
g.drawLine(x + w - 2, y + h - 4, x + w - 3, y + h - 4);// right arc
g.drawLine(x + w - 1, y + h - 5, x + w - 1, y + h - 5);// right arc
for (int i = 3; i < h - 2; i++) {// right
g.drawLine(x + w - 3 + i, y + h - 3 - i, x + w - 3 + i, y + h - 3 - i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x, y + h - 3, x, y);// left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// left
// arc
g.drawLine(x + w - 6, y + h - 1, x + 2, y + h - 1);// bottom
g.drawLine(x + w - 4, y + h - 2, x + w - 5, y + h - 2);// right arc
g.drawLine(x + w - 2, y + h - 3, x + w - 3, y + h - 3);// right arc
g.drawLine(x + w - 1, y + h - 4, x + w - 1, y + h - 4);// right arc
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + h - 2 - i, x + w - 3 + i, y + h - 2 - i);
}
g.drawLine(x + w - 4 + h, y, x + w -5 + h, y);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 4, y + h - 3, x + w - 5, y + h - 3);// right
// arc
g.drawLine(x + w - 2, y + h - 4, x + w - 3, y + h - 4);// right
// arc
g.drawLine(x + w - 1, y + h - 5, x + w - 1, y + h - 5);// right arc
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + h - 3 - i, x + w - 3 + i, y + h - 3 - i);
}
g.drawLine(x + w - 6, y + h - 2, x + 3, y + h - 2);// bottom
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + w - 6, y + h - 1, x + 2, y + h - 1);// bottom
g.drawLine(x, y + h - 3, x, y);// left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// left
// arc
g.drawLine(x + w - 4, y + h - 2, x + w - 5, y + h - 2);// right arc
g.drawLine(x + w - 2, y + h - 3, x + w - 3, y + h - 3);// right arc
g.drawLine(x + w - 1, y + h - 4, x + w - 1, y + h - 4);// right arc
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 4, y + h - 3, x + w - 5, y + h - 3);// right
// arc
g.drawLine(x + w - 2, y + h - 4, x + w - 3, y + h - 4);// right
// arc
g.drawLine(x + w - 1, y + h - 5, x + w -1, y + h - 5);// right arc
g.drawLine(x + w - 6, y + h - 2, x + 3, y + h - 2);// bottom
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
}
}
}
}
break;
case TOP:
default:
if (leftToRight) {
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc
g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc
g.drawLine(x, y + 3, x, y + 3);
g.drawLine(x + 5, y, x + w - 3, y);// top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + 1 + i, x + 2 - i, y + 1 + i);
}
g.drawLine(x - h + 3, y + h - 1, x - h + 4, y + h - 1);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc
g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc
g.drawLine(x, y + 4, x, y + 4);
g.drawLine(x + 5, y + 1, x + w - 3, y + 1);// top
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + 2 + i, x + 2 - i, y + 2 + i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc
g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc
g.drawLine(x, y + 3, x, y + 3);
g.drawLine(x + 5, y, x + w - 3, y);// top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + 1 + i, x + 2 - i, y + 1 + i);
}
g.drawLine(x - h + 3, y + h - 1, x - h + 4, y + h - 1);
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc
g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc
g.drawLine(x, y + 4, x, y + 4);
// left
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + 2 - i, y + 2 + i, x + 2 - i, y + 2
+ i);
}
g.drawLine(x + 5, y + 1, x + w - 4, y + 1);// top
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 3, y + 1, x + w - 3, y + 1);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc
g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc
g.drawLine(x, y + 3, x, y + 3);
g.drawLine(x + 5, y, x + w - 3, y);// top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc
g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc
g.drawLine(x, y + 4, x, y + 4);
g.drawLine(x + 5, y + 1, x + w - 4, y + 1);// top
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 3, y + 1, x + w - 3, y + 1);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right
}
}
}
}
else {
if (isSelected) {// the tab is selected
g.setColor(_selectColor1);
g.drawLine(x + w - 4, y + 1, x + w - 5, y + 1);// right arc
g.drawLine(x + w - 2, y + 2, x + w - 3, y + 2);// right arc
g.drawLine(x + w - 1, y + 3, x + w - 1, y + 3);
g.drawLine(x + w - 6, y, x + 2, y);// top
g.drawLine(x + 1, y + 1, x + 1, y + 1);// left arc
g.drawLine(x, y + 2, x, y + h - 1);// left
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + 1 + i, x + w - 3 + i, y + 1 + i);
}
g.drawLine(x + w - 4 + h, y + h - 1, x + w - 5 + h, y + h - 1);
g.setColor(_selectColor2);
g.drawLine(x + w - 4, y + 2, x + w - 5, y + 2);// right arc
g.drawLine(x + w - 2, y + 3, x + w - 3, y + 3);// right arc
g.drawLine(x + w - 1, y + 4, x + w - 1, y + 4);
g.drawLine(x + w - 6, y + 1, x + 2, y + 1);// top
g.drawLine(x + 1, y + 2, x + 1, y + h - 1);// right
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + 2 + i, x + w - 3 + i, y + 2 + i);
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 4, y + 1, x + w - 5, y + 1);// right arc
g.drawLine(x + w - 2, y + 2, x + w - 3, y + 2);// right arc
g.drawLine(x + w - 1, y + 3, x + w - 1, y + 3);
g.drawLine(x + w - 6, y, x + 2, y);// top
g.drawLine(x + 1, y + 1, x + 1, y + 1);// left arc
g.drawLine(x, y + 2, x, y + h - 1);// left
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + 1 + i, x + w - 3 + i, y + 1 + i);
}
g.drawLine(x + w - 4 + h, y + h - 1, x + w - 5 + h, y + h - 1);//
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 4, y + 2, x + w - 5, y + 2);// right arc
g.drawLine(x + w - 2, y + 3, x + w - 3, y + 3);// right arc
g.drawLine(x + w - 1, y + 4, x + w - 1, y + 4);
// right
for (int i = 3; i < h - 2; i++) {
g.drawLine(x + w - 3 + i, y + 2 + i, x + w - 3 + i, y + 2 + i);
}
g.drawLine(x + w - 6, y + 1, x + 3, y + 1);// top
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + 1, x + 2, y + 1);
g.drawLine(x + 1, y + 2, x + 1, y + h - 1);// left
}
}
else {
g.setColor(_unselectColor1);
g.drawLine(x + w - 4, y + 1, x + w - 5, y + 1);// right arc
g.drawLine(x + w - 2, y + 2, x + w - 3, y + 2);// right arc
g.drawLine(x + w - 1, y + 3, x + w - 1, y + 3);
g.drawLine(x + w - 6, y, x + 2, y);// top
g.drawLine(x + 1, y + 1, x + 1, y + 1);// left arc
g.drawLine(x, y + 2, x, y + h - 1);// left
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 4, y + 2, x + w - 5, y + 2);// right arc
g.drawLine(x + w - 2, y + 3, x + w - 3, y + 3);// right arc
g.drawLine(x + w - 1, y + 4, x + w - 1, y + 4);
g.drawLine(x + w - 6, y + 1, x + 3, y + 1);// top
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + 1, x + 2, y + 1);
g.drawLine(x + 1, y + 2, x + 1, y + h - 1);// left
}
}
}
}
}
}
protected void paintExcelTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + 5, x, y + h - 5);// left
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i);
}
if (_selectColor2 != null) {
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i);
}
}
if (_selectColor3 != null) {
g.setColor(_selectColor3);
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i);
}
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 5, x, y + h - 5);// left
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left
for (int i = 0, j = 0; i < w / 2; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i);
}
}
}
else if (tabIndex == _tabPane.getSelectedIndex() - 1) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 5, x, y + h - 5);// left
for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i);
}
for (int i = 0, j = 0; i < 5; i++, j = j + 2) {// bottom
g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left
for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point
for (int i = 0, j = 0; i < 5; i++, j = j + 2) {// bottom
g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i);
}
}
}
else if (tabIndex != _tabPane.getSelectedIndex() - 1) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 5, x, y + h - 5);// left
for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left
for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top
g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom
g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i);
}
}
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i);
}
if (_selectColor2 != null) {
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i);
}
}
if (_selectColor3 != null) {
g.setColor(_selectColor3);
g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i);
}
}
}
else {
if (tabIndex == 0) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a
// point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i);
}
}
}
else if (tabIndex == _tabPane.getSelectedIndex() - 1) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right
for (int i = 0, j = 0; i < 4; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i);
}
for (int i = 0, j = 0; i < 5; i++, j += 2) {// bottom
g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right
for (int i = 0, j = 0; i < 4; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point
for (int i = 0, j = 0; i < 5; i++, j += 2) {// bottom
g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i);
}
}
}
else if (tabIndex != _tabPane.getSelectedIndex() - 1) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right
for (int i = 0, j = 0; i < 4; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i);
}
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right
for (int i = 0, j = 0; i < 4; i++, j += 2) {// top
g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point
for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom
g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i);
}
}
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 5, y + h - 1);// bottom
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + h - 1 - j, x + w - 4 - 1 + i, y + h - 2 - j);
}
if (_selectColor2 != null) {
g.setColor(_selectColor2);
g.drawLine(x + 5, y + h - 3, x + 5, y + h - 3);// bottom
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 4 - j, x + 4 - i, y + h - 5 - j);
}
}
if (_selectColor3 != null) {
g.setColor(_selectColor3);
g.drawLine(x + 5, y + h - 2, x + w - 6, y + h - 2);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j);
}
}
}
else {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 5, y + h - 1);// bottom
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + h - 1 - j, x + w - 4 - 1 + i, y + h - 2 - j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j);
}
}
}
else if (tabIndex == _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 6, y + h - 1);// bottom
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j);
}
for (int i = 0, j = 0; i < 5; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 1 - j, x + w - 5 + i, y + h - 2 - j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point
for (int i = 0, j = 0; i < 5; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j);
}
}
}
else if (tabIndex != _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y + h - 1, x + w - 6, y + h - 1);// bottom
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 1 - j, x + w - 5 + i, y + h - 2 - j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j);
}
}
}
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 5, y, x + w - 5, y);// top
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j);
}
if (_selectColor2 != null) {
g.setColor(_selectColor2);
g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j);
}
}
if (_selectColor3 != null) {
g.setColor(_selectColor3);
g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j);
}
}
}
else {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y, x + w - 5, y);// top
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j);
}
}
}
else if (tabIndex == _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y, x + w - 5, y);// top
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j);
}
for (int i = 0, j = 0; i < 5; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point
for (int i = 0, j = 0; i < 5; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j);
}
}
}
else if (tabIndex != _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) {
g.setColor(_unselectColor1);
g.drawLine(x + 5, y, x + w - 5, y);// top
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j);
}
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j);
}
if (_unselectColor2 != null) {
g.setColor(_unselectColor2);
g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top
for (int i = 0, j = 0; i < 5; i++, j += 2) {// left
g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j);
}
}
if (_unselectColor3 != null) {
g.setColor(_unselectColor3);
g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point
for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right
g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j);
}
}
}
}
}
}
protected void paintWindowsTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
int colorTheme = getColorTheme();
switch (tabPlacement) {
case LEFT:
if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x - 2, y + 1, x - 2, y + h - 1);// left
g.drawLine(x - 1, y, x - 1, y);// top arc
g.drawLine(x, y - 1, x + w - 1, y - 1);// top
g.setColor(_selectColor2);
g.drawLine(x - 1, y + h, x - 1, y + h);// bottom arc
g.drawLine(x, y + h + 1, x, y + h + 1);// bottom arc
g.drawLine(x + 1, y + h, x + w - 1, y + h);// bottom
g.setColor(_selectColor3);
g.drawLine(x, y + h, x, y + h);// bottom arc
g.drawLine(x + 1, y + h + 1, x + w - 1, y + h + 1);// bottom
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 2, x, y + h - 3);// left
g.drawLine(x + 1, y + 1, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + w - 1, y);// top
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// bottom arc
g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc
g.drawLine(x + 3, y + h - 2, x + w - 1, y + h - 2);// bottom
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// bottom arc
g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 3, x, y + h - 2);// left
g.drawLine(x + 1, y + 2, x + 1, y + 2);// top arc
g.drawLine(x + 2, y + 1, x + w - 1, y + 1);// top
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc
g.drawLine(x + 2, y + h, x + 2, y + h);// bottom arc
g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom
g.setColor(_unselectColor3);
g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc
g.drawLine(x + 3, y + h, x + w - 1, y + h);// bottom
}
}
}
else {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x - 2, y + 1, x - 2, y + h - 1);// left
g.drawLine(x - 1, y, x - 1, y);// top arc
g.drawLine(x, y - 1, x, y - 1);// top arc
g.drawLine(x - 1, y + h, x - 1, y + h);// bottom arc
g.drawLine(x, y + h + 1, x, y + h + 1);// bottom arc
g.setColor(_selectColor2);
g.drawLine(x - 1, y + 1, x - 1, y + h - 1);// left
g.drawLine(x, y, x, y + h);// left
g.setColor(_selectColor3);
g.drawLine(x + 1, y - 2, x + w - 1, y - 2);// top
g.drawLine(x + 1, y + h + 2, x + w - 1, y + h + 2);// bottom
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 2, x, y + h - 4);// left
g.drawLine(x + 1, y + 1, x + 1, y + 1);// top arc
g.drawLine(x + 2, y, x + w - 1, y);// top
g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3);// bottom arc
g.drawLine(x + 2, y + h - 2, x + w - 1, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + 4, x, y + h - 2);// left
g.drawLine(x + 1, y + 3, x + 1, y + 3);// top arc
g.drawLine(x + 2, y + 2, x + w - 1, y + 2);// top
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc
g.drawLine(x + 2, y + h, x + w - 1, y + h);// bottom
}
}
}
break;
case RIGHT:
if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y - 1, x, y - 1);// top
g.setColor(_selectColor2);
g.drawLine(x + w, y + 1, x + w, y + h - 1);// right
g.drawLine(x + w - 1, y + h, x, y + h);// bottom
g.setColor(_selectColor3);
g.drawLine(x + w, y, x + w, y);// top arc
g.drawLine(x + w + 1, y + 1, x + w + 1, y + h - 1);// right
g.drawLine(x + w, y + h, x + w, y + h);// bottom arc
g.drawLine(x + w - 1, y + h + 1, x, y + h + 1);// bottom
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 3, y, x, y);// top
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 3);// right
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3);// right
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom arc
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 3, y + 1, x, y + 1);// top
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 3, x + w - 2, y + h - 2);// right
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.setColor(_unselectColor3);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + 2);// top arc
g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 2);// right
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc
g.drawLine(x + w - 3, y + h, x, y + h);// bottom
}
}
}
else {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + w + 1, y + 1, x + w + 1, y + h - 1);// right
g.drawLine(x + w, y, x + w, y);// top arc
g.drawLine(x + w - 1, y - 1, x + w - 1, y - 1);// top arc
g.drawLine(x + w, y + h, x + w, y + h);// bottom arc
g.drawLine(x + w - 1, y + h + 1, x + w - 1, y + h + 1);// bottom arc
g.setColor(_selectColor2);
g.drawLine(x + w, y + 1, x + w, y + h - 1);// right
g.drawLine(x + w - 1, y, x + w - 1, y + h);// right
g.setColor(_selectColor3);
g.drawLine(x + w - 2, y - 2, x, y - 2);// top
g.drawLine(x + w - 2, y + h + 2, x, y + h + 2);// bottom
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 4);// right
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top arc
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom arc
g.drawLine(x + w - 3, y, x, y);// top
g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2);// right
g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3);// top arc
g.drawLine(x + w - 3, y + 2, x, y + 2);// top
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc
g.drawLine(x + w - 3, y + h, x, y + h);// bottom
}
}
}
break;
case BOTTOM:
if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + h, x, y + h);// left arc
g.drawLine(x - 1, y + h - 1, x - 1, y);// left
g.setColor(_selectColor2);
g.drawLine(x + 1, y + h, x + w - 2, y + h);// bottom
g.drawLine(x + w - 1, y + h - 1, x + w - 1, y - 1);// right
g.setColor(_selectColor3);
g.drawLine(x + 1, y + h + 1, x + w - 2, y + h + 1);// bottom
g.drawLine(x + w - 1, y + h, x + w - 1, y + h);// right arc
g.drawLine(x + w, y + h - 1, x + w, y - 1);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + h - 2, x, y + h - 2);// left arc
g.drawLine(x - 1, y + h - 3, x - 1, y);// left
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 2, x + w - 4, y + h - 2);// bottom
g.drawLine(x + w - 3, y + h - 3, x + w - 3, y - 1);// right
g.setColor(_unselectColor3);
g.drawLine(x + 1, y + h - 1, x + w - 4, y + h - 1);// bottom
g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2);// right arc
g.drawLine(x + w - 2, y + h - 3, x + w - 2, y - 1);// right
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
g.setColor(_unselectColor2);
g.drawLine(x + 3, y + h - 2, x + w - 2, y + h - 2);// bottom
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
g.setColor(_unselectColor3);
g.drawLine(x + 3, y + h - 1, x + w - 2, y + h - 1);// bottom
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);// right arc
g.drawLine(x + w, y + h - 3, x + w, y);// right
}
}
}
else {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 1, y + h + 1, x + w, y + h + 1);// bottom
g.drawLine(x, y + h, x, y + h);// right arc
g.drawLine(x - 1, y + h - 1, x - 1, y + h - 1);// right arc
g.drawLine(x + w + 1, y + h, x + w + 1, y + h);// left arc
g.drawLine(x + w + 2, y + h - 1, x + w + 2, y + h - 1);// left arc
g.setColor(_selectColor2);
g.drawLine(x + 1, y + h, x + w, y + h);// bottom
g.drawLine(x, y + h - 1, x + w + 1, y + h - 1);// bottom
g.setColor(_selectColor3);
g.drawLine(x - 1, y + h - 2, x - 1, y);// left
g.drawLine(x + w + 2, y + h - 2, x + w + 2, y);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right arc
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y - 1);// right
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);// bottom
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right arc
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y - 1);// right
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc
g.drawLine(x + 1, y + h - 3, x + 1, y);// left
}
}
}
break;
case TOP:
default:
if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y - 1, x, y - 1); // left arc
g.drawLine(x - 1, y, x - 1, y + h - 1);// left
g.drawLine(x + 1, y - 2, x + w + 1, y - 2);// top
g.setColor(_selectColor2);
g.drawLine(x + w + 2, y - 1, x + w + 2, y + h - 1);// right
g.setColor(_selectColor3);
g.drawLine(x + w + 2, y - 1, x + w + 2, y - 1);// right arc
g.drawLine(x + w + 3, y, x + w + 3, y + h - 1);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 3, y, x + w - 2, y); // top
g.setColor(_unselectColor2);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right
g.setColor(_unselectColor3);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc
g.drawLine(x + w, y + 2, x + w, y + h - 1);// right
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 3, y, x + w - 2, y); // top
g.setColor(_unselectColor2);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right
g.setColor(_unselectColor3);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc
g.drawLine(x + w, y + 2, x + w, y + h - 1);// right
}
}
}
else {
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 1, y - 2, x + w, y - 2); // top
g.drawLine(x, y - 1, x, y - 1); // left arc
g.drawLine(x - 1, y, x - 1, y); // left arc
g.drawLine(x + w + 1, y - 1, x + w + 1, y - 1);// right arc
g.drawLine(x + w + 2, y, x + w + 2, y);// right arc
g.setColor(_selectColor2);
g.drawLine(x + 1, y - 1, x + w, y - 1);// top
g.drawLine(x, y, x + w + 1, y);// top
g.setColor(_selectColor3);
g.drawLine(x - 1, y + 1, x - 1, y + h - 1);// left
g.drawLine(x + w + 2, y + 1, x + w + 2, y + h - 1);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 3, y, x + w - 3, y); // top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 3, y, x + w - 3, y); // top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right
}
}
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintTabBorderMouseOver(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS) {
switch (tabPlacement) {
case LEFT:
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 2;
}
g.setColor(_selectColor1);
g.drawLine(x, y + 4, x, y + h - 2);
g.drawLine(x + 1, y + 3, x + 1, y + 3);
g.drawLine(x + 2, y + 2, x + 2, y + 2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
g.drawLine(x + 2, y + h, x + 2, y + h);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 4, x + 1, y + h - 2);
g.drawLine(x + 2, y + 3, x + 2, y + h - 1);
break;
case RIGHT:
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 2;
}
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2);
g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3);
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 2);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w - 3, y + h, x + w - 3, y + h);
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 4, x + w - 2, y + h - 2);
g.drawLine(x + w - 3, y + 3, x + w - 3, y + h - 1);
break;
case BOTTOM:
g.setColor(_selectColor1);
g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);
g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3);
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y + h - 3);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + h - 2, x + w - 3, y + h - 2);
g.drawLine(x + 2, y + h - 3, x + w - 2, y + h - 3);
break;
case TOP:
default:
g.setColor(_selectColor1);
g.drawLine(x + 3, y, x + w - 3, y);
g.drawLine(x + 2, y + 1, x + 2, y + 1);
g.drawLine(x + 1, y + 2, x + 1, y + 2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + 2);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + 1, x + w - 3, y + 1);
g.drawLine(x + 2, y + 2, x + w - 2, y + 2);
}
}
else if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
switch (tabPlacement) {
case LEFT:
if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) {
if (tabIndex > _tabPane.getSelectedIndex()) {
y -= 2;
}
g.setColor(_selectColor1);
g.drawLine(x, y + 4, x, y + h - 2);
g.drawLine(x + 1, y + 3, x + 1, y + 3);
g.drawLine(x + 2, y + 2, x + 2, y + 2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
g.drawLine(x + 2, y + h, x + 2, y + h);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 4, x + 1, y + h - 2);
g.drawLine(x + 2, y + 3, x + 2, y + h - 1);
g.setColor(_selectColor3);
g.drawLine(x + 3, y + 2, x + w - 1, y + 2);
g.drawLine(x + 3, y + h, x + w - 1, y + h);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 1;
}
g.setColor(_selectColor1);
g.drawLine(x, y + 3, x, y + h - 2);// left
g.drawLine(x + 1, y + 2, x + 1, y + 2);// top arc
g.drawLine(x + 2, y + 1, x + w - 1, y + 1);// top
g.setColor(_selectColor2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc
g.drawLine(x + 2, y + h, x + 2, y + h);// bottom arc
g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom
g.setColor(_selectColor3);
g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc
g.drawLine(x + 3, y + h, x + w - 1, y + h);// bottom
}
break;
case RIGHT:
if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) {
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 2;
}
g.setColor(_selectColor1);
g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2);
g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3);
g.drawLine(x + w - 3, y + 2, x + w - 3, y + 2);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w - 3, y + h, x + w - 3, y + h);
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 4, x + w - 2, y + h - 2);
g.drawLine(x + w - 3, y + 3, x + w - 3, y + h - 1);
g.setColor(_selectColor3);
g.drawLine(x + w - 4, y + 2, x, y + 2);
g.drawLine(x + w - 4, y + h, x, y + h);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
y = y - 1;
}
g.setColor(_selectColor3);
g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 2);// right
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc
g.drawLine(x + w - 3, y + h, x, y + h);// bottom
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 3, x + w - 2, y + h - 2);// right
g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom
g.setColor(_selectColor1);
g.drawLine(x + w - 2, y + 2, x + w - 2, y + 2);// top arc
g.drawLine(x + w - 3, y + 1, x, y + 1);// top
}
break;
case BOTTOM:
if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) {
g.setColor(_selectColor1);
g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);
g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3);
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y + h - 3);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + h - 2, x + w - 3, y + h - 2);
g.drawLine(x + 2, y + h - 3, x + w - 2, y + h - 3);
g.setColor(_selectColor3);
g.drawLine(x + 1, y, x + 1, y + h - 4); // left
g.drawLine(x + w - 1, y, x + w - 1, y + h - 4);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
x = x - 2;
}
g.setColor(_selectColor3);
g.drawLine(x + 3, y + h - 1, x + w - 2, y + h - 1);// bottom
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);// right arc
g.drawLine(x + w, y + h - 3, x + w, y);// right
g.setColor(_selectColor1);
g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left
g.drawLine(x + 1, y + h - 3, x + 1, y);// left arc
g.setColor(_selectColor2);
g.drawLine(x + 3, y + h - 2, x + w - 2, y + h - 2);// bottom
g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right
}
break;
case TOP:
default:
if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) {
g.setColor(_selectColor1);
g.drawLine(x + 3, y, x + w - 3, y);
g.drawLine(x + 2, y + 1, x + 2, y + 1);
g.drawLine(x + 1, y + 2, x + 1, y + 2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + 2);
g.setColor(_selectColor2);
g.drawLine(x + 3, y + 1, x + w - 3, y + 1);
g.drawLine(x + 2, y + 2, x + w - 2, y + 2);
g.setColor(_selectColor3);
g.drawLine(x + 1, y + 3, x + 1, y + h - 1); // left
g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 1);// right
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
x = x - 1;
}
g.setColor(_selectColor1);
g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc
g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left
g.drawLine(x + 3, y, x + w - 2, y); // top
g.setColor(_selectColor2);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right
g.setColor(_selectColor3);
g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc
g.drawLine(x + w, y + 2, x + w, y + h - 1);// right
}
}
}
}
protected void paintVsnetTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 1, y);// top
g.drawLine(x, y, x, y + h - 2);// left
g.setColor(_selectColor2);
g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + 2, y + h - 2, x + w - 2, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x + 2, y, x + w - 2, y);// top
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 1, y);// top
g.setColor(_selectColor2);
g.drawLine(x + w - 1, y, x + w - 1, y + h - 2);// left
g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + 1, y + h - 2, x + w - 3, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x + 1, y, x + w - 3, y);// top
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x, y + h - 1); // left
g.setColor(_selectColor2);
g.drawLine(x, y + h - 1, x + w - 1, y + h - 1); // bottom
g.drawLine(x + w - 1, y, x + w - 1, y + h - 2); // right
}
else {
g.setColor(_unselectColor1);
if (leftToRight) {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
}
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + 1, x, y + h - 1); // left
g.drawLine(x, y, x + w - 1, y); // top
g.setColor(_selectColor2);
g.drawLine(x + w - 1, y, x + w - 1, y + h - 1); // right
}
else {
g.setColor(_unselectColor1);
if (leftToRight) {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
}
}
}
}
protected void paintRoundedVsnetTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 2, y, x + w - 1, y);// top
g.drawLine(x + 1, y + 1, x + 1, y + 1);// top-left
g.drawLine(x, y + 2, x, y + h - 3);// left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// bottom-left
g.drawLine(x + 2, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + 2, y + h - 2, x + w - 2, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x + 2, y + 1, x + w - 2, y + 1);// top
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 3, y);// top
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top-left
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3);// left
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom-left
g.drawLine(x, y + h - 1, x + w - 3, y + h - 1);// bottom
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + 1, y + h - 2, x + w - 3, y + h - 2);// bottom
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x + 1, y + 1, x + w - 3, y + 1);// top
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x, y + h - 3); // left
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2); // bottom-left
g.drawLine(x + 2, y + h - 1, x + w - 3, y + h - 1); // bottom
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2); // bottom-right
g.drawLine(x + w - 1, y, x + w - 1, y + h - 3); // right
}
else {
g.setColor(_unselectColor1);
if (leftToRight) {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
}
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + 2, x, y + h - 1); // left
g.drawLine(x, y + 2, x + 2, y); // top-left
g.drawLine(x + 2, y, x + w - 3, y); // top
g.drawLine(x + w - 3, y, x + w - 1, y + 2); // top-left
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1); // right
}
else {
g.setColor(_unselectColor1);
if (leftToRight) {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.drawLine(x, y + 2, x, y + h - 2); // left
}
else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right
}
}
}
}
}
protected void paintFlatTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawRect(x, y, w, h);
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawRect(x, y, w, h - 1);
}
else {
g.drawRect(x, y, w, h);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.drawRect(x, y, w, h);
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawRect(x - 1, y, w, h);
}
else {
g.setColor(_unselectColor1);
if (tabIndex > _tabPane.getSelectedIndex()) {
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawRect(x - 1, y, w, h - 1);
}
else {
g.drawRect(x - 1, y, w, h);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.drawRect(x - 1, y, w, h);
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawRect(x, y - 1, w, h);
}
else {
g.setColor(_unselectColor1);
g.drawRect(x, y - 1, w, h);
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawRect(x, y, w, h);
}
else {
g.setColor(_unselectColor1);
g.drawRect(x, y, w, h);
}
}
}
protected void paintRoundedFlatTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
switch (tabPlacement) {
case LEFT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x + 2, y, x + w - 1, y);
g.drawLine(x + 2, y + h, x + w - 1, y + h);
g.drawLine(x, y + 2, x, y + h - 2);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + 1, x + 1, y + 1);
// g.drawLine(x, y + 1, x, y + 1);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
// g.drawLine(x + 1, y + h, x + 1, y + h);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y, x + w - 1, y);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + 2, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x, y + 2, x, y + h - 3);
}
else {
g.drawLine(x + 2, y + h, x + w - 1, y + h);
g.drawLine(x, y + 2, x, y + h - 2);
}
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 1, x + 1, y + 1);
// g.drawLine(x, y + 1, x, y + 1);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x, y + h - 2, x, y + h - 2);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
}
else {
g.drawLine(x, y + h - 1, x, y + h - 1);
g.drawLine(x + 1, y + h, x + 1, y + h);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x + 2, y, x + w - 1, y);
g.drawLine(x + 2, y + h, x + w - 1, y + h);
g.drawLine(x, y + 2, x, y + h - 2);
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 1, x + 1, y + 1);
// g.drawLine(x, y + 1, x, y + 1);
g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
// g.drawLine(x + 1, y + h, x + 1, y + h);
}
}
break;
case RIGHT:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 3, y);
g.drawLine(x, y + h, x + w - 3, y + h);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2);
g.setColor(_selectColor2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
// g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y, x + w - 3, y);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x, y + h - 1, x + w - 3, y + h - 1);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3);
}
else {
g.drawLine(x, y + h, x + w - 3, y + h);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2);
}
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
// g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);
// g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
}
else {
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y, x + w - 3, y);
g.drawLine(x, y + h, x + w - 3, y + h);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2);
g.setColor(_unselectColor2);
g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);
// g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);
g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
// g.drawLine(x + w - 2, y + h, x + w - 2, y + h);
}
}
break;
case BOTTOM:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x, y + h - 3);
g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w, y, x + w, y + h - 3);
g.setColor(_selectColor2);
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);
// g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y, x, y + h - 3);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + 2, y + h - 1, x + w - 3, y + h - 1);
g.drawLine(x + w - 1, y, x + w - 1, y + h - 3);
}
else {
g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w, y, x + w, y + h - 3);
}
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);
// g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
if (tabIndex == _tabPane.getTabCount() - 1) {
// g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);
}
else {
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y, x, y + h - 3);
g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1);
g.drawLine(x + w, y, x + w, y + h - 3);
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);
// g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);
// g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1);
g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);
}
}
break;
case TOP:
default:
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y + h - 1, x, y + 2);
g.drawLine(x + 2, y, x + w - 2, y);
g.drawLine(x + w, y + 2, x + w, y + h - 1);
g.setColor(_selectColor2);
g.drawLine(x, y + 2, x + 2, y); // top-left
g.drawLine(x + w - 2, y, x + w, y + 2);
// g.drawLine(x + w, y + 1, x + w, y + 1);
}
else {
if (tabIndex > _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + h - 1, x, y + 2);
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + 2, y, x + w - 3, y);
g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);
}
else {
g.drawLine(x + 2, y, x + w - 2, y);
g.drawLine(x + w, y + 2, x + w, y + h - 1);
}
g.setColor(_unselectColor2);
g.drawLine(x, y + 2, x + 2, y); // top-left
if (tabIndex == _tabPane.getTabCount() - 1) {
g.drawLine(x + w - 3, y, x + w - 1, y + 2);
}
else {
g.drawLine(x + w - 2, y, x + w, y + 2);
}
}
else if (tabIndex < _tabPane.getSelectedIndex()) {
g.setColor(_unselectColor1);
g.drawLine(x, y + h - 1, x, y + 2);
g.drawLine(x + 2, y, x + w - 2, y);
g.drawLine(x + w, y + 2, x + w, y + h - 1);
g.setColor(_unselectColor2);
g.drawLine(x, y + 2, x + 2, y);
g.drawLine(x + w - 2, y, x + w, y + 2);
}
}
}
}
protected void paintBoxTabBorder(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
if (isSelected) {
g.setColor(_selectColor1);
g.drawLine(x, y, x + w - 2, y);// top
g.drawLine(x, y, x, y + h - 2);// left
g.setColor(_selectColor2);
g.drawLine(x + w - 1, y, x + w - 1, y + h - 1);// right
g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom
}
else {
if (tabIndex != _tabPane.getSelectedIndex() - 1) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
g.setColor(_unselectColor1);
g.drawLine(x + 2, y + h, x + w - 2, y + h);// bottom
g.setColor(_unselectColor2);
g.drawLine(x + 2, y + h + 1, x + w - 2, y + h + 1);// bottom
break;
case BOTTOM:
case TOP:
default:
if (leftToRight) {
g.setColor(_unselectColor1);
g.drawLine(x + w, y + 2, x + w, y + h - 2);// right
g.setColor(_unselectColor2);
g.drawLine(x + w + 1, y + 2, x + w + 1, y + h - 2);// right
}
else {
g.setColor(_unselectColor1);
g.drawLine(x, y + 2, x, y + h - 2);// right
g.setColor(_unselectColor2);
g.drawLine(x + 1, y + 2, x + 1, y + h - 2);// right
}
}
}
}
}
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
if (!PAINT_TAB_BACKGROUND) {
return;
}
switch (getTabShape()) {
case JideTabbedPane.SHAPE_BOX:
paintButtonTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_EXCEL:
paintExcelTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_WINDOWS:
paintDefaultTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_WINDOWS_SELECTED:
if (isSelected) {
paintDefaultTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
break;
case JideTabbedPane.SHAPE_VSNET:
case JideTabbedPane.SHAPE_ROUNDED_VSNET:
paintVsnetTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_FLAT:
case JideTabbedPane.SHAPE_ROUNDED_FLAT:
paintFlatTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
break;
case JideTabbedPane.SHAPE_OFFICE2003:
default:
paintOffice2003TabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected);
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintOffice2003TabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (tabIndex != 0 && !isSelected) {
int xp[] = {x + w, x + 4, x + 2, x, x, x + 3, x + w};
int yp[] = {y, y, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {// tabIndex != 0
int xp[] = {x + w, x + 2, x, x, x + 3, x + w};
int yp[] = {y - w + 2 + 2, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case RIGHT:
if (tabIndex != 0 && !isSelected) {
int xp[] = {x, x + w - 4, x + w - 3, x + w - 1, x + w - 1, x + w - 3, x};
int yp[] = {y, y, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x + w - 3, x + w - 1, x + w - 1, x + w - 3, x};
int yp[] = {y - w + 2 + 2, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case BOTTOM:
if (leftToRight) {
int xp[] = {x - (tabIndex == 0 || isSelected ? h - 5 : 0), x, x + 4, x + w - 3, x + w - 1, x + w - 1};
int yp[] = {y, y + h - 5, y + h - 1, y + h - 1, y + h - 5, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x, x + 2, x + w - 5, x + w - 1, x + w - 1 + (tabIndex == 0 || isSelected ? h - 5 : 0)};
int yp[] = {y, y + h - 5, y + h - 1, y + h - 1, y + h - 5, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case TOP:
default:
if (leftToRight) {
int xp[] = {x - (tabIndex == 0 || isSelected ? h - 5 : 0), x, x + 4, x + w - 3, x + w - 1, x + w - 1};
int yp[] = {y + h, y + 3, y + 1, y + 1, y + 3, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x, x + 2, x + w - 5, x + w - 1, x + w - 1 + (tabIndex == 0 || isSelected ? h - 5 : 0)};
int yp[] = {y + h, y + 3, y + 1, y + 1, y + 3, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintExcelTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
switch (tabPlacement) {
case LEFT:
if (!isSelected) {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
int xp[] = {x + w, x, x, x + w};
int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + w, x + 9, x, x, x + w};
int yp[] = {y + 8, y + 2, y + 6, y + h - 5, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
else {
int xp[] = {x + w, x, x, x + w};
int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case RIGHT:
if (!isSelected) {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
int xp[] = {x, x + w - 1, x + w - 1, x};
int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x + w - 10, x + w - 1, x + w - 1, x};
int yp[] = {y + 8, y + 2, y + 6, y + h - 5,
y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
else {
int xp[] = {x, x + w - 1, x + w - 1, x};
int yp[] = {y - 5, y + 5, y + h - 4, y + h + 6};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case BOTTOM:
if (!isSelected) {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
int xp[] = {x - 5, x + 5, x + w - 5, x + w + 5};
int yp[] = {y, y + h - 1, y + h - 1, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + 7, x + 1, x + 5, x + w - 5, x + w + 5};
int yp[] = {y, y + h - 10, y + h - 1, y + h - 1, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
else {
int xp[] = {x - 5, x + 5, x + w - 5, x + w + 5};
int yp[] = {y, y + h - 1, y + h - 1, y};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case TOP:
default:
if (!isSelected) {
if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) {
int xp[] = {x - 6, x + 5, x + w - 5, x + w + 5};
int yp[] = {y + h, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + 7, x + 1, x + 6, x + w - 5, x + w + 5};
int yp[] = {y + h, y + 9, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
else {
int xp[] = {x - 6, x + 5, x + w - 5, x + w + 5};
int yp[] = {y + h, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintDefaultTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
switch (tabPlacement) {
case LEFT:
if (isSelected) {
x = x + 1;
int xp[] = {x + w, x, x - 2, x - 2, x + w};
int yp[] = {y - 1, y - 1, y + 1, y + h + 2, y + h + 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
if (tabIndex < _tabPane.getSelectedIndex()) {
y = y + 1;
int xp[] = {x + w, x + 2, x, x, x + w};
int yp[] = {y + 1, y + 1, y + 3, y + h - 1,
y + h - 1};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + w, x + 2, x, x, x + w};
int yp[] = {y + 1, y + 1, y + 3, y + h - 2,
y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
break;
case RIGHT:
if (isSelected) {
int xp[] = {x, x + w - 1, x + w, x + w, x};
int yp[] = {y - 1, y - 1, y + 1, y + h + 2, y + h + 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
if (tabIndex < _tabPane.getSelectedIndex()) {
y = y + 1;
int xp[] = {x, x + w - 3, x + w - 1, x + w - 1, x};
int yp[] = {y + 1, y + 1, y + 3, y + h - 1,
y + h - 1};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x + w - 2, x + w - 1, x + w - 1, x};
int yp[] = {y + 1, y + 1, y + 3, y + h - 2,
y + h - 2};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
break;
case BOTTOM:
if (isSelected) {
int xp[] = {x, x, x + 2, x + w + 2, x + w + 2};
int yp[] = {y + h, y, y - 2, y - 2, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + 1, x + 1, x + 1, x + w - 1, x + w - 1};
int yp[] = {y + h - 1, y + 2, y, y, y + h - 1};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
break;
case TOP:
default:
if (isSelected) {
int xp[] = {x, x, x + 2, x + w + 2, x + w + 2};
int yp[] = {y + h + 1, y, y - 2, y - 2, y + h + 1};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
else {
int xp[] = {x + 1, x + 1, x + 3, x + w - 1, x + w - 1};
int yp[] = {y + h, y + 2, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintTabBackgroundMouseOver(Graphics g, int tabPlacement, int tabIndex,
int x, int y, int w, int h, boolean isSelected, Color backgroundUnselectedColorStart, Color backgroundUnselectedColorEnd) {
Graphics2D g2d = (Graphics2D) g;
Polygon polygon;
switch (tabPlacement) {
case LEFT:
if (tabIndex < _tabPane.getSelectedIndex()) {
int xp[] = {x + w, x + 2, x, x, x + 2, x + w};
int yp[] = {y + 2, y + 2, y + 4, y + h - 1, y + h,
y + h};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
}
else {// tabIndex > _tabPane.getSelectedIndex()
int xp[] = {x + w, x + 2, x, x, x + 2, x + w};
int yp[] = {y + 1, y + 1, y + 3, y + h - 3,
y + h - 2, y + h - 2};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
}
JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorStart, backgroundUnselectedColorEnd, false);
break;
case RIGHT:
if (tabIndex < _tabPane.getSelectedIndex()) {
int xp[] = {x, x + w - 3, x + w - 1, x + w - 1,
x + w - 3, x};
int yp[] = {y + 2, y + 2, y + 4, y + h - 1, y + h,
y + h};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
}
else {
int xp[] = {x, x + w - 2, x + w - 1, x + w - 1,
x + w - 3, x};
int yp[] = {y + 1, y + 1, y + 3, y + h - 3,
y + h - 2, y + h - 2};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
}
JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorEnd, backgroundUnselectedColorStart, false);
break;
case BOTTOM:
int xp[] = {x + 1, x + 1, x + 1, x + w - 1, x + w - 1};
int yp[] = {y + h - 2, y + 2, y, y, y + h - 2};
int np = yp.length;
polygon = new Polygon(xp, yp, np);
JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorEnd, backgroundUnselectedColorStart, true);
break;
case TOP:
default:
int xp1[] = {x + 1, x + 1, x + 3, x + w - 1, x + w - 1};
int yp1[] = {y + h, y + 2, y, y, y + h};
int np1 = yp1.length;
polygon = new Polygon(xp1, yp1, np1);
JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorStart, backgroundUnselectedColorEnd, true);
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintVsnetTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
int xp[];
int yp[];
switch (tabPlacement) {
case LEFT:
xp = new int[]{x + 1, x + 1, x + w, x + w};
yp = new int[]{y + h - 1, y + 1, y + 1, y + h - 1};
break;
case RIGHT:
xp = new int[]{x, x, x + w - 1, x + w - 1};
yp = new int[]{y + h - 1, y + 1, y + 1, y + h - 1};
break;
case BOTTOM:
xp = new int[]{x + 1, x + 1, x + w - 1, x + w - 1};
yp = new int[]{y + h - 1, y, y, y + h - 1};
break;
case TOP:
default:
xp = new int[]{x + 1, x + 1, x + w - 1, x + w - 1};
yp = new int[]{y + h, y + 1, y + 1, y + h};
break;
}
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintFlatTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
switch (tabPlacement) {
case LEFT:
int xp1[] = {x + 1, x + 1, x + w, x + w};
int yp1[] = {y + h, y + 1, y + 1, y + h};
int np1 = yp1.length;
tabRegion = new Polygon(xp1, yp1, np1);
break;
case RIGHT:
int xp2[] = {x, x, x + w - 1, x + w - 1};
int yp2[] = {y + h, y + 1, y + 1, y + h};
int np2 = yp2.length;
tabRegion = new Polygon(xp2, yp2, np2);
break;
case BOTTOM:
int xp3[] = {x + 1, x + 1, x + w, x + w};
int yp3[] = {y + h - 1, y, y, y + h - 1};
int np3 = yp3.length;
tabRegion = new Polygon(xp3, yp3, np3);
break;
case TOP:
default:
int xp4[] = {x, x + 1, x + w, x + w};
int yp4[] = {y + h, y + 1, y + 1, y + h};
int np4 = yp4.length;
tabRegion = new Polygon(xp4, yp4, np4);
}
}
@SuppressWarnings({"UnusedDeclaration"})
protected void paintButtonTabBackground(Graphics g, int tabPlacement,
int tabIndex, int x, int y, int w, int h, boolean isSelected) {
int xp[] = {x, x, x + w, x + w};
int yp[] = {y + h, y, y, y + h};
int np = yp.length;
tabRegion = new Polygon(xp, yp, np);
}
protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) {
int width = _tabPane.getWidth();
int height = _tabPane.getHeight();
Insets insets = _tabPane.getInsets();
int x = insets.left;
int y = insets.top;
int w = width - insets.right - insets.left;
int h = height - insets.top - insets.bottom;
int temp = -1;
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
x += calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
if (isTabLeadingComponentVisible()) {
if (lsize.width > calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth)) {
x = insets.left + lsize.width;
temp = _tabLeadingComponent.getSize().width;
}
}
if (isTabTrailingComponentVisible()) {
if (_maxTabWidth < tsize.width
&& temp < tsize.width) {
x = insets.left + tsize.width;
}
}
w -= (x - insets.left);
break;
case RIGHT:
w -= calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
break;
case BOTTOM:
h -= calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
break;
case TOP:
default:
y += calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
if (lsize.height > calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight)) {
y = insets.top + lsize.height;
temp = lsize.height;
}
}
if (isTabTrailingComponentVisible()) {
if (_maxTabHeight < tsize.height
&& temp < tsize.height) {
y = insets.top + tsize.height;
}
}
h -= (y - insets.top);
}
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
// Fill region behind content area
paintContentBorder(g, x, y, w, h);
switch (tabPlacement) {
case LEFT:
paintContentBorderLeftEdge(g, tabPlacement, selectedIndex, x, y, w, h);
break;
case RIGHT:
paintContentBorderRightEdge(g, tabPlacement, selectedIndex, x, y, w, h);
break;
case BOTTOM:
paintContentBorderBottomEdge(g, tabPlacement, selectedIndex, x, y, w, h);
break;
case TOP:
default:
paintContentBorderTopEdge(g, tabPlacement, selectedIndex, x, y, w, h);
break;
}
}
}
protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
}
protected void paintContentBorderRightEdge(Graphics g, int tabPlacement,
int selectedIndex, int x, int y, int w, int h) {
}
protected void paintContentBorder(Graphics g, int x, int y, int w, int h) {
if (!PAINT_CONTENT_BORDER) {
return;
}
if (_tabPane.isOpaque()) {
g.setColor(_tabBackground);
g.fillRect(x, y, w, h);
}
}
protected Color getBorderEdgeColor() {
if ("true".equals(SecurityUtils.getProperty("shadingtheme", "false"))) {
return _shadow;
}
else {
return _lightHighlight;
}
}
protected void paintContentBorderTopEdge(Graphics g, int tabPlacement,
int selectedIndex,
int x, int y, int w, int h) {
if (!PAINT_CONTENT_BORDER_EDGE) {
return;
}
if (selectedIndex < 0) {
return;
}
if (!_tabPane.isTabShown()) {
return;
}
Rectangle selRect = getTabBounds(selectedIndex, _calcRect);
g.setColor(getBorderEdgeColor());
// Draw unbroken line if tabs are not on TOP, OR
// selected tab is not in run adjacent to content, OR
// selected tab is not visible (SCROLL_TAB_LAYOUT)
//
if (tabPlacement != TOP || selectedIndex < 0 ||
/*(selRect.y + selRect.height + 1 < y) ||*/
(selRect.x < x || selRect.x > x + w)) {
g.drawLine(x, y, x + w - 1, y);
}
else {
// Break line to show visual connection to selected tab
g.drawLine(x, y, selRect.x, y);
if (!getBorderEdgeColor().equals(_lightHighlight)) {
if (selRect.x + selRect.width < x + w - 2) {
g.drawLine(selRect.x + selRect.width - 1, y,
selRect.x + selRect.width - 1, y);
g.drawLine(selRect.x + selRect.width, y, x + w - 1, y);
}
else {
g.drawLine(x + w - 2, y, x + w - 1, y);
}
}
else {
if (selRect.x + selRect.width < x + w - 2) {
g.setColor(_darkShadow);
g.drawLine(selRect.x + selRect.width - 1, y,
selRect.x + selRect.width - 1, y);
g.setColor(_lightHighlight);
g.drawLine(selRect.x + selRect.width, y, x + w - 1, y);
}
else {
g.setColor(_selectedColor == null ?
_tabPane.getBackground() : _selectedColor);
g.drawLine(x + w - 2, y, x + w - 1, y);
}
}
}
}
protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement,
int selectedIndex,
int x, int y, int w, int h) {
if (!PAINT_CONTENT_BORDER_EDGE) {
return;
}
if (selectedIndex < 0) {
return;
}
if (!_tabPane.isTabShown()) {
return;
}
Rectangle selRect = getTabBounds(selectedIndex, _calcRect);
// Draw unbroken line if tabs are not on BOTTOM, OR
// selected tab is not in run adjacent to content, OR
// selected tab is not visible (SCROLL_TAB_LAYOUT)
//
if (tabPlacement != BOTTOM || selectedIndex < 0 ||
/*(selRect.y - 1 > h) ||*/
(selRect.x < x || selRect.x > x + w)) {
g.setColor(getBorderEdgeColor());
g.drawLine(x, y + h - 1, x + w - 2, y + h - 1);
}
else {
if (!getBorderEdgeColor().equals(_lightHighlight)) {
g.setColor(getBorderEdgeColor());
g.drawLine(x, y + h - 1, selRect.x - 1, y + h - 1);
g.drawLine(selRect.x, y + h - 1, selRect.x, y + h - 1);
if (selRect.x + selRect.width < x + w - 2) {
g.drawLine(selRect.x + selRect.width - 1, y + h - 1, x + w - 2, y + h - 1); // dark line to the end
}
}
else {
// Break line to show visual connection to selected tab
g.setColor(_darkShadow); // dark line at the beginning
g.drawLine(x, y + h - 1, selRect.x - 1, y + h - 1);
g.setColor(_lightHighlight); // light line to meet with tab
// border
g.drawLine(selRect.x, y + h - 1, selRect.x, y + h - 1);
if (selRect.x + selRect.width < x + w - 2) {
g.setColor(_darkShadow);
g.drawLine(selRect.x + selRect.width - 1, y + h - 1, x + w - 2, y + h - 1); // dark line to the end
}
}
}
}
protected void ensureCurrentLayout() {
/*
* If tabPane doesn't have a peer yet, the validate() call will
* silently fail. We handle that by forcing a layout if tabPane
* is still invalid. See bug 4237677.
*/
if (!_tabPane.isValid()) {
TabbedPaneLayout layout = (TabbedPaneLayout) _tabPane.getLayout();
layout.calculateLayoutInfo();
}
}
private void updateCloseButtons() {
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab()) {
for (int i = 0; i < _closeButtons.length; i++) {
if (_tabPane.isShowCloseButtonOnSelectedTab()) {
if (i != _tabPane.getSelectedIndex()) {
_closeButtons[i].setBounds(0, 0, 0, 0);
continue;
}
}
else {
if (i >= _rects.length) {
_closeButtons[i].setBounds(0, 0, 0, 0);
continue;
}
}
if (!_tabPane.isTabClosableAt(i)) {
_closeButtons[i].setBounds(0, 0, 0, 0);
continue;
}
Dimension size = _closeButtons[i].getPreferredSize();
Rectangle bounds;
if (_closeButtonAlignment == SwingConstants.TRAILING) {
if (_tabPane.getTabPlacement() == JideTabbedPane.TOP || _tabPane.getTabPlacement() == JideTabbedPane.BOTTOM) {
if (leftToRight) {
bounds = new Rectangle(_rects[i].x + _rects[i].width - size.width - _closeButtonRightMargin,
_rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height);
bounds.x -= getTabGap();
}
else {
bounds = new Rectangle(_rects[i].x + _closeButtonLeftMargin + getTabGap(), _rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height);
}
}
else /*if (_tabPane.getTabPlacement() == JideTabbedPane.LEFT || _tabPane.getTabPlacement() == JideTabbedPane.RIGHT)*/ {
bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2, _rects[i].y + _rects[i].height - size.height - _closeButtonRightMargin, size.width, size.height);
bounds.y -= getTabGap();
}
}
else {
if (_tabPane.getTabPlacement() == JideTabbedPane.TOP || _tabPane.getTabPlacement() == JideTabbedPane.BOTTOM) {
if (leftToRight) {
bounds = new Rectangle(_rects[i].x + _closeButtonLeftMargin + getTabGap(), _rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height);
}
else {
bounds = new Rectangle(_rects[i].x + _rects[i].width - size.width - _closeButtonRightMargin,
_rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height);
bounds.x -= getTabGap();
}
}
else if (_tabPane.getTabPlacement() == JideTabbedPane.LEFT) {
bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2, _rects[i].y + _closeButtonLeftMargin, size.width, size.height);
}
else /*if (_tabPane.getTabPlacement() == JideTabbedPane.RIGHT)*/ {
bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2 - 2, _rects[i].y + _closeButtonLeftMargin, size.width, size.height);
}
}
_closeButtons[i].setIndex(i);
if (!bounds.equals(_closeButtons[i].getBounds())) {
_closeButtons[i].setBounds(bounds);
}
if (_tabPane.getSelectedIndex() == i) {
_closeButtons[i].setBackground(_selectedColor == null ? _tabPane.getBackgroundAt(i) : _selectedColor);
}
else {
_closeButtons[i].setBackground(_tabPane.getBackgroundAt(i));
}
}
}
}
// TabbedPaneUI methods
/**
* Returns the bounds of the specified tab index. The bounds are with respect to the JTabbedPane's coordinate
* space.
*/
@Override
public Rectangle getTabBounds(JTabbedPane pane, int i) {
ensureCurrentLayout();
Rectangle tabRect = new Rectangle();
return getTabBounds(i, tabRect);
}
@Override
public int getTabRunCount(JTabbedPane pane) {
ensureCurrentLayout();
return _runCount;
}
/**
* Returns the tab index which intersects the specified point in the JTabbedPane's coordinate space.
*/
@Override
public int tabForCoordinate(JTabbedPane pane, int x, int y) {
ensureCurrentLayout();
Point p = new Point(x, y);
if (scrollableTabLayoutEnabled()) {
translatePointToTabPanel(x, y, p);
}
int tabCount = _tabPane.getTabCount();
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
p.x -= _tabScroller.viewport.getExpectedViewX();
}
for (int i = 0; i < tabCount; i++) {
if (_rects[i].contains(p.x, p.y)) {
return i;
}
}
return -1;
}
/**
* Returns the bounds of the specified tab in the coordinate space of the JTabbedPane component. This is required
* because the tab rects are by default defined in the coordinate space of the component where they are rendered,
* which could be the JTabbedPane (for WRAP_TAB_LAYOUT) or a ScrollableTabPanel (SCROLL_TAB_LAYOUT). This method
* should be used whenever the tab rectangle must be relative to the JTabbedPane itself and the result should be
* placed in a designated Rectangle object (rather than instantiating and returning a new Rectangle each time). The
* tab index parameter must be a valid tabbed pane tab index (0 to tab count - 1, inclusive). The destination
* rectangle parameter must be a valid <code>Rectangle</code> instance. The handling of invalid parameters is
* unspecified.
*
* @param tabIndex the index of the tab
* @param dest the rectangle where the result should be placed
* @return the resulting rectangle
*/
protected Rectangle getTabBounds(int tabIndex, Rectangle dest) {
if (_rects.length == 0) {
return null;
}
// to make the index is in bound.
if (tabIndex > _rects.length - 1) {
tabIndex = _rects.length - 1;
}
if (tabIndex < 0) {
tabIndex = 0;
}
dest.width = _rects[tabIndex].width;
dest.height = _rects[tabIndex].height;
if (scrollableTabLayoutEnabled()) { // SCROLL_TAB_LAYOUT
// Need to translate coordinates based on viewport location &
// view position
int tabPlacement = _tabPane.getTabPlacement();
Point vpp = _tabScroller.viewport.getLocation();
Point viewp = _tabScroller.viewport.getViewPosition();
dest.x = _rects[tabIndex].x + vpp.x - (((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) ? -_tabScroller.viewport.getExpectedViewX(): viewp.x);
dest.y = _rects[tabIndex].y + vpp.y - viewp.y;
}
else { // WRAP_TAB_LAYOUT
dest.x = _rects[tabIndex].x;
dest.y = _rects[tabIndex].y;
}
return dest;
}
/**
* Returns the tab index which intersects the specified point in the coordinate space of the component where the
* tabs are actually rendered, which could be the JTabbedPane (for WRAP_TAB_LAYOUT) or a ScrollableTabPanel
* (SCROLL_TAB_LAYOUT).
*
* @param x x value of the point
* @param y y value of the point
* @return the tab index in the point (x, y). -1 if no tab could be found.
*/
public int getTabAtLocation(int x, int y) {
ensureCurrentLayout();
int tabCount = _tabPane.getTabCount();
for (int i = 0; i < tabCount; i++) {
if (_rects[i].contains(x, y)) {
return i;
}
}
return -1;
}
/**
* Returns if the point resides in the empty tab area, which means it is in the tab area however no real tab contains
* that point.
*
* @param x x value of the point
* @param y y value of the point
* @return true if the point is in empty tab area. Otherwise false.
*/
public boolean isEmptyTabArea(int x, int y) {
int tabCount = _tabPane.getTabCount();
if (getTabAtLocation(x, y) >= 0 || tabCount <= 0) {
return false;
}
int tabPlacement = _tabPane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (_rects[0].contains(_rects[0].x + 1, y)) {
return true;
}
}
else {
if (_rects[0].contains(x, _rects[0].y + 1)) {
return true;
}
}
return false;
}
/*
* Returns the index of the tab closest to the passed in location, note that the returned tab may not contain the
* location x,y.
*/
private int getClosestTab(int x, int y) {
int min = 0;
int tabCount = Math.min(_rects.length, _tabPane.getTabCount());
int max = tabCount;
int tabPlacement = _tabPane.getTabPlacement();
boolean useX = (tabPlacement == TOP || tabPlacement == BOTTOM);
int want = (useX) ? x : y;
if (!_tabPane.getComponentOrientation().isLeftToRight()) {
want = x - _tabScroller.viewport.getExpectedViewX() - 1;
}
Rectangle[] rects = new Rectangle[_rects.length];
boolean needConvert = false;
if (!useX || _tabPane.getComponentOrientation().isLeftToRight()) {
System.arraycopy(_rects, 0, rects, 0, _rects.length);
}
else {
if (x == _tabScroller.viewport.getViewRect().width) {
return _tabScroller.leadingTabIndex;
}
needConvert = true;
for (int i = 0; i < _rects.length; i++) {
rects[i] = _rects[_rects.length - 1 - i];
}
}
while (min != max) {
int current = (max + min) >> 1;
int minLoc;
int maxLoc;
if (useX) {
minLoc = rects[current].x;
maxLoc = minLoc + rects[current].width;
}
else {
minLoc = rects[current].y;
maxLoc = minLoc + rects[current].height;
}
if (want < minLoc) {
max = current;
if (min == max) {
int tabIndex = Math.max(0, current - 1);
return needConvert ? rects.length - 1 - tabIndex : tabIndex;
}
}
else if (want >= maxLoc) {
min = current;
if (max - min <= 1) {
int tabIndex = Math.max(current + 1, tabCount - 1);
return needConvert ? rects.length - 1 - tabIndex : tabIndex;
}
}
else {
return needConvert ? rects.length - 1 - current : current;
}
}
return needConvert ? rects.length - 1 - min : min;
}
/*
* Returns a point which is translated from the specified point in the JTabbedPane's coordinate space to the
* coordinate space of the ScrollableTabPanel. This is used for SCROLL_TAB_LAYOUT ONLY.
*/
private Point translatePointToTabPanel(int srcx, int srcy, Point dest) {
Point vpp = _tabScroller.viewport.getLocation();
Point viewp = _tabScroller.viewport.getViewPosition();
dest.x = srcx - vpp.x + viewp.x;
dest.y = srcy - vpp.y + viewp.y;
return dest;
}
// VsnetJideTabbedPaneUI methods
protected Component getVisibleComponent() {
return visibleComponent;
}
protected void setVisibleComponent(Component component) {
if (visibleComponent != null && visibleComponent != component &&
visibleComponent.getParent() == _tabPane) {
visibleComponent.setVisible(false);
}
if (component != null && !component.isVisible()) {
component.setVisible(true);
}
visibleComponent = component;
}
protected void assureRectsCreated(int tabCount) {
int rectArrayLen = _rects.length;
if (tabCount != rectArrayLen) {
Rectangle[] tempRectArray = new Rectangle[tabCount];
System.arraycopy(_rects, 0, tempRectArray, 0,
Math.min(rectArrayLen, tabCount));
_rects = tempRectArray;
for (int rectIndex = rectArrayLen; rectIndex < tabCount; rectIndex++) {
_rects[rectIndex] = new Rectangle();
}
}
}
protected void expandTabRunsArray() {
int rectLen = _tabRuns.length;
int[] newArray = new int[rectLen + 10];
System.arraycopy(_tabRuns, 0, newArray, 0, _runCount);
_tabRuns = newArray;
}
protected int getRunForTab(int tabCount, int tabIndex) {
for (int i = 0; i < _runCount; i++) {
int first = _tabRuns[i];
int last = lastTabInRun(tabCount, i);
if (tabIndex >= first && tabIndex <= last) {
return i;
}
}
return 0;
}
protected int lastTabInRun(int tabCount, int run) {
if (_runCount == 1) {
return tabCount - 1;
}
int nextRun = (run == _runCount - 1 ? 0 : run + 1);
if (_tabRuns[nextRun] == 0) {
return tabCount - 1;
}
return _tabRuns[nextRun] - 1;
}
@SuppressWarnings({"UnusedDeclaration"})
protected int getTabRunOverlay(int tabPlacement) {
return _tabRunOverlay;
}
@SuppressWarnings({"UnusedDeclaration"})
protected int getTabRunIndent(int tabPlacement, int run) {
return 0;
}
@SuppressWarnings({"UnusedDeclaration"})
protected boolean shouldPadTabRun(int tabPlacement, int run) {
return _runCount > 1;
}
@SuppressWarnings({"UnusedDeclaration"})
protected boolean shouldRotateTabRuns(int tabPlacement) {
return true;
}
/**
* Returns the text View object required to render stylized text (HTML) for the specified tab or null if no
* specialized text rendering is needed for this tab. This is provided to support html rendering inside tabs.
*
* @param tabIndex the index of the tab
* @return the text view to render the tab's text or null if no specialized rendering is required
*/
protected View getTextViewForTab(int tabIndex) {
if (htmlViews != null && tabIndex < htmlViews.size()) {
return (View) htmlViews.elementAt(tabIndex);
}
return null;
}
protected int calculateTabHeight(int tabPlacement, int tabIndex, FontMetrics metrics) {
int height = 0;
if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
height += (int) v.getPreferredSpan(View.Y_AXIS);
}
else {
// plain text
height += metrics.getHeight();
}
Icon icon = _tabPane.getIconForTab(tabIndex);
Insets tabInsets = getTabInsets(tabPlacement, tabIndex);
if (icon != null) {
height = Math.max(height, icon.getIconHeight());
}
height += tabInsets.top + tabInsets.bottom + 2;
}
else {
Icon icon = _tabPane.getIconForTab(tabIndex);
Insets tabInsets = getTabInsets(tabPlacement, tabIndex);
height = tabInsets.top + tabInsets.bottom + 3;
if (icon != null) {
height += icon.getIconHeight() + _textIconGap;
}
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
height += (int) v.getPreferredSpan(View.X_AXIS);
}
else {
// plain text
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
height += SwingUtilities.computeStringWidth(metrics, title);
}
// for gripper
if (_tabPane.isShowGripper()) {
height += _gripperHeight;
}
if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex)) {
if (_tabPane.isShowCloseButtonOnSelectedTab()) {
if (_tabPane.getSelectedIndex() == tabIndex) {
height += _closeButtons[tabIndex].getPreferredSize().height + _closeButtonRightMargin + _closeButtonLeftMargin;
}
}
else {
height += _closeButtons[tabIndex].getPreferredSize().height + _closeButtonRightMargin + _closeButtonLeftMargin;
}
}
// height += _tabRectPadding;
}
return height;
}
protected int calculateMaxTabHeight(int tabPlacement) {
int tabCount = _tabPane.getTabCount();
int result = 0;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
result = Math.max(calculateTabHeight(tabPlacement, i, metrics), result);
}
return result;
}
protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
int width = 0;
if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
Icon icon = _tabPane.getIconForTab(tabIndex);
Insets tabInsets = getTabInsets(tabPlacement, tabIndex);
width = tabInsets.left + tabInsets.right + 3 + getTabGap();
if (icon != null) {
width += icon.getIconWidth() + _textIconGap;
}
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
width += (int) v.getPreferredSpan(View.X_AXIS);
}
else {
// plain text
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
while (title == null || title.length() < 3)
title += " ";
width += SwingUtilities.computeStringWidth(metrics, title);
}
// for gripper
if (_tabPane.isShowGripper()) {
width += _gripperWidth;
}
if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex)) {
if (_tabPane.isShowCloseButtonOnSelectedTab()) {
if (_tabPane.getSelectedIndex() == tabIndex) {
width += _closeButtons[tabIndex].getPreferredSize().width + _closeButtonRightMargin + _closeButtonLeftMargin;
}
}
else {
width += _closeButtons[tabIndex].getPreferredSize().width + _closeButtonRightMargin + _closeButtonLeftMargin;
}
}
// width += _tabRectPadding;
}
else {
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
width += (int) v.getPreferredSpan(View.Y_AXIS);
}
else {
// plain text
width += metrics.getHeight();
}
Icon icon = _tabPane.getIconForTab(tabIndex);
Insets tabInsets = getTabInsets(tabPlacement, tabIndex);
if (icon != null) {
width = Math.max(width, icon.getIconWidth());
}
width += tabInsets.left + tabInsets.right + 2;
}
return width;
}
protected int calculateMaxTabWidth(int tabPlacement) {
int tabCount = _tabPane.getTabCount();
int result = 0;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
result = Math.max(calculateTabWidth(tabPlacement, i, metrics), result);
}
return result;
}
protected int calculateTabAreaHeight(int tabPlacement, int horizRunCount, int maxTabHeight) {
if (!_tabPane.isTabShown()) {
return 0;
}
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int tabRunOverlay = getTabRunOverlay(tabPlacement);
return (horizRunCount > 0 ? horizRunCount * (maxTabHeight - tabRunOverlay) + tabRunOverlay + tabAreaInsets.top + tabAreaInsets.bottom : 0);
}
protected int calculateTabAreaWidth(int tabPlacement, int vertRunCount, int maxTabWidth) {
if (!_tabPane.isTabShown()) {
return 0;
}
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int tabRunOverlay = getTabRunOverlay(tabPlacement);
return (vertRunCount > 0 ? vertRunCount * (maxTabWidth - tabRunOverlay) + tabRunOverlay + tabAreaInsets.left + tabAreaInsets.right : 0);
}
@SuppressWarnings({"UnusedDeclaration"})
protected Insets getTabInsets(int tabPlacement, int tabIndex) {
rotateInsets(_tabInsets, _currentTabInsets, tabPlacement);
return _currentTabInsets;
}
protected Insets getSelectedTabPadInsets(int tabPlacement) {
rotateInsets(_selectedTabPadInsets, _currentPadInsets, tabPlacement);
return _currentPadInsets;
}
protected Insets getTabAreaInsets(int tabPlacement) {
rotateInsets(_tabAreaInsets, _currentTabAreaInsets, tabPlacement);
return _currentTabAreaInsets;
}
protected Insets getContentBorderInsets(int tabPlacement) {
rotateInsets(_tabPane.getContentBorderInsets(), _currentContentBorderInsets, tabPlacement);
if (_ignoreContentBorderInsetsIfNoTabs && !_tabPane.isTabShown())
return new Insets(0, 0, 0, 0);
else
return _currentContentBorderInsets;
}
protected FontMetrics getFontMetrics(int tab) {
Font font;
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex == tab && _tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (selectedIndex == tab && _tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
return _tabPane.getFontMetrics(font);
}
// Tab Navigation methods
protected void navigateSelectedTab(int direction) {
int tabPlacement = _tabPane.getTabPlacement();
int current = _tabPane.getSelectedIndex();
int tabCount = _tabPane.getTabCount();
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
// If we have no tabs then don't navigate.
if (tabCount <= 0) {
return;
}
int offset;
switch (tabPlacement) {
case NEXT:
selectNextTab(current);
break;
case PREVIOUS:
selectPreviousTab(current);
break;
case LEFT:
case RIGHT:
switch (direction) {
case NORTH:
selectPreviousTabInRun(current);
break;
case SOUTH:
selectNextTabInRun(current);
break;
case WEST:
offset = getTabRunOffset(tabPlacement, tabCount, current, false);
selectAdjacentRunTab(tabPlacement, current, offset);
break;
case EAST:
offset = getTabRunOffset(tabPlacement, tabCount, current, true);
selectAdjacentRunTab(tabPlacement, current, offset);
break;
default:
}
break;
case BOTTOM:
case TOP:
default:
switch (direction) {
case NORTH:
offset = getTabRunOffset(tabPlacement, tabCount, current, false);
selectAdjacentRunTab(tabPlacement, current, offset);
break;
case SOUTH:
offset = getTabRunOffset(tabPlacement, tabCount, current, true);
selectAdjacentRunTab(tabPlacement, current, offset);
break;
case EAST:
if (leftToRight) {
selectNextTabInRun(current);
}
else {
selectPreviousTabInRun(current);
}
break;
case WEST:
if (leftToRight) {
selectPreviousTabInRun(current);
}
else {
selectNextTabInRun(current);
}
break;
default:
}
}
}
protected void selectNextTabInRun(int current) {
int tabCount = _tabPane.getTabCount();
int tabIndex = getNextTabIndexInRun(tabCount, current);
while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) {
tabIndex = getNextTabIndexInRun(tabCount, tabIndex);
}
_tabPane.setSelectedIndex(tabIndex);
}
protected void selectPreviousTabInRun(int current) {
int tabCount = _tabPane.getTabCount();
int tabIndex = getPreviousTabIndexInRun(tabCount, current);
while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) {
tabIndex = getPreviousTabIndexInRun(tabCount, tabIndex);
}
_tabPane.setSelectedIndex(tabIndex);
}
protected void selectNextTab(int current) {
int tabIndex = getNextTabIndex(current);
while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) {
tabIndex = getNextTabIndex(tabIndex);
}
_tabPane.setSelectedIndex(tabIndex);
}
protected void selectPreviousTab(int current) {
int tabIndex = getPreviousTabIndex(current);
while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) {
tabIndex = getPreviousTabIndex(tabIndex);
}
_tabPane.setSelectedIndex(tabIndex);
}
protected void selectAdjacentRunTab(int tabPlacement,
int tabIndex, int offset) {
if (_runCount < 2) {
return;
}
int newIndex;
Rectangle r = _rects[tabIndex];
switch (tabPlacement) {
case LEFT:
case RIGHT:
newIndex = getTabAtLocation(r.x + (r.width >> 1) + offset,
r.y + (r.height >> 1));
break;
case BOTTOM:
case TOP:
default:
newIndex = getTabAtLocation(r.x + (r.width >> 1),
r.y + (r.height >> 1) + offset);
}
if (newIndex != -1) {
while (!_tabPane.isEnabledAt(newIndex) && newIndex != tabIndex) {
newIndex = getNextTabIndex(newIndex);
}
_tabPane.setSelectedIndex(newIndex);
}
}
protected int getTabRunOffset(int tabPlacement, int tabCount,
int tabIndex, boolean forward) {
int run = getRunForTab(tabCount, tabIndex);
int offset;
switch (tabPlacement) {
case LEFT: {
if (run == 0) {
offset = (forward ?
-(calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth) :
-_maxTabWidth);
}
else if (run == _runCount - 1) {
offset = (forward ?
_maxTabWidth :
calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth);
}
else {
offset = (forward ? _maxTabWidth : -_maxTabWidth);
}
break;
}
case RIGHT: {
if (run == 0) {
offset = (forward ?
_maxTabWidth :
calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth);
}
else if (run == _runCount - 1) {
offset = (forward ?
-(calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth) :
-_maxTabWidth);
}
else {
offset = (forward ? _maxTabWidth : -_maxTabWidth);
}
break;
}
case BOTTOM: {
if (run == 0) {
offset = (forward ?
_maxTabHeight :
calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight);
}
else if (run == _runCount - 1) {
offset = (forward ?
-(calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight) :
-_maxTabHeight);
}
else {
offset = (forward ? _maxTabHeight : -_maxTabHeight);
}
break;
}
case TOP:
default: {
if (run == 0) {
offset = (forward ?
-(calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight) :
-_maxTabHeight);
}
else if (run == _runCount - 1) {
offset = (forward ?
_maxTabHeight :
calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight);
}
else {
offset = (forward ? _maxTabHeight : -_maxTabHeight);
}
}
}
return offset;
}
protected int getPreviousTabIndex(int base) {
int tabIndex = (base - 1 >= 0 ? base - 1 : _tabPane.getTabCount() - 1);
return (tabIndex >= 0 ? tabIndex : 0);
}
protected int getNextTabIndex(int base) {
return (base + 1) % _tabPane.getTabCount();
}
protected int getNextTabIndexInRun(int tabCount, int base) {
if (_runCount < 2) {
return getNextTabIndex(base);
}
int currentRun = getRunForTab(tabCount, base);
int next = getNextTabIndex(base);
if (next == _tabRuns[getNextTabRun(currentRun)]) {
return _tabRuns[currentRun];
}
return next;
}
protected int getPreviousTabIndexInRun(int tabCount, int base) {
if (_runCount < 2) {
return getPreviousTabIndex(base);
}
int currentRun = getRunForTab(tabCount, base);
if (base == _tabRuns[currentRun]) {
int previous = _tabRuns[getNextTabRun(currentRun)] - 1;
return (previous != -1 ? previous : tabCount - 1);
}
return getPreviousTabIndex(base);
}
protected int getPreviousTabRun(int baseRun) {
int runIndex = (baseRun - 1 >= 0 ? baseRun - 1 : _runCount - 1);
return (runIndex >= 0 ? runIndex : 0);
}
protected int getNextTabRun(int baseRun) {
return (baseRun + 1) % _runCount;
}
public static void rotateInsets(Insets topInsets, Insets targetInsets, int targetPlacement) {
switch (targetPlacement) {
case LEFT:
targetInsets.top = topInsets.left;
targetInsets.left = topInsets.top;
targetInsets.bottom = topInsets.right;
targetInsets.right = topInsets.bottom;
break;
case BOTTOM:
targetInsets.top = topInsets.bottom;
targetInsets.left = topInsets.left;
targetInsets.bottom = topInsets.top;
targetInsets.right = topInsets.right;
break;
case RIGHT:
targetInsets.top = topInsets.left;
targetInsets.left = topInsets.bottom;
targetInsets.bottom = topInsets.right;
targetInsets.right = topInsets.top;
break;
case TOP:
default:
targetInsets.top = topInsets.top;
targetInsets.left = topInsets.left;
targetInsets.bottom = topInsets.bottom;
targetInsets.right = topInsets.right;
}
}
protected boolean requestFocusForVisibleComponent() {
Component visibleComponent = getVisibleComponent();
Component lastFocused = _tabPane.getLastFocusedComponent(visibleComponent);
if (lastFocused != null && lastFocused.requestFocusInWindow()) {
return true;
}
else if (visibleComponent != null && JideSwingUtilities.passesFocusabilityTest(visibleComponent)) { // visibleComponent.isFocusTraversable()) {
JideSwingUtilities.compositeRequestFocus(visibleComponent);
return true;
}
else if (visibleComponent instanceof JComponent) {
if (((JComponent) visibleComponent).requestDefaultFocus()) {
return true;
}
}
return false;
}
private static class RightAction extends AbstractAction {
private static final long serialVersionUID = -1759791760116532857L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(EAST);
}
}
private static class LeftAction extends AbstractAction {
private static final long serialVersionUID = 8670680299012169408L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(WEST);
}
}
private static class UpAction extends AbstractAction {
private static final long serialVersionUID = -6961702501242792445L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NORTH);
}
}
private static class DownAction extends AbstractAction {
private static final long serialVersionUID = -453174268282628886L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(SOUTH);
}
}
private static class NextAction extends AbstractAction {
private static final long serialVersionUID = -154035573464933924L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NEXT);
}
}
private static class PreviousAction extends AbstractAction {
private static final long serialVersionUID = 2095403667386334865L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(PREVIOUS);
}
}
private static class PageUpAction extends AbstractAction {
private static final long serialVersionUID = 1154273528778779166L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(WEST);
}
else {
ui.navigateSelectedTab(NORTH);
}
}
}
private static class PageDownAction extends AbstractAction {
private static final long serialVersionUID = 4895454480954468453L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(EAST);
}
else {
ui.navigateSelectedTab(SOUTH);
}
}
}
private static class RequestFocusAction extends AbstractAction {
private static final long serialVersionUID = 3791111435639724577L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (!pane.requestFocusInWindow()) {
pane.requestFocus();
}
}
}
private static class RequestFocusForVisibleAction extends AbstractAction {
private static final long serialVersionUID = 6677797853998039155L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.requestFocusForVisibleComponent();
}
}
/**
* Selects a tab in the JTabbedPane based on the String of the action command. The tab selected is based on the
* first tab that has a mnemonic matching the first character of the action command.
*/
private static class SetSelectedIndexAction extends AbstractAction {
private static final long serialVersionUID = 6216635910156115469L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (pane != null && (pane.getUI() instanceof BasicJideTabbedPaneUI)) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
String command = e.getActionCommand();
if (command != null && command.length() > 0) {
int mnemonic = (int) e.getActionCommand().charAt(0);
if (mnemonic >= 'a' && mnemonic <= 'z') {
mnemonic -= ('a' - 'A');
}
Integer index = (Integer) ui._mnemonicToIndexMap
.get(new Integer(mnemonic));
if (index != null && pane.isEnabledAt(index)) {
pane.setSelectedIndex(index);
}
}
}
}
}
protected TabCloseButton createNoFocusButton(int type) {
return new TabCloseButton(type);
}
private static class ScrollTabsForwardAction extends AbstractAction {
private static final long serialVersionUID = 8772616556895545931L;
public ScrollTabsForwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollForward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollForward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsBackwardAction extends AbstractAction {
private static final long serialVersionUID = -426408621939940046L;
public ScrollTabsBackwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollBackward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollBackward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsListAction extends AbstractAction {
private static final long serialVersionUID = 246103712600916771L;
public ScrollTabsListAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.showList"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
if (ui._tabScroller._popup != null && ui._tabScroller._popup.isPopupVisible()) {
ui._tabScroller._popup.hidePopupImmediately();
ui._tabScroller._popup = null;
}
else {
ui._tabScroller.createPopup(pane.getTabPlacement());
}
}
}
}
}
protected void stopOrCancelEditing() {
boolean isEditValid = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
isEditValid = _tabPane.getTabEditingValidator().isValid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (isEditValid)
_tabPane.stopTabEditing();
else
_tabPane.cancelTabEditing();
}
private static class CloseTabAction extends AbstractAction {
private static final long serialVersionUID = 7779678389793199733L;
public CloseTabAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.close"));
}
public void actionPerformed(ActionEvent e) {
JideTabbedPane pane;
Object src = e.getSource();
int index;
boolean closeSelected = false;
if (src instanceof JideTabbedPane) {
pane = (JideTabbedPane) src;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof JideTabbedPane) {
pane = (JideTabbedPane) ((TabCloseButton) src).getParent();
closeSelected = true;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof ScrollableTabPanel) {
pane = (JideTabbedPane) SwingUtilities.getAncestorOfClass(JideTabbedPane.class, (TabCloseButton) src);
closeSelected = false;
}
else {
return; // shouldn't happen
}
if (pane.isTabEditing()) {
((BasicJideTabbedPaneUI) pane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
}
ActionEvent e2 = e;
if (src instanceof TabCloseButton) {
index = ((TabCloseButton) src).getIndex();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
else if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
if (pane.getCloseAction() != null) {
pane.getCloseAction().actionPerformed(e2);
}
else {
if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
if (index >= 0)
pane.removeTabAt(index);
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else if (closeSelected) {
if (pane.getSelectedIndex() >= 0)
pane.removeTabAt(pane.getSelectedIndex());
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else {
int i = ((TabCloseButton) src).getIndex();
if (i != -1) {
int tabIndex = pane.getSelectedIndex();
pane.removeTabAt(i);
if (i < tabIndex) {
pane.setSelectedIndex(tabIndex - 1);
}
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
}
}
}
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabbedPaneLayout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
return calculateSize(false);
}
public Dimension minimumLayoutSize(Container parent) {
return calculateSize(true);
}
protected Dimension calculateSize(boolean minimum) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
Insets contentInsets = getContentBorderInsets(tabPlacement);
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
Dimension zeroSize = new Dimension(0, 0);
int height = contentInsets.top + contentInsets.bottom;
int width = contentInsets.left + contentInsets.right;
int cWidth = 0;
int cHeight = 0;
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
// Determine minimum size required to display largest
// child in each dimension
//
if (_tabPane.isShowTabContent()) {
for (int i = 0; i < _tabPane.getTabCount(); i++) {
Component component = _tabPane.getComponentAt(i);
if (component != null) {
Dimension size = zeroSize;
size = minimum ? component.getMinimumSize() :
component.getPreferredSize();
if (size != null) {
cHeight = Math.max(size.height, cHeight);
cWidth = Math.max(size.width, cWidth);
}
}
}
// Add content border insets to minimum size
width += cWidth;
height += cHeight;
}
int tabExtent;
// Calculate how much space the tabs will need, based on the
// minimum size required to display largest child + content border
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
height = Math.max(height, (minimum ? 0 : calculateMaxTabHeight(tabPlacement)) + tabAreaInsets.top + tabAreaInsets.bottom);
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.width, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.width, tabExtent);
}
width += tabExtent;
break;
case TOP:
case BOTTOM:
default:
if (_tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {
width = Math.max(width, (_tabPane.getTabCount() << 2) +
tabAreaInsets.left + tabAreaInsets.right);
}
else {
width = Math.max(width, (minimum ? 0 : calculateMaxTabWidth(tabPlacement)) +
tabAreaInsets.left + tabAreaInsets.right);
}
if (_tabPane.isTabShown()) {
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.height, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.height, tabExtent);
}
height += tabExtent;
}
}
}
return new Dimension(width + insets.left + insets.right,
height + insets.bottom + insets.top);
}
protected int preferredTabAreaHeight(int tabPlacement, int width) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int rows = 1;
int x = 0;
int maxTabHeight = calculateMaxTabHeight(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabWidth = calculateTabWidth(tabPlacement, i, metrics);
if (x != 0 && x + tabWidth > width) {
rows++;
x = 0;
}
x += tabWidth;
}
total = calculateTabAreaHeight(tabPlacement, rows, maxTabHeight);
}
return total;
}
protected int preferredTabAreaWidth(int tabPlacement, int height) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int columns = 1;
int y = 0;
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabHeight = calculateTabHeight(tabPlacement, i, metrics);
if (y != 0 && y + tabHeight > height) {
columns++;
y = 0;
}
y += tabHeight;
}
total = calculateTabAreaWidth(tabPlacement, columns, _maxTabWidth);
}
return total;
}
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
int cx, cy, cw, ch;
int totalTabWidth = 0;
int totalTabHeight = 0;
Insets contentInsets = getContentBorderInsets(tabPlacement);
Component selectedComponent = _tabPane.getComponentAt(selectedIndex);
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + totalTabWidth + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case RIGHT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case BOTTOM:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case TOP:
default:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + totalTabHeight + contentInsets.top;
}
cw = bounds.width - totalTabWidth -
insets.left - insets.right -
contentInsets.left - contentInsets.right;
ch = bounds.height - totalTabHeight -
insets.top - insets.bottom -
contentInsets.top - contentInsets.bottom;
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
child.setBounds(cx, cy, cw, ch);
}
}
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
public void calculateLayoutInfo() {
int tabCount = _tabPane.getTabCount();
assureRectsCreated(tabCount);
calculateTabRects(_tabPane.getTabPlacement(), tabCount);
}
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int selectedIndex = _tabPane.getSelectedIndex();
int tabRunOverlay;
int i, j;
int x, y;
int returnAt;
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
//
// Calculate bounds within which a tab run must fit
//
switch (tabPlacement) {
case LEFT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = size.width - insets.right - tabAreaInsets.right - _maxTabWidth;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case BOTTOM:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = size.height - insets.bottom - tabAreaInsets.bottom - _maxTabHeight;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
}
tabRunOverlay = getTabRunOverlay(tabPlacement);
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
// Run through tabs and partition them into runs
Rectangle rect;
for (i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabWidth = 0;
rect.x = x;
}
rect.width = calculateTabWidth(tabPlacement, i, metrics);
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
// Never move a TAB down a run if it is in the first column.
// Even if there isn't enough room, moving it to a fresh
// line won't help.
if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.x = x;
}
// Initialize y position in case there's just one run
rect.y = y;
rect.height = _maxTabHeight/* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabHeight = 0;
rect.y = y;
}
rect.height = calculateTabHeight(tabPlacement, i, metrics);
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
// Never move a TAB over a run if it is in the first run.
// Even if there isn't enough room, moving it to a fresh
// column won't help.
if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.y = y;
}
// Initialize x position in case there's just one column
rect.x = x;
rect.width = _maxTabWidth/* - 2 */;
}
if (i == selectedIndex) {
_selectedRun = _runCount - 1;
}
}
if (_runCount > 1) {
// Re-distribute tabs in case last run has leftover space
normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns ? y : x, returnAt);
_selectedRun = getRunForTab(tabCount, selectedIndex);
// Rotate run array so that selected run is first
if (shouldRotateTabRuns(tabPlacement)) {
rotateTabRuns(tabPlacement, _selectedRun);
}
}
// Step through runs from back to front to calculate
// tab y locations and to pad runs appropriately
for (i = _runCount - 1; i >= 0; i--) {
int start = _tabRuns[i];
int next = _tabRuns[i == (_runCount - 1) ? 0 : i + 1];
int end = (next != 0 ? next - 1 : tabCount - 1);
if (!verticalTabRuns) {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.y = y;
rect.x += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == BOTTOM) {
y -= (_maxTabHeight - tabRunOverlay);
}
else {
y += (_maxTabHeight - tabRunOverlay);
}
}
else {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.x = x;
rect.y += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == RIGHT) {
x -= (_maxTabWidth - tabRunOverlay);
}
else {
x += (_maxTabWidth - tabRunOverlay);
}
}
}
// Pad the selected tab so that it appears raised in front
padSelectedTab(tabPlacement, selectedIndex);
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right);
for (i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width;
}
}
}
/*
* Rotates the run-index array so that the selected run is run[0]
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void rotateTabRuns(int tabPlacement, int selectedRun) {
for (int i = 0; i < selectedRun; i++) {
int save = _tabRuns[0];
for (int j = 1; j < _runCount; j++) {
_tabRuns[j - 1] = _tabRuns[j];
}
_tabRuns[_runCount - 1] = save;
}
}
protected void normalizeTabRuns(int tabPlacement, int tabCount,
int start, int max) {
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
int run = _runCount - 1;
boolean keepAdjusting = true;
double weight = 1.25;
// At this point the tab runs are packed to fit as many
// tabs as possible, which can leave the last run with a lot
// of extra space (resulting in very fat tabs on the last run).
// So we'll attempt to distribute this extra space more evenly
// across the runs in order to make the runs look more consistent.
//
// Starting with the last run, determine whether the last tab in
// the previous run would fit (generously) in this run; if so,
// move tab to current run and shift tabs accordingly. Cycle
// through remaining runs using the same algorithm.
//
while (keepAdjusting) {
int last = lastTabInRun(tabCount, run);
int prevLast = lastTabInRun(tabCount, run - 1);
int end;
int prevLastLen;
if (!verticalTabRuns) {
end = _rects[last].x + _rects[last].width;
prevLastLen = (int) (_maxTabWidth * weight);
}
else {
end = _rects[last].y + _rects[last].height;
prevLastLen = (int) (_maxTabHeight * weight * 2);
}
// Check if the run has enough extra space to fit the last tab
// from the previous row...
if (max - end > prevLastLen) {
// Insert tab from previous row and shift rest over
_tabRuns[run] = prevLast;
if (!verticalTabRuns) {
_rects[prevLast].x = start;
}
else {
_rects[prevLast].y = start;
}
for (int i = prevLast + 1; i <= last; i++) {
if (!verticalTabRuns) {
_rects[i].x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_rects[i].y = _rects[i - 1].y + _rects[i - 1].height;
}
}
}
else if (run == _runCount - 1) {
// no more room left in last run, so we're done!
keepAdjusting = false;
}
if (run - 1 > 0) {
// check previous run next...
run -= 1;
}
else {
// check last run again...but require a higher ratio
// of extraspace-to-tabsize because we don't want to
// end up with too many tabs on the last run!
run = _runCount - 1;
weight += .25;
}
}
}
protected void padTabRun(int tabPlacement, int start, int end, int max) {
Rectangle lastRect = _rects[end];
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int runWidth = (lastRect.x + lastRect.width) - _rects[start].x;
int deltaWidth = max - (lastRect.x + lastRect.width);
float factor = (float) deltaWidth / (float) runWidth;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.x = _rects[j - 1].x + _rects[j - 1].width;
}
pastRect.width += Math.round((float) pastRect.width * factor);
}
lastRect.width = max - lastRect.x;
}
else {
int runHeight = (lastRect.y + lastRect.height) - _rects[start].y;
int deltaHeight = max - (lastRect.y + lastRect.height);
float factor = (float) deltaHeight / (float) runHeight;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.y = _rects[j - 1].y + _rects[j - 1].height;
}
pastRect.height += Math.round((float) pastRect.height * factor);
}
lastRect.height = max - lastRect.y;
}
}
protected void padSelectedTab(int tabPlacement, int selectedIndex) {
if (selectedIndex >= 0) {
Rectangle selRect = _rects[selectedIndex];
Insets padInsets = getSelectedTabPadInsets(tabPlacement);
selRect.x -= padInsets.left;
selRect.width += (padInsets.left + padInsets.right);
selRect.y -= padInsets.top;
selRect.height += (padInsets.top + padInsets.bottom);
}
}
}
protected TabSpaceAllocator tryTabSpacer = new TabSpaceAllocator();
protected class TabbedPaneScrollLayout extends TabbedPaneLayout {
@Override
protected int preferredTabAreaHeight(int tabPlacement, int width) {
return calculateMaxTabHeight(tabPlacement);
}
@Override
protected int preferredTabAreaWidth(int tabPlacement, int height) {
return calculateMaxTabWidth(tabPlacement);
}
@Override
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
JViewport viewport = null;
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
int tx, ty, tw, th; // tab area bounds
int cx, cy, cw, ch; // content area bounds
Insets contentInsets = getContentBorderInsets(tabPlacement);
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = insets.left;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
}
}
// calculate content area bounds
cx = tx + tw + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case RIGHT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount,
_maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = bounds.width - insets.right - tw;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
tx = bounds.width - insets.right - tw;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
tx = bounds.width - insets.right - tw;
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case BOTTOM:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = bounds.height - insets.bottom - th;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
break;
case TOP:
default:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = insets.top;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + th + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
}
// if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (tw < _rects[0].width + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
// else {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (th < _rects[0].height + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
if (child instanceof ScrollableTabViewport) {
viewport = (JViewport) child;
// Rectangle viewRect = viewport.getViewRect();
int vw = tw;
int vh = th;
int numberOfButtons = getNumberOfTabButtons();
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (totalTabHeight > th || isShowTabButtons()) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
// if (totalTabHeight - viewRect.y <= vh) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vh = totalTabHeight - viewRect.y;
// }
}
else {
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
}
if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) {
vh += getLayoutSize();
}
break;
case BOTTOM:
case TOP:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (isShowTabButtons() || !widthEnough) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Need to allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
// if (totalTabWidth - viewRect.x <= vw) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vw = totalTabWidth - viewRect.x;
// }
}
else {
// Allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
}
if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) {
vw += getLayoutSize();
if (!leftToRight) {
tx -= getLayoutSize();
}
}
break;
}
child.setBounds(tx, ty, vw, vh);
}
else if (child instanceof TabCloseButton) {
TabCloseButton scrollbutton = (TabCloseButton) child;
if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) {
Dimension bsize = scrollbutton.getPreferredSize();
int bx = 0;
int by = 0;
int bw = bsize.width;
int bh = bsize.height;
boolean visible = false;
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) {
int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
}
bx = tx + 2;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
bx = tx + 2;
}
}
if (isTabTrailingComponentVisible()) {
by = by - tsize.height;
}
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.width >= _rects[0].width) {
if (tabPlacement == LEFT) {
bx += lsize.width - _rects[0].width;
temp = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.width >= _rects[0].width
&& temp < tsize.width) {
if (tabPlacement == LEFT) {
bx += tsize.width - _rects[0].width;
}
}
}
break;
case TOP:
case BOTTOM:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (_tabPane.isTabShown() && (isShowTabButtons() || !widthEnough)) {
int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON
// NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
bx = insets.left - 5;
}
}
else {
visible = false;
bx = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (1 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
}
by = ((th - bsize.height) >> 1) + ty;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
visible = false;
bx = 0;
}
by = ((th - bsize.height) >> 1) + ty;
}
}
if (isTabTrailingComponentVisible()) {
bx -= tsize.width;
}
temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.height >= _rects[0].height) {
if (tabPlacement == TOP) {
by = ty + 2 + lsize.height - _rects[0].height;
temp = lsize.height;
}
else {
by = ty + 2;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.height >= _rects[0].height
&& temp < tsize.height) {
if (tabPlacement == TOP) {
by = ty + 2 + tsize.height - _rects[0].height;
}
else {
by = ty + 2;
}
}
}
}
child.setVisible(visible);
if (visible) {
child.setBounds(bx, by, bw, bh);
}
}
else {
scrollbutton.setBounds(0, 0, 0, 0);
}
}
else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) {
if (_tabPane.isShowTabContent()) {
// All content children...
child.setBounds(cx, cy, cw, ch);
}
else {
child.setBounds(0, 0, 0, 0);
}
}
}
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
}
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
if (!leftToRight && !verticalTabRuns && viewport != null && !viewport.getSize().equals(_tabPane.getSize())) {
int offset = _tabPane.getWidth() - viewport.getWidth();
for (Rectangle rect : _rects) {
rect.x -= offset;
}
}
updateCloseButtons();
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
@Override
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
int x = tabAreaInsets.left;
int y = tabAreaInsets.top;
//
// Calculate bounds within which a tab run must fit
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < lsize.width) {
_maxTabWidth = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < tsize.width) {
_maxTabWidth = tsize.width;
}
}
}
break;
case BOTTOM:
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < lsize.height) {
_maxTabHeight = lsize.height;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < tsize.height) {
_maxTabHeight = tsize.height;
}
}
}
}
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
_selectedRun = 0;
_runCount = 1;
// Run through tabs and lay them out in a single run
Rectangle rect;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_maxTabWidth = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.x = x + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.x = x;
}
}
rect.width = calculateTabWidth(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
rect.y = y;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < lsize.height) {
rect.y = y + lsize.height - _maxTabHeight - 2;
temp = lsize.height;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < tsize.height
&& temp < tsize.height) {
rect.y = y + tsize.height - _maxTabHeight - 2;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
rect.height = calculateMaxTabHeight(tabPlacement);///* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_maxTabHeight = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.y = y + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.y = y;
}
}
rect.height = calculateTabHeight(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
rect.x = x;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < lsize.width) {
rect.x = x + lsize.width - _maxTabWidth - 2;
temp = lsize.width;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < tsize.width
&& temp < tsize.width) {
rect.x = x + tsize.width - _maxTabWidth - 2;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
rect.width = calculateMaxTabWidth(tabPlacement)/* - 2 */;
}
}
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right) - _tabScroller.viewport.getLocation().x;
if (isTabLeadingComponentVisible()) {
rightMargin -= lsize.width;
}
int offset = 0;
if (isTabTrailingComponentVisible()) {
offset += tsize.width;
}
for (int i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width - offset + tabAreaInsets.left;
// if(i == tabCount - 1) {
// _rects[i].width += getLeftMargin();
// _rects[i].x -= getLeftMargin();
// }
}
}
ensureCurrentRects(getLeftMargin(), tabCount);
}
}
protected void ensureCurrentRects(int leftMargin, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
int totalWidth = 0;
int totalHeight = 0;
boolean verticalTabRuns = (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT);
boolean ltr = _tabPane.getComponentOrientation().isLeftToRight();
if (tabCount == 0) {
return;
}
Rectangle r = _rects[tabCount - 1];
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (verticalTabRuns) {
totalHeight = r.y + r.height;
if (_tabLeadingComponent != null) {
totalHeight -= lsize.height;
}
}
else {
// totalWidth = r.x + r.width;
for (Rectangle rect : _rects) {
totalWidth += rect.width;
}
if (ltr) {
totalWidth += _rects[0].x;
}
else {
totalWidth += size.width - _rects[0].x - _rects[0].width - _tabScroller.viewport.getLocation().x;
}
if (_tabLeadingComponent != null) {
totalWidth -= lsize.width;
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {// LayOut Style is Size to Fix
if (verticalTabRuns) {
int availHeight;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom - leftMargin - getTabRightPadding();// give the first tab extra space
}
else {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom;
}
if (_tabPane.isShowCloseButton()) {
availHeight -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availHeight = availHeight - lsize.height;
}
if (isTabTrailingComponentVisible()) {
availHeight = availHeight - tsize.height;
}
int numberOfButtons = getNumberOfTabButtons();
availHeight -= _buttonSize * numberOfButtons;
if (totalHeight > availHeight) { // shrink is necessary
// calculate each tab width
int tabHeight = availHeight / tabCount;
totalHeight = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
_rects[k].height = tabHeight;
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
tabRect.y = totalHeight + leftMargin;// give the first tab extra space
}
else {
tabRect.y = totalHeight;
}
totalHeight += tabRect.height;
}
}
}
else {
int availWidth;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right - leftMargin - getTabRightPadding();
}
else {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right;
}
if (_tabPane.isShowCloseButton()) {
availWidth -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availWidth -= lsize.width;
}
if (isTabTrailingComponentVisible()) {
availWidth -= tsize.width;
}
int numberOfButtons = getNumberOfTabButtons();
availWidth -= _buttonSize * numberOfButtons;
if (totalWidth > availWidth) { // shrink is necessary
// calculate each tab width
int tabWidth = availWidth / tabCount;
int gripperWidth = _tabPane.isShowGripper() ? _gripperWidth
: 0;
if (tabWidth < _textIconGap + _fitStyleTextMinWidth
+ _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleIconMinWidth + gripperWidth) // cannot
// hold any text but can hold an icon
tabWidth = _fitStyleIconMinWidth + gripperWidth;
if (tabWidth < _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleFirstTabMargin + gripperWidth) // cannot
// hold any icon but gripper
tabWidth = _fitStyleFirstTabMargin + gripperWidth;
tryTabSpacer.reArrange(_rects, insets, availWidth);
}
totalWidth = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
if (ltr) {
tabRect.x = totalWidth + leftMargin;// give the first tab extra space when the style is not box style
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width + leftMargin;// give the first tab extra space when the style is not box style
}
}
else {
if (ltr) {
tabRect.x = totalWidth;
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width;
}
}
totalWidth += tabRect.width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIXED) {// LayOut Style is Fix
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
_rects[k].height = _fixedStyleRectSize;// + _rectSizeExtend * 2;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].height += _closeButtons[k].getPreferredSize().height;
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
_rects[k].width = _fixedStyleRectSize;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].width += _closeButtons[k].getPreferredSize().width;
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED) {// LayOut Style is Compressed
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab() && !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].height = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].height = icon.getIconHeight() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].height = _rects[k].height + _closeButtons[k].getPreferredSize().height + _compressedStyleCloseButtonMarginVertical;
}
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab()
&& !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].width = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].width = icon.getIconWidth() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].width = _rects[k].width + _closeButtons[k].getPreferredSize().width + _compressedStyleCloseButtonMarginHorizon;
}
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
totalWidth += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalWidth += lsize.width;
}
}
else {
totalHeight += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalHeight += tsize.height;
}
}
_tabScroller.tabPanel.setPreferredSize(new Dimension(totalWidth, totalHeight));
}
protected class ActivateTabAction extends AbstractAction {
int _tabIndex;
private static final long serialVersionUID = 3270152106579039554L;
public ActivateTabAction(String name, Icon icon, int tabIndex) {
super(name, icon);
_tabIndex = tabIndex;
}
public void actionPerformed(ActionEvent e) {
_tabPane.setSelectedIndex(_tabIndex);
}
}
protected ListCellRenderer getTabListCellRenderer() {
return _tabPane.getTabListCellRenderer();
}
public class ScrollableTabSupport implements ChangeListener {
public ScrollableTabViewport viewport;
public ScrollableTabPanel tabPanel;
public TabCloseButton scrollForwardButton;
public TabCloseButton scrollBackwardButton;
public TabCloseButton listButton;
public TabCloseButton closeButton;
public int leadingTabIndex;
private Point tabViewPosition = new Point(0, 0);
public JidePopup _popup;
@SuppressWarnings({"UnusedDeclaration"})
ScrollableTabSupport(int tabPlacement) {
viewport = new ScrollableTabViewport();
tabPanel = new ScrollableTabPanel();
viewport.setView(tabPanel);
viewport.addChangeListener(this);
scrollForwardButton = createNoFocusButton(TabCloseButton.EAST_BUTTON);
scrollForwardButton.setName(BUTTON_NAME_SCROLL_FORWARD);
scrollBackwardButton = createNoFocusButton(TabCloseButton.WEST_BUTTON);
scrollBackwardButton.setName(BUTTON_NAME_SCROLL_BACKWARD);
scrollForwardButton.setBackground(viewport.getBackground());
scrollBackwardButton.setBackground(viewport.getBackground());
listButton = createNoFocusButton(TabCloseButton.LIST_BUTTON);
listButton.setName(BUTTON_NAME_TAB_LIST);
listButton.setBackground(viewport.getBackground());
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName(BUTTON_NAME_CLOSE);
closeButton.setBackground(viewport.getBackground());
}
public void createPopupMenu(int tabPlacement) {
JPopupMenu popup = new JPopupMenu();
int totalCount = _tabPane.getTabCount();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
for (int i = 0; i < totalCount; i++) {
if (_tabPane.isEnabledAt(i)) {
JMenuItem item;
popup.add(item = new JCheckBoxMenuItem(new ActivateTabAction(_tabPane.getTitleAt(i), _tabPane.getIconForTab(i), i)));
item.setToolTipText(_tabPane.getToolTipTextAt(i));
item.setSelected(selectedIndex == i);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
}
}
Dimension preferredSize = popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
switch (tabPlacement) {
case TOP:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y + bounds.height);
break;
case BOTTOM:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y - preferredSize.height);
break;
case LEFT:
popup.show(_tabPane, bounds.x + bounds.width, bounds.y + bounds.height - preferredSize.height);
break;
case RIGHT:
popup.show(_tabPane, bounds.x - preferredSize.width, bounds.y + bounds.height - preferredSize.height);
break;
}
}
public void createPopup(int tabPlacement) {
final JList list = new JList() {
// override this method to disallow deselect by ctrl-click
@Override
public void removeSelectionInterval(int index0, int index1) {
super.removeSelectionInterval(index0, index1);
if (getSelectedIndex() == -1) {
setSelectedIndex(index0);
}
}
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension preferredScrollableViewportSize = super.getPreferredScrollableViewportSize();
if (preferredScrollableViewportSize.width < 150) {
preferredScrollableViewportSize.width = 150;
}
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredScrollableViewportSize.width >= screenWidth) {
preferredScrollableViewportSize.width = screenWidth;
}
return preferredScrollableViewportSize;
}
@Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredSize.width >= screenWidth) {
preferredSize.width = screenWidth;
}
return preferredSize;
}
};
new Sticky(list);
list.setBackground(_tabListBackground);
JScrollPane scroller = new JScrollPane(list);
scroller.setBorder(BorderFactory.createEmptyBorder());
scroller.getViewport().setOpaque(false);
scroller.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(_tabListBackground);
panel.setOpaque(true);
panel.add(scroller);
panel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
if (_popup != null) {
if (_popup.isPopupVisible()) {
_popup.hidePopupImmediately();
}
_popup = null;
}
_popup = com.jidesoft.popup.JidePopupFactory.getSharedInstance().createPopup();
_popup.setPopupBorder(BorderFactory.createLineBorder(_darkShadow));
_popup.add(panel);
_popup.addExcludedComponent(listButton);
_popup.setDefaultFocusComponent(list);
DefaultListModel listModel = new DefaultListModel();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
int totalCount = _tabPane.getTabCount();
for (int i = 0; i < totalCount; i++) {
listModel.addElement(_tabPane);
}
list.setCellRenderer(getTabListCellRenderer());
list.setModel(listModel);
list.setSelectedIndex(selectedIndex);
list.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
componentSelected(list);
}
}
public void keyReleased(KeyEvent e) {
}
});
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
componentSelected(list);
}
});
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Insets insets = panel.getInsets();
int max = (PortingUtils.getLocalScreenSize(_tabPane).height - insets.top - insets.bottom) / list.getCellBounds(0, 0).height;
if (listModel.getSize() > max) {
list.setVisibleRowCount(max);
}
else {
list.setVisibleRowCount(listModel.getSize());
}
_popup.setOwner(_tabPane);
_popup.removeExcludedComponent(_tabPane);
Dimension size = _popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
Point p = listButton.getLocationOnScreen();
bounds.x = p.x;
bounds.y = p.y;
int x;
int y;
switch (tabPlacement) {
case TOP:
default:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y + bounds.height + 2;
break;
case BOTTOM:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y - size.height - 2;
break;
case LEFT:
x = bounds.x + bounds.width + 2;
y = bounds.y + bounds.height - size.height;
break;
case RIGHT:
x = bounds.x - size.width - 2;
y = bounds.y + bounds.height - size.height;
break;
}
Rectangle screenBounds = PortingUtils.getScreenBounds(_tabPane);
int right = x + size.width + 3;
int bottom = y + size.height + 3;
if (right > screenBounds.x + screenBounds.width) {
x -= right - screenBounds.x - screenBounds.width; // move left so that the whole popup can fit in
}
if (x < screenBounds.x) {
x = screenBounds.x; // move right so that the whole popup can fit in
}
if (bottom > screenBounds.height) {
y -= bottom - screenBounds.height;
}
if (y < screenBounds.y) {
y = screenBounds.y;
}
_popup.showPopup(x, y);
}
private void componentSelected(JList list) {
int tabIndex = list.getSelectedIndex();
if (tabIndex != -1 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
Runnable runnable = new Runnable() {
public void run() {
_tabPane.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
Runnable runnable = new Runnable() {
public void run() {
if (lastFocused != null) {
lastFocused.requestFocus();
}
else if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocus();
}
}
};
SwingUtilities.invokeLater(runnable);
}
});
}
else {
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
Runnable runnable = new Runnable() {
public void run() {
lastFocused.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
else {
Container container;
if (comp instanceof Container) {
container = (Container) comp;
}
else {
container = comp.getFocusCycleRootAncestor();
}
FocusTraversalPolicy traversalPolicy = container.getFocusTraversalPolicy();
Component focusComponent;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(container);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(container);
}
}
else if (comp instanceof Container) {
// not sure if it is correct
focusComponent = findFocusableComponent((Container) comp);
}
else {
focusComponent = comp;
}
if (focusComponent != null) {
final Component theComponent = focusComponent;
Runnable runnable = new Runnable() {
public void run() {
theComponent.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
}
}
ensureActiveTabIsVisible(false);
_popup.hidePopupImmediately();
_popup = null;
}
}
private Component findFocusableComponent(Container parent) {
FocusTraversalPolicy traversalPolicy = parent.getFocusTraversalPolicy();
Component focusComponent = null;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(parent);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(parent);
}
}
if (focusComponent != null) {
return focusComponent;
}
int i = 0;
while (i < parent.getComponentCount()) {
Component comp = parent.getComponent(i);
if (comp instanceof Container) {
focusComponent = findFocusableComponent((Container) comp);
if (focusComponent != null) {
return focusComponent;
}
}
else if (comp.isFocusable()) {
return comp;
}
i++;
}
if (parent.isFocusable()) {
return parent;
}
return null;
}
public void scrollForward(int tabPlacement) {
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (viewRect.width >= viewSize.width - viewRect.x) {
return; // no room left to scroll
}
}
else { // tabPlacement == LEFT || tabPlacement == RIGHT
if (viewRect.height >= viewSize.height - viewRect.y) {
return;
}
}
setLeadingTabIndex(tabPlacement, leadingTabIndex + 1);
}
public void scrollBackward(int tabPlacement) {
setLeadingTabIndex(tabPlacement, leadingTabIndex > 0 ? leadingTabIndex - 1 : 0);
}
public void setLeadingTabIndex(int tabPlacement, int index) {
// make sure the index is in range
if (index < 0 || index >= _tabPane.getTabCount()) {
return;
}
leadingTabIndex = index;
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
switch (tabPlacement) {
case TOP:
case BOTTOM:
tabViewPosition.y = 0;
if (_tabPane.getComponentOrientation().isLeftToRight()) {
tabViewPosition.x = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].x;
}
else {
tabViewPosition.x = (_rects.length <= 0 || leadingTabIndex == 0) ? 0 : _rects[0].x - _rects[leadingTabIndex].x + (_rects[0].width - _rects[leadingTabIndex].width) + 25;
}
if ((viewSize.width - tabViewPosition.x) < viewRect.width) {
tabViewPosition.x = viewSize.width - viewRect.width;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewSize.width - tabViewPosition.x,
// viewRect.height);
// System.out.println("setExtendedSize: " + extentSize);
// viewport.setExtentSize(extentSize);
}
break;
case LEFT:
case RIGHT:
tabViewPosition.x = 0;
tabViewPosition.y = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].y;
if ((viewSize.height - tabViewPosition.y) < viewRect.height) {
tabViewPosition.y = viewSize.height - viewRect.height;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewRect.width,
// viewSize.height - tabViewPosition.y);
// viewport.setExtentSize(extentSize);
}
break;
}
viewport.setViewPosition(tabViewPosition);
_tabPane.repaint();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight() && tabViewPosition.x == 0) {
// In current workaround, tabViewPosition set to 0 cannot trigger state change event
stateChanged(new ChangeEvent(viewport));
}
}
public void stateChanged(ChangeEvent e) {
if (_tabPane == null) return;
ensureCurrentLayout();
JViewport viewport = (JViewport) e.getSource();
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Rectangle vpRect = viewport.getBounds();
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
leadingTabIndex = getClosestTab(viewRect.x + viewRect.width, viewRect.y + viewRect.height);
if (leadingTabIndex < 0) {
leadingTabIndex = 0;
}
}
else {
leadingTabIndex = getClosestTab(viewRect.x, viewRect.y);
}
// If the tab isn't right aligned, adjust it.
if (leadingTabIndex < _rects.length && leadingTabIndex >= _rects.length) {
switch (tabPlacement) {
case TOP:
case BOTTOM:
if (_rects[leadingTabIndex].x < viewRect.x) {
leadingTabIndex++;
}
break;
case LEFT:
case RIGHT:
if (_rects[leadingTabIndex].y < viewRect.y) {
leadingTabIndex++;
}
break;
}
}
Insets contentInsets = getContentBorderInsets(tabPlacement);
int checkX;
switch (tabPlacement) {
case LEFT:
_tabPane.repaint(vpRect.x + vpRect.width, vpRect.y, contentInsets.left, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case RIGHT:
_tabPane.repaint(vpRect.x - contentInsets.right, vpRect.y, contentInsets.right, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case BOTTOM:
_tabPane.repaint(vpRect.x, vpRect.y - contentInsets.bottom, vpRect.width, contentInsets.bottom);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
break;
case TOP:
default:
_tabPane.repaint(vpRect.x, vpRect.y + vpRect.height, vpRect.width, contentInsets.top);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
}
if (SystemInfo.isJdk15Above()) {
_tabPane.setComponentZOrder(_tabScroller.scrollForwardButton, 0);
_tabPane.setComponentZOrder(_tabScroller.scrollBackwardButton, 0);
}
_tabScroller.scrollForwardButton.repaint();
_tabScroller.scrollBackwardButton.repaint();
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount()) {
closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex));
}
}
@Override
public String toString() {
return "viewport.viewSize=" + viewport.getViewSize() + "\n" +
"viewport.viewRectangle=" + viewport.getViewRect() + "\n" +
"leadingTabIndex=" + leadingTabIndex + "\n" +
"tabViewPosition=" + tabViewPosition;
}
}
public class ScrollableTabViewport extends JViewport implements UIResource {
int _expectViewX = 0;
boolean _protectView = false;
public ScrollableTabViewport() {
super();
setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
setOpaque(false);
setLayout(new ViewportLayout() {
private static final long serialVersionUID = -1069760662716244442L;
@Override
public void layoutContainer(Container parent) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
_protectView = true;
}
try {
super.layoutContainer(parent);
}
finally {
_protectView = false;
}
}
});
}
/**
* Gets the background color of this component.
*
* @return this component's background color; if this component does not have a background color, the background
* color of its parent is returned
*/
@Override
public Color getBackground() {
return UIDefaultsLookup.getColor("JideTabbedPane.background");
}
// workaround for swing bug
@Override
public void setViewPosition(Point p) {
int oldX = _expectViewX;
_expectViewX = p.x;
super.setViewPosition(p); // to trigger state change event, so the adjustment for RTL need to be done at ScrollableTabPanel#setBounds()
if (_protectView) {
_expectViewX = oldX;
Point savedPosition = new Point(oldX, p.y);
super.setViewPosition(savedPosition);
}
}
public int getExpectedViewX() {
return _expectViewX;
}
}
public class ScrollableTabPanel extends JPanel implements UIResource {
public ScrollableTabPanel() {
setLayout(null);
}
@Override
public boolean isOpaque() {
return false;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_tabPane.isOpaque()) {
if (getTabShape() == JideTabbedPane.SHAPE_BOX) {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"));
}
else {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground"));
}
g.fillRect(0, 0, getWidth(), getHeight());
}
paintTabArea(g, _tabPane.getTabPlacement(), _tabPane.getSelectedIndex(), this);
}
// workaround for swing bug
@Override
public void scrollRectToVisible(Rectangle aRect) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
int startX = aRect.x + _tabScroller.viewport.getExpectedViewX();
if (startX < 0) {
int i;
for (i = _tabScroller.leadingTabIndex; i < _rects.length; i++) {
startX += _rects[i].width;
if (startX >= 0) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.min(i + 1, _rects.length - 1));
}
else if (startX > aRect.x + aRect.width) {
int i;
for (i = _tabScroller.leadingTabIndex - 1; i >= 0; i--) {
startX -= _rects[i].width;
if (startX <= aRect.x + aRect.width) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.max(i, 0));
}
return;
}
super.scrollRectToVisible(aRect);
}
// workaround for swing bug
@Override
public void setBounds(int x, int y, int width, int height) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
super.setBounds(0, y, width, height);
return;
}
super.setBounds(x, y, width, height);
}
// workaround for swing bug
// http://developer.java.sun.com/developer/bugParade/bugs/4668865.html
@Override
public void setToolTipText(String text) {
_tabPane.setToolTipText(text);
}
@Override
public String getToolTipText() {
return _tabPane.getToolTipText();
}
@Override
public String getToolTipText(MouseEvent event) {
return _tabPane.getToolTipText(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public Point getToolTipLocation(MouseEvent event) {
return _tabPane.getToolTipLocation(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public JToolTip createToolTip() {
return _tabPane.createToolTip();
}
}
protected Color _closeButtonSelectedColor = new Color(255, 162, 165);
protected Color _closeButtonColor = Color.BLACK;
protected Color _popupColor = Color.BLACK;
/**
* Close button on the tab.
*/
public class TabCloseButton extends JButton implements MouseMotionListener, MouseListener, UIResource {
public static final int CLOSE_BUTTON = 0;
public static final int EAST_BUTTON = 1;
public static final int WEST_BUTTON = 2;
public static final int NORTH_BUTTON = 3;
public static final int SOUTH_BUTTON = 4;
public static final int LIST_BUTTON = 5;
private int _type;
private int _index = -1;
private boolean _mouseOver = false;
private boolean _mousePressed = false;
/**
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
@Override
public void updateUI() {
super.updateUI();
setMargin(new Insets(0, 0, 0, 0));
setBorder(BorderFactory.createEmptyBorder());
setFocusPainted(false);
setFocusable(false);
setRequestFocusEnabled(false);
String name = getName();
if (name != null) setToolTipText(getResourceString(name));
}
public TabCloseButton() {
this(CLOSE_BUTTON);
}
public TabCloseButton(int type) {
addMouseMotionListener(this);
addMouseListener(this);
setFocusPainted(false);
setFocusable(false);
setType(type);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(5, 5);
}
public int getIndex() {
return _index;
}
public void setIndex(int index) {
_index = index;
}
@Override
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
@Override
protected void paintComponent(Graphics g) {
if (!isEnabled()) {
setMouseOver(false);
setMousePressed(false);
}
if (isMouseOver() && isMousePressed()) {
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
else if (isMouseOver()) {
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
g.setColor(UIDefaultsLookup.getColor("controlShadow").darker());
int centerX = getWidth() >> 1;
int centerY = getHeight() >> 1;
int type = getType();
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
if (type == EAST_BUTTON) {
type = WEST_BUTTON;
}
else if (type == WEST_BUTTON) {
type = EAST_BUTTON;
}
}
switch (type) {
case CLOSE_BUTTON:
if (isEnabled()) {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX - 4, centerY - 3, centerX + 2, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
g.drawLine(centerX + 2, centerY - 3, centerX - 4, centerY + 3);
}
else {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
}
break;
case EAST_BUTTON:
//
// |
// ||
// |||
// ||||
// ||||*
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX + 2, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 3, y - 3, x - 3, y + 3);
g.drawLine(x - 2, y - 2, x - 2, y + 2);
g.drawLine(x - 1, y - 1, x - 1, y + 1);
g.drawLine(x, y, x, y);
}
else {
g.drawLine(x - 4, y - 4, x, y);
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
else {
int x = centerX + 3, y = centerY - 2; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 7, y + 1, x - 1, y + 1);
g.drawLine(x - 6, y + 2, x - 2, y + 2);
g.drawLine(x - 5, y + 3, x - 3, y + 3);
g.drawLine(x - 4, y + 4, x - 4, y + 4);
}
else {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 8, y, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
}
break;
case WEST_BUTTON: {
//
// |
// ||
// |||
// ||||
// *||||
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX - 3, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x, y);
g.drawLine(x + 1, y - 1, x + 1, y + 1);
g.drawLine(x + 2, y - 2, x + 2, y + 2);
g.drawLine(x + 3, y - 3, x + 3, y + 3);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
else {
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x, y, x + 4, y + 4);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
}
else {
int x = centerX - 5, y = centerY + 3; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x + 8, y);
g.drawLine(x + 1, y - 1, x + 7, y - 1);
g.drawLine(x + 2, y - 2, x + 6, y - 2);
g.drawLine(x + 3, y - 3, x + 5, y - 3);
g.drawLine(x + 4, y - 4, x + 4, y - 4);
}
else {
g.drawLine(x, y, x + 8, y);
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x + 8, y, x + 4, y - 4);
}
}
}
break;
}
case LIST_BUTTON: {
int x = centerX + 2, y = centerY; // start point. mark as
// * above
g.drawLine(x - 6, y - 4, x - 6, y + 4);
g.drawLine(x + 1, y - 4, x + 1, y + 4);
g.drawLine(x - 6, y - 4, x + 1, y - 4);
g.drawLine(x - 4, y - 2, x - 1, y - 2);
g.drawLine(x - 4, y, x - 1, y);
g.drawLine(x - 4, y + 2, x - 1, y + 2);
g.drawLine(x - 6, y + 4, x + 1, y + 4);
break;
}
}
}
@Override
public boolean isFocusable() {
return false;
}
@Override
public void requestFocus() {
}
@Override
public boolean isOpaque() {
return false;
}
public boolean scrollsForward() {
return getType() == EAST_BUTTON || getType() == SOUTH_BUTTON;
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
setMousePressed(false);
}
public void mousePressed(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(true);
repaint();
}
public void mouseReleased(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(false);
setMouseOver(false);
}
public void mouseEntered(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseExited(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(false);
setMousePressed(false);
repaint();
_tabScroller.tabPanel.repaint();
}
public int getType() {
return _type;
}
public void setType(int type) {
_type = type;
}
public boolean isMouseOver() {
return _mouseOver;
}
public void setMouseOver(boolean mouseOver) {
_mouseOver = mouseOver;
}
public boolean isMousePressed() {
return _mousePressed;
}
public void setMousePressed(boolean mousePressed) {
_mousePressed = mousePressed;
}
}
// Controller: event listeners
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class PropertyChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
String name = e.getPropertyName();
if ("mnemonicAt".equals(name)) {
updateMnemonics();
pane.repaint();
}
else if ("displayedMnemonicIndexAt".equals(name)) {
pane.repaint();
}
else if (name.equals("indexForTitle")) {
int index = (Integer) e.getNewValue();
String title = getCurrentDisplayTitleAt(_tabPane, index);
if (BasicHTML.isHTMLString(title)) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(_tabPane, title);
htmlViews.setElementAt(v, index);
}
}
else {
if (htmlViews != null && htmlViews.elementAt(index) != null) {
htmlViews.setElementAt(null, index);
}
}
updateMnemonics();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(
_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(false);
}
}
else if (name.equals("tabLayoutPolicy")) {
_tabPane.updateUI();
}
else if (name.equals("closeTabAction")) {
updateCloseAction();
}
else if (name.equals(JideTabbedPane.PROPERTY_DRAG_OVER_DISABLED)) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_COLOR_PROVIDER)) {
_tabPane.repaint();
}
else if (name.equals("locale")) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.BOLDACTIVETAB_PROPERTY)) {
getTabPanel().invalidate();
_tabPane.invalidate();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_LEADING_COMPONENT)) {
ensureCurrentLayout();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(false);
_tabPane.remove(_tabLeadingComponent);
}
_tabLeadingComponent = (Component) e.getNewValue();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(true);
_tabPane.add(_tabLeadingComponent);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_TRAILING_COMPONENT)) {
ensureCurrentLayout();
if (_tabTrailingComponent != null) {
_tabTrailingComponent.setVisible(false);
_tabPane.remove(_tabTrailingComponent);
}
_tabTrailingComponent = (Component) e.getNewValue();
if (_tabTrailingComponent != null) {
_tabPane.add(_tabTrailingComponent);
_tabTrailingComponent.setVisible(true);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.SHRINK_TAB_PROPERTY) ||
name.equals(JideTabbedPane.HIDE_IF_ONE_TAB_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_AREA_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_CONTENT_PROPERTY) ||
name.equals(JideTabbedPane.BOX_STYLE_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.TAB_CLOSABLE_PROPERTY) ||
name.equals(JideTabbedPane.PROPERTY_TAB_SHAPE) ||
name.equals(JideTabbedPane.PROPERTY_COLOR_THEME) ||
name.equals(JideTabbedPane.PROPERTY_TAB_RESIZE_MODE) ||
name.equals(JideTabbedPane.SHOW_TAB_BUTTONS_PROPERTY)) {
if ((name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY))
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
ensureCloseButtonCreated();
}
_tabPane.updateUI();
}
+ else if (name.equals("__index_to_remove__")) {
+ setVisibleComponent(null);
+ }
}
}
protected void updateCloseAction() {
ensureCloseButtonCreated();
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabSelectionHandler implements ChangeListener {
public void stateChanged(ChangeEvent e) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
ensureCloseButtonCreated();
Runnable runnable = new Runnable() {
public void run() {
ensureActiveTabIsVisible(false);
}
};
SwingUtilities.invokeLater(runnable);
}
}
public class TabFocusListener implements FocusListener {
public void focusGained(FocusEvent e) {
repaintSelectedTab();
}
public void focusLost(FocusEvent e) {
repaintSelectedTab();
}
private void repaintSelectedTab() {
if (_tabPane.getTabCount() > 0) {
Rectangle rect = getTabBounds(_tabPane, _tabPane.getSelectedIndex());
if (rect != null) {
_tabPane.repaint(rect);
}
}
}
}
public class MouseMotionHandler extends MouseMotionAdapter {
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class MouseHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isMiddleMouseButton(e)) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
Action action = getActionMap().get("closeTabAction");
if (action != null && tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex) && _tabPane.isCloseTabOnMouseMiddleButton() && _tabPane.isTabClosableAt(tabIndex)) {
ActionEvent event = new ActionEvent(_tabPane, tabIndex, "middleMouseButtonClicked");
action.actionPerformed(event);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isLeftMouseButton(e) || _tabPane.isRightClickSelect()) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
_tabPane.processMouseSelection(tabIndex, e);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else if (_tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
});
}
else {
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else {
// first try to find a default component.
boolean foundInTab = JideSwingUtilities.compositeRequestFocus(comp);
if (!foundInTab) { // && !_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
if (!isTabEditing())
startEditing(e); // start editing tab
}
}
public class MouseWheelHandler implements MouseWheelListener {
public void mouseWheelMoved(MouseWheelEvent e) {
if (_tabPane.isScrollSelectedTabOnWheel()) {
// set selected tab to the currently selected tab plus the wheel rotation but between
// 0 and tabCount-1
_tabPane.setSelectedIndex(
Math.min(_tabPane.getTabCount() - 1, Math.max(0, _tabPane.getSelectedIndex() + e.getWheelRotation())));
}
else if (scrollableTabLayoutEnabled() && e.getWheelRotation() != 0) {
if (e.getWheelRotation() > 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollForward(_tabPane.getTabPlacement());
}
}
else if (e.getWheelRotation() < 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollBackward(_tabPane.getTabPlacement());
}
}
}
}
}
private class ComponentHandler implements ComponentListener {
public void componentResized(ComponentEvent e) {
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
/* GES 2/3/99:
The container listener code was added to support HTML
rendering of tab titles.
Ideally, we would be able to listen for property changes
when a tab is added or its text modified. At the moment
there are no such events because the Beans spec doesn't
allow 'indexed' property changes (i.e. tab 2's text changed
from A to B).
In order to get around this, we listen for tabs to be added
or removed by listening for the container events. we then
queue up a runnable (so the component has a chance to complete
the add) which checks the tab title of the new component to see
if it requires HTML rendering.
The Views (one per tab title requiring HTML rendering) are
stored in the htmlViews Vector, which is only allocated after
the first time we run into an HTML tab. Note that this vector
is kept in step with the number of pages, and nulls are added
for those pages whose tab title do not require HTML rendering.
This makes it easy for the paint and layout code to tell
whether to invoke the HTML engine without having to check
the string during time-sensitive operations.
When we have added a way to listen for tab additions and
changes to tab text, this code should be removed and
replaced by something which uses that. */
private class ContainerHandler implements ContainerListener {
public void componentAdded(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
int index = tp.indexOfComponent(child);
String title = getCurrentDisplayTitleAt(tp, index);
boolean isHTML = BasicHTML.isHTMLString(title);
if (isHTML) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(tp, title);
htmlViews.insertElementAt(v, index);
}
}
else { // Not HTML
if (htmlViews != null) { // Add placeholder
htmlViews.insertElementAt(null, index);
} // else nada!
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
}
public void componentRemoved(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
// NOTE 4/15/2002 (joutwate):
// This fix is implemented using client properties since there is
// currently no IndexPropertyChangeEvent. Once
// IndexPropertyChangeEvents have been added this code should be
// modified to use it.
Integer index =
(Integer) tp.getClientProperty("__index_to_remove__");
if (index != null) {
if (htmlViews != null && htmlViews.size() > index) {
htmlViews.removeElementAt(index);
}
tp.putClientProperty("__index_to_remove__", null);
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
// ensureActiveTabIsVisible(true);
}
}
private Vector createHTMLVector() {
Vector htmlViews = new Vector();
int count = _tabPane.getTabCount();
if (count > 0) {
for (int i = 0; i < count; i++) {
String title = getCurrentDisplayTitleAt(_tabPane, i);
if (BasicHTML.isHTMLString(title)) {
htmlViews.addElement(BasicHTML.createHTMLView(_tabPane, title));
}
else {
htmlViews.addElement(null);
}
}
}
return htmlViews;
}
@Override
public Component getTabPanel() {
if (scrollableTabLayoutEnabled())
return _tabScroller.tabPanel;
else
return _tabPane;
}
static class AbstractTab {
int width;
int id;
public void copy(AbstractTab tab) {
this.width = tab.width;
this.id = tab.id;
}
}
public static class TabSpaceAllocator {
static final int startOffset = 4;
private Insets insets = null;
static final int tabWidth = 24;
static final int textIconGap = 8;
private AbstractTab tabs[];
private void setInsets(Insets insets) {
this.insets = (Insets) insets.clone();
}
private void init(Rectangle rects[], Insets insets) {
setInsets(insets);
tabs = new AbstractTab[rects.length];
// fill up internal datastructure
for (int i = 0; i < rects.length; i++) {
tabs[i] = new AbstractTab();
tabs[i].id = i;
tabs[i].width = rects[i].width;
}
tabSort();
}
private void bestfit(AbstractTab tabs[], int freeWidth, int startTab) {
int tabCount = tabs.length;
int worstWidth;
int currentTabWidth;
int initialPos;
currentTabWidth = tabs[startTab].width;
initialPos = startTab;
if (startTab == tabCount - 1) {
// directly fill as worst case
tabs[startTab].width = freeWidth;
return;
}
worstWidth = freeWidth / (tabCount - startTab);
while (currentTabWidth < worstWidth) {
freeWidth -= currentTabWidth;
if (++startTab < tabCount - 1) {
currentTabWidth = tabs[startTab].width;
}
else {
tabs[startTab].width = worstWidth;
return;
}
}
if (startTab == initialPos) {
// didn't find anything smaller
for (int i = startTab; i < tabCount; i++) {
tabs[i].width = worstWidth;
}
}
else if (startTab < tabCount - 1) {
bestfit(tabs, freeWidth, startTab);
}
}
// bubble sort for now
private void tabSort() {
int tabCount = tabs.length;
AbstractTab tempTab = new AbstractTab();
for (int i = 0; i < tabCount - 1; i++) {
for (int j = i + 1; j < tabCount; j++) {
if (tabs[i].width > tabs[j].width) {
tempTab.copy(tabs[j]);
tabs[j].copy(tabs[i]);
tabs[i].copy(tempTab);
}
}
}
}
// directly modify the rects
private void outpush(Rectangle rects[]) {
for (AbstractTab tab : tabs) {
rects[tab.id].width = tab.width;
}
rects[0].x = startOffset;
for (int i = 1; i < rects.length; i++) {
rects[i].x = rects[i - 1].x + rects[i - 1].width;
}
}
public void reArrange(Rectangle rects[], Insets insets, int totalAvailableSpace) {
init(rects, insets);
bestfit(tabs, totalAvailableSpace, 0);
outpush(rects);
clearup();
}
private void clearup() {
for (int i = 0; i < tabs.length; i++) {
tabs[i] = null;
}
tabs = null;
}
}
@Override
public void ensureActiveTabIsVisible(boolean scrollLeft) {
if (_tabPane == null || _tabPane.getWidth() == 0) {
return;
}
if (scrollableTabLayoutEnabled()) {
ensureCurrentLayout();
if (scrollLeft && _rects.length > 0) {
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
_tabScroller.tabPanel.scrollRectToVisible(_rects[0]);
}
else {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
}
int index = _tabPane.getSelectedIndex();
if ((!scrollLeft || index != 0) && index < _rects.length && index != -1) {
if (index == 0) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
else {
if (index == _rects.length - 1) { // last one, scroll to the end
Rectangle lastRect = _rects[index];
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && _tabPane.getComponentOrientation().isLeftToRight()) {
lastRect.width = _tabScroller.tabPanel.getWidth() - lastRect.x;
}
_tabScroller.tabPanel.scrollRectToVisible(lastRect);
}
else {
_tabScroller.tabPanel.scrollRectToVisible(_rects[index]);
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.tabPanel.getParent().doLayout();
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabPane.revalidate();
_tabPane.repaintTabAreaAndContentBorder();
}
else {
_tabPane.repaint();
}
}
}
protected boolean isShowCloseButtonOnTab() {
if (_tabPane.isUseDefaultShowCloseButtonOnTab()) {
return _showCloseButtonOnTab;
}
else return _tabPane.isShowCloseButtonOnTab();
}
protected boolean isShowCloseButton() {
return _tabPane.isShowCloseButton();
}
public void ensureCloseButtonCreated() {
if (isShowCloseButton() && isShowCloseButtonOnTab() && scrollableTabLayoutEnabled()) {
if (_closeButtons == null) {
_closeButtons = new TabCloseButton[_tabPane.getTabCount()];
}
else if (_closeButtons.length > _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0, temp.length);
for (int i = temp.length; i < _closeButtons.length; i++) {
TabCloseButton tabCloseButton = _closeButtons[i];
_tabScroller.tabPanel.remove(tabCloseButton);
}
_closeButtons = temp;
}
else if (_closeButtons.length < _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0,
_closeButtons.length);
_closeButtons = temp;
}
ActionMap am = getActionMap();
for (int i = 0; i < _closeButtons.length; i++) {
TabCloseButton closeButton = _closeButtons[i];
if (closeButton == null) {
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName("JideTabbedPane.close");
_closeButtons[i] = closeButton;
closeButton.setBounds(0, 0, 0, 0);
Action action = _tabPane.getCloseAction();
closeButton.setAction(am.get("closeTabAction"));
updateButtonFromAction(closeButton, action);
_tabScroller.tabPanel.add(closeButton);
}
closeButton.setIndex(i);
}
}
}
private void updateButtonFromAction(TabCloseButton closeButton, Action action) {
if (action == null) {
return;
}
closeButton.setEnabled(action.isEnabled());
Object desc = action.getValue(Action.SHORT_DESCRIPTION);
if (desc instanceof String) {
closeButton.setToolTipText((String) desc);
}
Object icon = action.getValue(Action.SMALL_ICON);
if (icon instanceof Icon) {
closeButton.setIcon((Icon) icon);
}
}
protected boolean isShowTabButtons() {
return _tabPane.getTabCount() != 0 && _tabPane.isShowTabArea() && _tabPane.isShowTabButtons();
}
protected boolean isShrinkTabs() {
return _tabPane.getTabCount() != 0 && _tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT;
}
protected TabEditor _tabEditor;
protected boolean _isEditing;
protected int _editingTab = -1;
protected String _oldValue;
protected String _oldPrefix;
protected String _oldPostfix;
// mtf - changed
protected Component _originalFocusComponent;
@Override
public boolean isTabEditing() {
return _isEditing;
}
protected TabEditor createDefaultTabEditor() {
final TabEditor editor = new TabEditor();
editor.getDocument().addDocumentListener(this);
editor.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
return true;
}
public boolean shouldYieldFocus(JComponent input) {
boolean shouldStopEditing = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
shouldStopEditing = _tabPane.getTabEditingValidator().alertIfInvalid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (shouldStopEditing && _tabPane != null && _tabPane.isTabEditing()) {
_tabPane.stopTabEditing();
}
return shouldStopEditing;
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_originalFocusComponent = e.getOppositeComponent();
}
@Override
public void focusLost(FocusEvent e) {
}
});
editor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editor.transferFocus();
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (_isEditing && (e.getKeyCode() == KeyEvent.VK_ESCAPE)) {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldValue);
}
_tabPane.cancelTabEditing();
}
}
});
editor.setFont(_tabPane.getFont());
return editor;
}
@Override
public void stopTabEditing() {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
cancelTabEditing();
}
@Override
public void cancelTabEditing() {
if (_tabEditor != null) {
_isEditing = false;
((Container) getTabPanel()).remove(_tabEditor);
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
Rectangle tabRect = _tabPane.getBoundsAt(_editingTab);
getTabPanel().repaint(tabRect.x, tabRect.y,
tabRect.width, tabRect.height);
}
else {
getTabPanel().repaint();
}
if (_originalFocusComponent != null)
_originalFocusComponent.requestFocus(); // InWindow();
else
_tabPane.requestFocusForVisibleComponent();
_editingTab = -1;
_oldValue = null;
_tabPane.doLayout();
}
}
@Override
public boolean editTabAt(int tabIndex) {
if (_isEditing) {
return false;
}
// _tabPane.popupSelectedIndex(tabIndex);
if (_tabEditor == null)
_tabEditor = createDefaultTabEditor();
if (_tabEditor != null) {
prepareEditor(_tabEditor, tabIndex);
((Container) getTabPanel()).add(_tabEditor);
resizeEditor(tabIndex);
_editingTab = tabIndex;
_isEditing = true;
_tabEditor.requestFocusInWindow();
_tabEditor.selectAll();
return true;
}
return false;
}
@Override
public int getEditingTabIndex() {
return _editingTab;
}
protected void prepareEditor(TabEditor e, int tabIndex) {
Font font;
if (_tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (_tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
e.setFont(font);
_oldValue = _tabPane.getTitleAt(tabIndex);
if (_oldValue.startsWith("<HTML>") && _oldValue.endsWith("/HTML>")) {
_oldPrefix = "<HTML>";
_oldPostfix = "</HTML>";
String title = _oldValue.substring("<HTML>".length(), _oldValue.length() - "</HTML>".length());
if (title.startsWith("<B>") && title.endsWith("/B>")) {
title = title.substring("<B>".length(), title.length() - "</B>".length());
_oldPrefix += "<B>";
_oldPostfix = "</B>" + _oldPostfix;
}
e.setText(title);
}
else {
_oldPrefix = "";
_oldPostfix = "";
e.setText(_oldValue);
}
e.selectAll();
e.setForeground(_tabPane.getForegroundAt(tabIndex));
}
protected Rectangle getTabsTextBoundsAt(int tabIndex) {
Rectangle tabRect = _tabPane.getBoundsAt(tabIndex);
Rectangle iconRect = new Rectangle(),
textRect = new Rectangle();
if (tabRect.width < 200) // random max size;
tabRect.width = 200;
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
while (title == null || title.length() < 3)
title += " ";
Icon icon = _tabPane.getIconForTab(tabIndex);
Font font = _tabPane.getFont();
if (tabIndex == _tabPane.getSelectedIndex() && _tabPane.isBoldActiveTab()) {
font = font.deriveFont(Font.BOLD);
}
SwingUtilities.layoutCompoundLabel(_tabPane, _tabPane.getGraphics().getFontMetrics(font), title, icon,
SwingUtilities.CENTER, SwingUtilities.CENTER,
SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect,
iconRect, textRect, icon == null ? 0 : _textIconGap);
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
iconRect.x = tabRect.x + _iconMargin;
textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding);
textRect.width += 2;
}
else {
iconRect.y = tabRect.y + _iconMargin;
textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding);
iconRect.x = tabRect.x + 2;
textRect.x = tabRect.x + 2;
textRect.height += 2;
}
return textRect;
}
private void updateTab() {
if (_isEditing) {
resizeEditor(getEditingTabIndex());
}
}
public void insertUpdate(DocumentEvent e) {
updateTab();
}
public void removeUpdate(DocumentEvent e) {
updateTab();
}
public void changedUpdate(DocumentEvent e) {
updateTab();
}
protected void resizeEditor(int tabIndex) {
// note - this should use the logic of label paint text so that the text overlays exactly.
Rectangle tabsTextBoundsAt = getTabsTextBoundsAt(tabIndex);
if (tabsTextBoundsAt.isEmpty()) {
tabsTextBoundsAt = new Rectangle(14, 3); // note - 14 should be the font height but...
}
tabsTextBoundsAt.x = tabsTextBoundsAt.x - _tabEditor.getBorder().getBorderInsets(_tabEditor).left;
tabsTextBoundsAt.width = +tabsTextBoundsAt.width +
_tabEditor.getBorder().getBorderInsets(_tabEditor).left +
_tabEditor.getBorder().getBorderInsets(_tabEditor).right;
tabsTextBoundsAt.y = tabsTextBoundsAt.y - _tabEditor.getBorder().getBorderInsets(_tabEditor).top;
tabsTextBoundsAt.height = tabsTextBoundsAt.height +
_tabEditor.getBorder().getBorderInsets(_tabEditor).top +
_tabEditor.getBorder().getBorderInsets(_tabEditor).bottom;
_tabEditor.setBounds(SwingUtilities.convertRectangle(_tabPane, tabsTextBoundsAt, getTabPanel()));
_tabEditor.invalidate();
_tabEditor.validate();
// getTabPanel().invalidate();
// getTabPanel().validate();
// getTabPanel().repaint();
// getTabPanel().doLayout();
_tabPane.doLayout();
// mtf - note - this is an exteme repaint but we need to paint any content borders
getTabPanel().getParent().getParent().repaint();
}
protected String getCurrentDisplayTitleAt(JideTabbedPane tp, int index) {
String returnTitle = tp.getDisplayTitleAt(index);
if ((_isEditing) && (index == _editingTab))
returnTitle = _tabEditor.getText();
return returnTitle;
}
protected class TabEditor extends JTextField implements UIResource {
TabEditor() {
setOpaque(false);
// setBorder(BorderFactory.createEmptyBorder());
setBorder(BorderFactory
.createCompoundBorder(new PartialLineBorder(Color.BLACK, 1, true),
BorderFactory.createEmptyBorder(0, 2, 0, 2)));
}
public boolean stopEditing() {
return true;
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Composite orgComposite = g2.getComposite();
Color orgColor = g2.getColor();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.70f));
Object o = JideSwingUtilities.setupShapeAntialiasing(g);
g2.setColor(getBackground());
g.fillRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 1, 1);
JideSwingUtilities.restoreShapeAntialiasing(g, o);
g2.setColor(orgColor);
g2.setComposite(orgComposite);
super.paintComponent(g);
}
}
public void startEditing(MouseEvent e) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (!e.isPopupTrigger() && tabIndex >= 0
&& _tabPane.isEnabledAt(tabIndex)
&& _tabPane.isTabEditingAllowed() && (e.getClickCount() == 2)) {
boolean shouldEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldEdit = _tabPane.getTabEditingValidator().shouldStartEdit(tabIndex, e);
if (shouldEdit) {
e.consume();
_tabPane.editTabAt(tabIndex);
}
}
if (e.getClickCount() == 1) {
if (_tabPane.isTabEditing()) {
boolean shouldStopEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldStopEdit = _tabPane.getTabEditingValidator().alertIfInvalid(tabIndex, _oldPrefix + _tabEditor.getText() + _oldPostfix);
if (shouldStopEdit)
_tabPane.stopTabEditing();
}
}
}
public ThemePainter getPainter() {
return _painter;
}
private class DragOverTimer extends Timer implements ActionListener {
private int _index;
private static final long serialVersionUID = -2529347876574638854L;
public DragOverTimer(int index) {
super(500, null);
_index = index;
addActionListener(this);
setRepeats(false);
}
public void actionPerformed(ActionEvent e) {
if (_tabPane.getTabCount() == 0) {
return;
}
if (_index == _tabPane.getSelectedIndex()) {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
_tabPane.repaint(getTabBounds(_tabPane, _index));
}
}
else {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
}
_tabPane.setSelectedIndex(_index);
}
stop();
}
}
private class DropListener implements DropTargetListener {
private DragOverTimer _timer;
int _index = -1;
public DropListener() {
}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
if (!_tabPane.isEnabled()) {
return;
}
int tabIndex = getTabAtLocation(dtde.getLocation().x, dtde.getLocation().y);
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex()) {
// selected already, do nothing
}
else if (tabIndex == _index) {
// same tab, timer has started
}
else {
stopTimer();
startTimer(tabIndex);
_index = tabIndex; // save the index
}
}
else {
stopTimer();
}
dtde.rejectDrag();
}
private void startTimer(int tabIndex) {
_timer = new DragOverTimer(tabIndex);
_timer.start();
}
private void stopTimer() {
if (_timer != null) {
_timer.stop();
_timer = null;
_index = -1;
}
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dte) {
stopTimer();
}
public void drop(DropTargetDropEvent dtde) {
stopTimer();
}
}
protected void paintFocusIndicator(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect,
boolean isSelected) {
Rectangle tabRect = new Rectangle(rects[tabIndex]);
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
tabRect.x += _tabScroller.viewport.getExpectedViewX();
}
if (_tabPane.hasFocus() && isSelected) {
int x, y, w, h;
g.setColor(_focus);
switch (tabPlacement) {
case LEFT:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case RIGHT:
x = tabRect.x + 2;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case BOTTOM:
x = tabRect.x + 3;
y = tabRect.y + 2;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
break;
case TOP:
default:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
}
BasicGraphicsUtils.drawDashedRect(g, x, y, w, h);
}
}
protected boolean isRoundedCorner() {
return "true".equals(SecurityUtils.getProperty("shadingtheme", "false"));
}
protected int getTabShape() {
return _tabPane.getTabShape();
}
protected int getTabResizeMode() {
return _tabPane.getTabResizeMode();
}
protected int getColorTheme() {
return _tabPane.getColorTheme();
}
// for debug purpose
final protected boolean PAINT_TAB = true;
final protected boolean PAINT_TAB_BORDER = true;
final protected boolean PAINT_TAB_BACKGROUND = true;
final protected boolean PAINT_TABAREA = true;
final protected boolean PAINT_CONTENT_BORDER = true;
final protected boolean PAINT_CONTENT_BORDER_EDGE = true;
protected int getLeftMargin() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return OFFICE2003_LEFT_MARGIN;
}
else if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else {
return DEFAULT_LEFT_MARGIN;
}
}
protected int getTabGap() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return 4;
}
else {
return 0;
}
}
protected int getLayoutSize() {
int tabShape = getTabShape();
if (tabShape == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else if (tabShape == JideTabbedPane.SHAPE_ECLIPSE3X) {
return 15;
}
else if (_tabPane.getTabShape() == JideTabbedPane.SHAPE_FLAT || _tabPane.getTabShape() == JideTabbedPane.SHAPE_ROUNDED_FLAT) {
return 2;
}
else if (tabShape == JideTabbedPane.SHAPE_WINDOWS
|| tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return 6;
}
else {
return 0;
}
}
protected int getTabRightPadding() {
if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return 4;
}
else {
return 0;
}
}
protected MouseListener createMouseListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseHandler();
}
else {
return new MouseHandler();
}
}
protected MouseWheelListener createMouseWheelListener() {
return new MouseWheelHandler();
}
protected MouseMotionListener createMouseMotionListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseMotionHandler();
}
else {
return new MouseMotionHandler();
}
}
public class DefaultMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class DefaultMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
}
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
public class RolloverMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class RolloverMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
protected boolean isTabLeadingComponentVisible() {
return _tabPane.isTabShown() && _tabLeadingComponent != null && _tabLeadingComponent.isVisible();
}
protected boolean isTabTrailingComponentVisible() {
return _tabPane.isTabShown() && _tabTrailingComponent != null && _tabTrailingComponent.isVisible();
}
protected boolean isTabTopVisible(int tabPlacement) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement));
case TOP:
case BOTTOM:
default:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement));
}
}
protected boolean showFocusIndicator() {
return _tabPane.hasFocusComponent() && _showFocusIndicator;
}
private int getNumberOfTabButtons() {
int numberOfButtons = (!isShowTabButtons() || isShrinkTabs()) ? 1 : 4;
if (!isShowCloseButton() || isShowCloseButtonOnTab()) {
numberOfButtons--;
}
return numberOfButtons;
}
/**
* Gets the resource string used in DocumentPane. Subclass can override it to provide their own strings.
*
* @param key the resource key
* @return the localized string.
*/
protected String getResourceString(String key) {
return Resource.getResourceBundle(_tabPane != null ? _tabPane.getLocale() : Locale.getDefault()).getString(key);
}
}
| true | true | protected boolean requestFocusForVisibleComponent() {
Component visibleComponent = getVisibleComponent();
Component lastFocused = _tabPane.getLastFocusedComponent(visibleComponent);
if (lastFocused != null && lastFocused.requestFocusInWindow()) {
return true;
}
else if (visibleComponent != null && JideSwingUtilities.passesFocusabilityTest(visibleComponent)) { // visibleComponent.isFocusTraversable()) {
JideSwingUtilities.compositeRequestFocus(visibleComponent);
return true;
}
else if (visibleComponent instanceof JComponent) {
if (((JComponent) visibleComponent).requestDefaultFocus()) {
return true;
}
}
return false;
}
private static class RightAction extends AbstractAction {
private static final long serialVersionUID = -1759791760116532857L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(EAST);
}
}
private static class LeftAction extends AbstractAction {
private static final long serialVersionUID = 8670680299012169408L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(WEST);
}
}
private static class UpAction extends AbstractAction {
private static final long serialVersionUID = -6961702501242792445L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NORTH);
}
}
private static class DownAction extends AbstractAction {
private static final long serialVersionUID = -453174268282628886L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(SOUTH);
}
}
private static class NextAction extends AbstractAction {
private static final long serialVersionUID = -154035573464933924L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NEXT);
}
}
private static class PreviousAction extends AbstractAction {
private static final long serialVersionUID = 2095403667386334865L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(PREVIOUS);
}
}
private static class PageUpAction extends AbstractAction {
private static final long serialVersionUID = 1154273528778779166L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(WEST);
}
else {
ui.navigateSelectedTab(NORTH);
}
}
}
private static class PageDownAction extends AbstractAction {
private static final long serialVersionUID = 4895454480954468453L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(EAST);
}
else {
ui.navigateSelectedTab(SOUTH);
}
}
}
private static class RequestFocusAction extends AbstractAction {
private static final long serialVersionUID = 3791111435639724577L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (!pane.requestFocusInWindow()) {
pane.requestFocus();
}
}
}
private static class RequestFocusForVisibleAction extends AbstractAction {
private static final long serialVersionUID = 6677797853998039155L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.requestFocusForVisibleComponent();
}
}
/**
* Selects a tab in the JTabbedPane based on the String of the action command. The tab selected is based on the
* first tab that has a mnemonic matching the first character of the action command.
*/
private static class SetSelectedIndexAction extends AbstractAction {
private static final long serialVersionUID = 6216635910156115469L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (pane != null && (pane.getUI() instanceof BasicJideTabbedPaneUI)) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
String command = e.getActionCommand();
if (command != null && command.length() > 0) {
int mnemonic = (int) e.getActionCommand().charAt(0);
if (mnemonic >= 'a' && mnemonic <= 'z') {
mnemonic -= ('a' - 'A');
}
Integer index = (Integer) ui._mnemonicToIndexMap
.get(new Integer(mnemonic));
if (index != null && pane.isEnabledAt(index)) {
pane.setSelectedIndex(index);
}
}
}
}
}
protected TabCloseButton createNoFocusButton(int type) {
return new TabCloseButton(type);
}
private static class ScrollTabsForwardAction extends AbstractAction {
private static final long serialVersionUID = 8772616556895545931L;
public ScrollTabsForwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollForward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollForward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsBackwardAction extends AbstractAction {
private static final long serialVersionUID = -426408621939940046L;
public ScrollTabsBackwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollBackward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollBackward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsListAction extends AbstractAction {
private static final long serialVersionUID = 246103712600916771L;
public ScrollTabsListAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.showList"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
if (ui._tabScroller._popup != null && ui._tabScroller._popup.isPopupVisible()) {
ui._tabScroller._popup.hidePopupImmediately();
ui._tabScroller._popup = null;
}
else {
ui._tabScroller.createPopup(pane.getTabPlacement());
}
}
}
}
}
protected void stopOrCancelEditing() {
boolean isEditValid = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
isEditValid = _tabPane.getTabEditingValidator().isValid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (isEditValid)
_tabPane.stopTabEditing();
else
_tabPane.cancelTabEditing();
}
private static class CloseTabAction extends AbstractAction {
private static final long serialVersionUID = 7779678389793199733L;
public CloseTabAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.close"));
}
public void actionPerformed(ActionEvent e) {
JideTabbedPane pane;
Object src = e.getSource();
int index;
boolean closeSelected = false;
if (src instanceof JideTabbedPane) {
pane = (JideTabbedPane) src;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof JideTabbedPane) {
pane = (JideTabbedPane) ((TabCloseButton) src).getParent();
closeSelected = true;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof ScrollableTabPanel) {
pane = (JideTabbedPane) SwingUtilities.getAncestorOfClass(JideTabbedPane.class, (TabCloseButton) src);
closeSelected = false;
}
else {
return; // shouldn't happen
}
if (pane.isTabEditing()) {
((BasicJideTabbedPaneUI) pane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
}
ActionEvent e2 = e;
if (src instanceof TabCloseButton) {
index = ((TabCloseButton) src).getIndex();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
else if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
if (pane.getCloseAction() != null) {
pane.getCloseAction().actionPerformed(e2);
}
else {
if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
if (index >= 0)
pane.removeTabAt(index);
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else if (closeSelected) {
if (pane.getSelectedIndex() >= 0)
pane.removeTabAt(pane.getSelectedIndex());
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else {
int i = ((TabCloseButton) src).getIndex();
if (i != -1) {
int tabIndex = pane.getSelectedIndex();
pane.removeTabAt(i);
if (i < tabIndex) {
pane.setSelectedIndex(tabIndex - 1);
}
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
}
}
}
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabbedPaneLayout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
return calculateSize(false);
}
public Dimension minimumLayoutSize(Container parent) {
return calculateSize(true);
}
protected Dimension calculateSize(boolean minimum) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
Insets contentInsets = getContentBorderInsets(tabPlacement);
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
Dimension zeroSize = new Dimension(0, 0);
int height = contentInsets.top + contentInsets.bottom;
int width = contentInsets.left + contentInsets.right;
int cWidth = 0;
int cHeight = 0;
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
// Determine minimum size required to display largest
// child in each dimension
//
if (_tabPane.isShowTabContent()) {
for (int i = 0; i < _tabPane.getTabCount(); i++) {
Component component = _tabPane.getComponentAt(i);
if (component != null) {
Dimension size = zeroSize;
size = minimum ? component.getMinimumSize() :
component.getPreferredSize();
if (size != null) {
cHeight = Math.max(size.height, cHeight);
cWidth = Math.max(size.width, cWidth);
}
}
}
// Add content border insets to minimum size
width += cWidth;
height += cHeight;
}
int tabExtent;
// Calculate how much space the tabs will need, based on the
// minimum size required to display largest child + content border
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
height = Math.max(height, (minimum ? 0 : calculateMaxTabHeight(tabPlacement)) + tabAreaInsets.top + tabAreaInsets.bottom);
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.width, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.width, tabExtent);
}
width += tabExtent;
break;
case TOP:
case BOTTOM:
default:
if (_tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {
width = Math.max(width, (_tabPane.getTabCount() << 2) +
tabAreaInsets.left + tabAreaInsets.right);
}
else {
width = Math.max(width, (minimum ? 0 : calculateMaxTabWidth(tabPlacement)) +
tabAreaInsets.left + tabAreaInsets.right);
}
if (_tabPane.isTabShown()) {
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.height, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.height, tabExtent);
}
height += tabExtent;
}
}
}
return new Dimension(width + insets.left + insets.right,
height + insets.bottom + insets.top);
}
protected int preferredTabAreaHeight(int tabPlacement, int width) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int rows = 1;
int x = 0;
int maxTabHeight = calculateMaxTabHeight(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabWidth = calculateTabWidth(tabPlacement, i, metrics);
if (x != 0 && x + tabWidth > width) {
rows++;
x = 0;
}
x += tabWidth;
}
total = calculateTabAreaHeight(tabPlacement, rows, maxTabHeight);
}
return total;
}
protected int preferredTabAreaWidth(int tabPlacement, int height) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int columns = 1;
int y = 0;
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabHeight = calculateTabHeight(tabPlacement, i, metrics);
if (y != 0 && y + tabHeight > height) {
columns++;
y = 0;
}
y += tabHeight;
}
total = calculateTabAreaWidth(tabPlacement, columns, _maxTabWidth);
}
return total;
}
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
int cx, cy, cw, ch;
int totalTabWidth = 0;
int totalTabHeight = 0;
Insets contentInsets = getContentBorderInsets(tabPlacement);
Component selectedComponent = _tabPane.getComponentAt(selectedIndex);
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + totalTabWidth + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case RIGHT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case BOTTOM:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case TOP:
default:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + totalTabHeight + contentInsets.top;
}
cw = bounds.width - totalTabWidth -
insets.left - insets.right -
contentInsets.left - contentInsets.right;
ch = bounds.height - totalTabHeight -
insets.top - insets.bottom -
contentInsets.top - contentInsets.bottom;
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
child.setBounds(cx, cy, cw, ch);
}
}
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
public void calculateLayoutInfo() {
int tabCount = _tabPane.getTabCount();
assureRectsCreated(tabCount);
calculateTabRects(_tabPane.getTabPlacement(), tabCount);
}
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int selectedIndex = _tabPane.getSelectedIndex();
int tabRunOverlay;
int i, j;
int x, y;
int returnAt;
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
//
// Calculate bounds within which a tab run must fit
//
switch (tabPlacement) {
case LEFT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = size.width - insets.right - tabAreaInsets.right - _maxTabWidth;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case BOTTOM:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = size.height - insets.bottom - tabAreaInsets.bottom - _maxTabHeight;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
}
tabRunOverlay = getTabRunOverlay(tabPlacement);
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
// Run through tabs and partition them into runs
Rectangle rect;
for (i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabWidth = 0;
rect.x = x;
}
rect.width = calculateTabWidth(tabPlacement, i, metrics);
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
// Never move a TAB down a run if it is in the first column.
// Even if there isn't enough room, moving it to a fresh
// line won't help.
if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.x = x;
}
// Initialize y position in case there's just one run
rect.y = y;
rect.height = _maxTabHeight/* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabHeight = 0;
rect.y = y;
}
rect.height = calculateTabHeight(tabPlacement, i, metrics);
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
// Never move a TAB over a run if it is in the first run.
// Even if there isn't enough room, moving it to a fresh
// column won't help.
if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.y = y;
}
// Initialize x position in case there's just one column
rect.x = x;
rect.width = _maxTabWidth/* - 2 */;
}
if (i == selectedIndex) {
_selectedRun = _runCount - 1;
}
}
if (_runCount > 1) {
// Re-distribute tabs in case last run has leftover space
normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns ? y : x, returnAt);
_selectedRun = getRunForTab(tabCount, selectedIndex);
// Rotate run array so that selected run is first
if (shouldRotateTabRuns(tabPlacement)) {
rotateTabRuns(tabPlacement, _selectedRun);
}
}
// Step through runs from back to front to calculate
// tab y locations and to pad runs appropriately
for (i = _runCount - 1; i >= 0; i--) {
int start = _tabRuns[i];
int next = _tabRuns[i == (_runCount - 1) ? 0 : i + 1];
int end = (next != 0 ? next - 1 : tabCount - 1);
if (!verticalTabRuns) {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.y = y;
rect.x += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == BOTTOM) {
y -= (_maxTabHeight - tabRunOverlay);
}
else {
y += (_maxTabHeight - tabRunOverlay);
}
}
else {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.x = x;
rect.y += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == RIGHT) {
x -= (_maxTabWidth - tabRunOverlay);
}
else {
x += (_maxTabWidth - tabRunOverlay);
}
}
}
// Pad the selected tab so that it appears raised in front
padSelectedTab(tabPlacement, selectedIndex);
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right);
for (i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width;
}
}
}
/*
* Rotates the run-index array so that the selected run is run[0]
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void rotateTabRuns(int tabPlacement, int selectedRun) {
for (int i = 0; i < selectedRun; i++) {
int save = _tabRuns[0];
for (int j = 1; j < _runCount; j++) {
_tabRuns[j - 1] = _tabRuns[j];
}
_tabRuns[_runCount - 1] = save;
}
}
protected void normalizeTabRuns(int tabPlacement, int tabCount,
int start, int max) {
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
int run = _runCount - 1;
boolean keepAdjusting = true;
double weight = 1.25;
// At this point the tab runs are packed to fit as many
// tabs as possible, which can leave the last run with a lot
// of extra space (resulting in very fat tabs on the last run).
// So we'll attempt to distribute this extra space more evenly
// across the runs in order to make the runs look more consistent.
//
// Starting with the last run, determine whether the last tab in
// the previous run would fit (generously) in this run; if so,
// move tab to current run and shift tabs accordingly. Cycle
// through remaining runs using the same algorithm.
//
while (keepAdjusting) {
int last = lastTabInRun(tabCount, run);
int prevLast = lastTabInRun(tabCount, run - 1);
int end;
int prevLastLen;
if (!verticalTabRuns) {
end = _rects[last].x + _rects[last].width;
prevLastLen = (int) (_maxTabWidth * weight);
}
else {
end = _rects[last].y + _rects[last].height;
prevLastLen = (int) (_maxTabHeight * weight * 2);
}
// Check if the run has enough extra space to fit the last tab
// from the previous row...
if (max - end > prevLastLen) {
// Insert tab from previous row and shift rest over
_tabRuns[run] = prevLast;
if (!verticalTabRuns) {
_rects[prevLast].x = start;
}
else {
_rects[prevLast].y = start;
}
for (int i = prevLast + 1; i <= last; i++) {
if (!verticalTabRuns) {
_rects[i].x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_rects[i].y = _rects[i - 1].y + _rects[i - 1].height;
}
}
}
else if (run == _runCount - 1) {
// no more room left in last run, so we're done!
keepAdjusting = false;
}
if (run - 1 > 0) {
// check previous run next...
run -= 1;
}
else {
// check last run again...but require a higher ratio
// of extraspace-to-tabsize because we don't want to
// end up with too many tabs on the last run!
run = _runCount - 1;
weight += .25;
}
}
}
protected void padTabRun(int tabPlacement, int start, int end, int max) {
Rectangle lastRect = _rects[end];
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int runWidth = (lastRect.x + lastRect.width) - _rects[start].x;
int deltaWidth = max - (lastRect.x + lastRect.width);
float factor = (float) deltaWidth / (float) runWidth;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.x = _rects[j - 1].x + _rects[j - 1].width;
}
pastRect.width += Math.round((float) pastRect.width * factor);
}
lastRect.width = max - lastRect.x;
}
else {
int runHeight = (lastRect.y + lastRect.height) - _rects[start].y;
int deltaHeight = max - (lastRect.y + lastRect.height);
float factor = (float) deltaHeight / (float) runHeight;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.y = _rects[j - 1].y + _rects[j - 1].height;
}
pastRect.height += Math.round((float) pastRect.height * factor);
}
lastRect.height = max - lastRect.y;
}
}
protected void padSelectedTab(int tabPlacement, int selectedIndex) {
if (selectedIndex >= 0) {
Rectangle selRect = _rects[selectedIndex];
Insets padInsets = getSelectedTabPadInsets(tabPlacement);
selRect.x -= padInsets.left;
selRect.width += (padInsets.left + padInsets.right);
selRect.y -= padInsets.top;
selRect.height += (padInsets.top + padInsets.bottom);
}
}
}
protected TabSpaceAllocator tryTabSpacer = new TabSpaceAllocator();
protected class TabbedPaneScrollLayout extends TabbedPaneLayout {
@Override
protected int preferredTabAreaHeight(int tabPlacement, int width) {
return calculateMaxTabHeight(tabPlacement);
}
@Override
protected int preferredTabAreaWidth(int tabPlacement, int height) {
return calculateMaxTabWidth(tabPlacement);
}
@Override
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
JViewport viewport = null;
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
int tx, ty, tw, th; // tab area bounds
int cx, cy, cw, ch; // content area bounds
Insets contentInsets = getContentBorderInsets(tabPlacement);
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = insets.left;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
}
}
// calculate content area bounds
cx = tx + tw + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case RIGHT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount,
_maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = bounds.width - insets.right - tw;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
tx = bounds.width - insets.right - tw;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
tx = bounds.width - insets.right - tw;
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case BOTTOM:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = bounds.height - insets.bottom - th;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
break;
case TOP:
default:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = insets.top;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + th + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
}
// if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (tw < _rects[0].width + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
// else {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (th < _rects[0].height + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
if (child instanceof ScrollableTabViewport) {
viewport = (JViewport) child;
// Rectangle viewRect = viewport.getViewRect();
int vw = tw;
int vh = th;
int numberOfButtons = getNumberOfTabButtons();
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (totalTabHeight > th || isShowTabButtons()) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
// if (totalTabHeight - viewRect.y <= vh) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vh = totalTabHeight - viewRect.y;
// }
}
else {
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
}
if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) {
vh += getLayoutSize();
}
break;
case BOTTOM:
case TOP:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (isShowTabButtons() || !widthEnough) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Need to allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
// if (totalTabWidth - viewRect.x <= vw) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vw = totalTabWidth - viewRect.x;
// }
}
else {
// Allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
}
if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) {
vw += getLayoutSize();
if (!leftToRight) {
tx -= getLayoutSize();
}
}
break;
}
child.setBounds(tx, ty, vw, vh);
}
else if (child instanceof TabCloseButton) {
TabCloseButton scrollbutton = (TabCloseButton) child;
if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) {
Dimension bsize = scrollbutton.getPreferredSize();
int bx = 0;
int by = 0;
int bw = bsize.width;
int bh = bsize.height;
boolean visible = false;
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) {
int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
}
bx = tx + 2;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
bx = tx + 2;
}
}
if (isTabTrailingComponentVisible()) {
by = by - tsize.height;
}
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.width >= _rects[0].width) {
if (tabPlacement == LEFT) {
bx += lsize.width - _rects[0].width;
temp = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.width >= _rects[0].width
&& temp < tsize.width) {
if (tabPlacement == LEFT) {
bx += tsize.width - _rects[0].width;
}
}
}
break;
case TOP:
case BOTTOM:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (_tabPane.isTabShown() && (isShowTabButtons() || !widthEnough)) {
int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON
// NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
bx = insets.left - 5;
}
}
else {
visible = false;
bx = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (1 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
}
by = ((th - bsize.height) >> 1) + ty;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
visible = false;
bx = 0;
}
by = ((th - bsize.height) >> 1) + ty;
}
}
if (isTabTrailingComponentVisible()) {
bx -= tsize.width;
}
temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.height >= _rects[0].height) {
if (tabPlacement == TOP) {
by = ty + 2 + lsize.height - _rects[0].height;
temp = lsize.height;
}
else {
by = ty + 2;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.height >= _rects[0].height
&& temp < tsize.height) {
if (tabPlacement == TOP) {
by = ty + 2 + tsize.height - _rects[0].height;
}
else {
by = ty + 2;
}
}
}
}
child.setVisible(visible);
if (visible) {
child.setBounds(bx, by, bw, bh);
}
}
else {
scrollbutton.setBounds(0, 0, 0, 0);
}
}
else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) {
if (_tabPane.isShowTabContent()) {
// All content children...
child.setBounds(cx, cy, cw, ch);
}
else {
child.setBounds(0, 0, 0, 0);
}
}
}
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
}
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
if (!leftToRight && !verticalTabRuns && viewport != null && !viewport.getSize().equals(_tabPane.getSize())) {
int offset = _tabPane.getWidth() - viewport.getWidth();
for (Rectangle rect : _rects) {
rect.x -= offset;
}
}
updateCloseButtons();
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
@Override
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
int x = tabAreaInsets.left;
int y = tabAreaInsets.top;
//
// Calculate bounds within which a tab run must fit
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < lsize.width) {
_maxTabWidth = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < tsize.width) {
_maxTabWidth = tsize.width;
}
}
}
break;
case BOTTOM:
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < lsize.height) {
_maxTabHeight = lsize.height;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < tsize.height) {
_maxTabHeight = tsize.height;
}
}
}
}
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
_selectedRun = 0;
_runCount = 1;
// Run through tabs and lay them out in a single run
Rectangle rect;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_maxTabWidth = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.x = x + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.x = x;
}
}
rect.width = calculateTabWidth(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
rect.y = y;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < lsize.height) {
rect.y = y + lsize.height - _maxTabHeight - 2;
temp = lsize.height;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < tsize.height
&& temp < tsize.height) {
rect.y = y + tsize.height - _maxTabHeight - 2;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
rect.height = calculateMaxTabHeight(tabPlacement);///* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_maxTabHeight = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.y = y + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.y = y;
}
}
rect.height = calculateTabHeight(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
rect.x = x;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < lsize.width) {
rect.x = x + lsize.width - _maxTabWidth - 2;
temp = lsize.width;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < tsize.width
&& temp < tsize.width) {
rect.x = x + tsize.width - _maxTabWidth - 2;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
rect.width = calculateMaxTabWidth(tabPlacement)/* - 2 */;
}
}
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right) - _tabScroller.viewport.getLocation().x;
if (isTabLeadingComponentVisible()) {
rightMargin -= lsize.width;
}
int offset = 0;
if (isTabTrailingComponentVisible()) {
offset += tsize.width;
}
for (int i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width - offset + tabAreaInsets.left;
// if(i == tabCount - 1) {
// _rects[i].width += getLeftMargin();
// _rects[i].x -= getLeftMargin();
// }
}
}
ensureCurrentRects(getLeftMargin(), tabCount);
}
}
protected void ensureCurrentRects(int leftMargin, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
int totalWidth = 0;
int totalHeight = 0;
boolean verticalTabRuns = (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT);
boolean ltr = _tabPane.getComponentOrientation().isLeftToRight();
if (tabCount == 0) {
return;
}
Rectangle r = _rects[tabCount - 1];
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (verticalTabRuns) {
totalHeight = r.y + r.height;
if (_tabLeadingComponent != null) {
totalHeight -= lsize.height;
}
}
else {
// totalWidth = r.x + r.width;
for (Rectangle rect : _rects) {
totalWidth += rect.width;
}
if (ltr) {
totalWidth += _rects[0].x;
}
else {
totalWidth += size.width - _rects[0].x - _rects[0].width - _tabScroller.viewport.getLocation().x;
}
if (_tabLeadingComponent != null) {
totalWidth -= lsize.width;
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {// LayOut Style is Size to Fix
if (verticalTabRuns) {
int availHeight;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom - leftMargin - getTabRightPadding();// give the first tab extra space
}
else {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom;
}
if (_tabPane.isShowCloseButton()) {
availHeight -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availHeight = availHeight - lsize.height;
}
if (isTabTrailingComponentVisible()) {
availHeight = availHeight - tsize.height;
}
int numberOfButtons = getNumberOfTabButtons();
availHeight -= _buttonSize * numberOfButtons;
if (totalHeight > availHeight) { // shrink is necessary
// calculate each tab width
int tabHeight = availHeight / tabCount;
totalHeight = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
_rects[k].height = tabHeight;
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
tabRect.y = totalHeight + leftMargin;// give the first tab extra space
}
else {
tabRect.y = totalHeight;
}
totalHeight += tabRect.height;
}
}
}
else {
int availWidth;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right - leftMargin - getTabRightPadding();
}
else {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right;
}
if (_tabPane.isShowCloseButton()) {
availWidth -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availWidth -= lsize.width;
}
if (isTabTrailingComponentVisible()) {
availWidth -= tsize.width;
}
int numberOfButtons = getNumberOfTabButtons();
availWidth -= _buttonSize * numberOfButtons;
if (totalWidth > availWidth) { // shrink is necessary
// calculate each tab width
int tabWidth = availWidth / tabCount;
int gripperWidth = _tabPane.isShowGripper() ? _gripperWidth
: 0;
if (tabWidth < _textIconGap + _fitStyleTextMinWidth
+ _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleIconMinWidth + gripperWidth) // cannot
// hold any text but can hold an icon
tabWidth = _fitStyleIconMinWidth + gripperWidth;
if (tabWidth < _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleFirstTabMargin + gripperWidth) // cannot
// hold any icon but gripper
tabWidth = _fitStyleFirstTabMargin + gripperWidth;
tryTabSpacer.reArrange(_rects, insets, availWidth);
}
totalWidth = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
if (ltr) {
tabRect.x = totalWidth + leftMargin;// give the first tab extra space when the style is not box style
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width + leftMargin;// give the first tab extra space when the style is not box style
}
}
else {
if (ltr) {
tabRect.x = totalWidth;
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width;
}
}
totalWidth += tabRect.width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIXED) {// LayOut Style is Fix
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
_rects[k].height = _fixedStyleRectSize;// + _rectSizeExtend * 2;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].height += _closeButtons[k].getPreferredSize().height;
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
_rects[k].width = _fixedStyleRectSize;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].width += _closeButtons[k].getPreferredSize().width;
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED) {// LayOut Style is Compressed
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab() && !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].height = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].height = icon.getIconHeight() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].height = _rects[k].height + _closeButtons[k].getPreferredSize().height + _compressedStyleCloseButtonMarginVertical;
}
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab()
&& !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].width = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].width = icon.getIconWidth() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].width = _rects[k].width + _closeButtons[k].getPreferredSize().width + _compressedStyleCloseButtonMarginHorizon;
}
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
totalWidth += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalWidth += lsize.width;
}
}
else {
totalHeight += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalHeight += tsize.height;
}
}
_tabScroller.tabPanel.setPreferredSize(new Dimension(totalWidth, totalHeight));
}
protected class ActivateTabAction extends AbstractAction {
int _tabIndex;
private static final long serialVersionUID = 3270152106579039554L;
public ActivateTabAction(String name, Icon icon, int tabIndex) {
super(name, icon);
_tabIndex = tabIndex;
}
public void actionPerformed(ActionEvent e) {
_tabPane.setSelectedIndex(_tabIndex);
}
}
protected ListCellRenderer getTabListCellRenderer() {
return _tabPane.getTabListCellRenderer();
}
public class ScrollableTabSupport implements ChangeListener {
public ScrollableTabViewport viewport;
public ScrollableTabPanel tabPanel;
public TabCloseButton scrollForwardButton;
public TabCloseButton scrollBackwardButton;
public TabCloseButton listButton;
public TabCloseButton closeButton;
public int leadingTabIndex;
private Point tabViewPosition = new Point(0, 0);
public JidePopup _popup;
@SuppressWarnings({"UnusedDeclaration"})
ScrollableTabSupport(int tabPlacement) {
viewport = new ScrollableTabViewport();
tabPanel = new ScrollableTabPanel();
viewport.setView(tabPanel);
viewport.addChangeListener(this);
scrollForwardButton = createNoFocusButton(TabCloseButton.EAST_BUTTON);
scrollForwardButton.setName(BUTTON_NAME_SCROLL_FORWARD);
scrollBackwardButton = createNoFocusButton(TabCloseButton.WEST_BUTTON);
scrollBackwardButton.setName(BUTTON_NAME_SCROLL_BACKWARD);
scrollForwardButton.setBackground(viewport.getBackground());
scrollBackwardButton.setBackground(viewport.getBackground());
listButton = createNoFocusButton(TabCloseButton.LIST_BUTTON);
listButton.setName(BUTTON_NAME_TAB_LIST);
listButton.setBackground(viewport.getBackground());
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName(BUTTON_NAME_CLOSE);
closeButton.setBackground(viewport.getBackground());
}
public void createPopupMenu(int tabPlacement) {
JPopupMenu popup = new JPopupMenu();
int totalCount = _tabPane.getTabCount();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
for (int i = 0; i < totalCount; i++) {
if (_tabPane.isEnabledAt(i)) {
JMenuItem item;
popup.add(item = new JCheckBoxMenuItem(new ActivateTabAction(_tabPane.getTitleAt(i), _tabPane.getIconForTab(i), i)));
item.setToolTipText(_tabPane.getToolTipTextAt(i));
item.setSelected(selectedIndex == i);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
}
}
Dimension preferredSize = popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
switch (tabPlacement) {
case TOP:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y + bounds.height);
break;
case BOTTOM:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y - preferredSize.height);
break;
case LEFT:
popup.show(_tabPane, bounds.x + bounds.width, bounds.y + bounds.height - preferredSize.height);
break;
case RIGHT:
popup.show(_tabPane, bounds.x - preferredSize.width, bounds.y + bounds.height - preferredSize.height);
break;
}
}
public void createPopup(int tabPlacement) {
final JList list = new JList() {
// override this method to disallow deselect by ctrl-click
@Override
public void removeSelectionInterval(int index0, int index1) {
super.removeSelectionInterval(index0, index1);
if (getSelectedIndex() == -1) {
setSelectedIndex(index0);
}
}
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension preferredScrollableViewportSize = super.getPreferredScrollableViewportSize();
if (preferredScrollableViewportSize.width < 150) {
preferredScrollableViewportSize.width = 150;
}
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredScrollableViewportSize.width >= screenWidth) {
preferredScrollableViewportSize.width = screenWidth;
}
return preferredScrollableViewportSize;
}
@Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredSize.width >= screenWidth) {
preferredSize.width = screenWidth;
}
return preferredSize;
}
};
new Sticky(list);
list.setBackground(_tabListBackground);
JScrollPane scroller = new JScrollPane(list);
scroller.setBorder(BorderFactory.createEmptyBorder());
scroller.getViewport().setOpaque(false);
scroller.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(_tabListBackground);
panel.setOpaque(true);
panel.add(scroller);
panel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
if (_popup != null) {
if (_popup.isPopupVisible()) {
_popup.hidePopupImmediately();
}
_popup = null;
}
_popup = com.jidesoft.popup.JidePopupFactory.getSharedInstance().createPopup();
_popup.setPopupBorder(BorderFactory.createLineBorder(_darkShadow));
_popup.add(panel);
_popup.addExcludedComponent(listButton);
_popup.setDefaultFocusComponent(list);
DefaultListModel listModel = new DefaultListModel();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
int totalCount = _tabPane.getTabCount();
for (int i = 0; i < totalCount; i++) {
listModel.addElement(_tabPane);
}
list.setCellRenderer(getTabListCellRenderer());
list.setModel(listModel);
list.setSelectedIndex(selectedIndex);
list.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
componentSelected(list);
}
}
public void keyReleased(KeyEvent e) {
}
});
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
componentSelected(list);
}
});
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Insets insets = panel.getInsets();
int max = (PortingUtils.getLocalScreenSize(_tabPane).height - insets.top - insets.bottom) / list.getCellBounds(0, 0).height;
if (listModel.getSize() > max) {
list.setVisibleRowCount(max);
}
else {
list.setVisibleRowCount(listModel.getSize());
}
_popup.setOwner(_tabPane);
_popup.removeExcludedComponent(_tabPane);
Dimension size = _popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
Point p = listButton.getLocationOnScreen();
bounds.x = p.x;
bounds.y = p.y;
int x;
int y;
switch (tabPlacement) {
case TOP:
default:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y + bounds.height + 2;
break;
case BOTTOM:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y - size.height - 2;
break;
case LEFT:
x = bounds.x + bounds.width + 2;
y = bounds.y + bounds.height - size.height;
break;
case RIGHT:
x = bounds.x - size.width - 2;
y = bounds.y + bounds.height - size.height;
break;
}
Rectangle screenBounds = PortingUtils.getScreenBounds(_tabPane);
int right = x + size.width + 3;
int bottom = y + size.height + 3;
if (right > screenBounds.x + screenBounds.width) {
x -= right - screenBounds.x - screenBounds.width; // move left so that the whole popup can fit in
}
if (x < screenBounds.x) {
x = screenBounds.x; // move right so that the whole popup can fit in
}
if (bottom > screenBounds.height) {
y -= bottom - screenBounds.height;
}
if (y < screenBounds.y) {
y = screenBounds.y;
}
_popup.showPopup(x, y);
}
private void componentSelected(JList list) {
int tabIndex = list.getSelectedIndex();
if (tabIndex != -1 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
Runnable runnable = new Runnable() {
public void run() {
_tabPane.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
Runnable runnable = new Runnable() {
public void run() {
if (lastFocused != null) {
lastFocused.requestFocus();
}
else if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocus();
}
}
};
SwingUtilities.invokeLater(runnable);
}
});
}
else {
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
Runnable runnable = new Runnable() {
public void run() {
lastFocused.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
else {
Container container;
if (comp instanceof Container) {
container = (Container) comp;
}
else {
container = comp.getFocusCycleRootAncestor();
}
FocusTraversalPolicy traversalPolicy = container.getFocusTraversalPolicy();
Component focusComponent;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(container);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(container);
}
}
else if (comp instanceof Container) {
// not sure if it is correct
focusComponent = findFocusableComponent((Container) comp);
}
else {
focusComponent = comp;
}
if (focusComponent != null) {
final Component theComponent = focusComponent;
Runnable runnable = new Runnable() {
public void run() {
theComponent.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
}
}
ensureActiveTabIsVisible(false);
_popup.hidePopupImmediately();
_popup = null;
}
}
private Component findFocusableComponent(Container parent) {
FocusTraversalPolicy traversalPolicy = parent.getFocusTraversalPolicy();
Component focusComponent = null;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(parent);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(parent);
}
}
if (focusComponent != null) {
return focusComponent;
}
int i = 0;
while (i < parent.getComponentCount()) {
Component comp = parent.getComponent(i);
if (comp instanceof Container) {
focusComponent = findFocusableComponent((Container) comp);
if (focusComponent != null) {
return focusComponent;
}
}
else if (comp.isFocusable()) {
return comp;
}
i++;
}
if (parent.isFocusable()) {
return parent;
}
return null;
}
public void scrollForward(int tabPlacement) {
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (viewRect.width >= viewSize.width - viewRect.x) {
return; // no room left to scroll
}
}
else { // tabPlacement == LEFT || tabPlacement == RIGHT
if (viewRect.height >= viewSize.height - viewRect.y) {
return;
}
}
setLeadingTabIndex(tabPlacement, leadingTabIndex + 1);
}
public void scrollBackward(int tabPlacement) {
setLeadingTabIndex(tabPlacement, leadingTabIndex > 0 ? leadingTabIndex - 1 : 0);
}
public void setLeadingTabIndex(int tabPlacement, int index) {
// make sure the index is in range
if (index < 0 || index >= _tabPane.getTabCount()) {
return;
}
leadingTabIndex = index;
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
switch (tabPlacement) {
case TOP:
case BOTTOM:
tabViewPosition.y = 0;
if (_tabPane.getComponentOrientation().isLeftToRight()) {
tabViewPosition.x = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].x;
}
else {
tabViewPosition.x = (_rects.length <= 0 || leadingTabIndex == 0) ? 0 : _rects[0].x - _rects[leadingTabIndex].x + (_rects[0].width - _rects[leadingTabIndex].width) + 25;
}
if ((viewSize.width - tabViewPosition.x) < viewRect.width) {
tabViewPosition.x = viewSize.width - viewRect.width;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewSize.width - tabViewPosition.x,
// viewRect.height);
// System.out.println("setExtendedSize: " + extentSize);
// viewport.setExtentSize(extentSize);
}
break;
case LEFT:
case RIGHT:
tabViewPosition.x = 0;
tabViewPosition.y = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].y;
if ((viewSize.height - tabViewPosition.y) < viewRect.height) {
tabViewPosition.y = viewSize.height - viewRect.height;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewRect.width,
// viewSize.height - tabViewPosition.y);
// viewport.setExtentSize(extentSize);
}
break;
}
viewport.setViewPosition(tabViewPosition);
_tabPane.repaint();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight() && tabViewPosition.x == 0) {
// In current workaround, tabViewPosition set to 0 cannot trigger state change event
stateChanged(new ChangeEvent(viewport));
}
}
public void stateChanged(ChangeEvent e) {
if (_tabPane == null) return;
ensureCurrentLayout();
JViewport viewport = (JViewport) e.getSource();
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Rectangle vpRect = viewport.getBounds();
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
leadingTabIndex = getClosestTab(viewRect.x + viewRect.width, viewRect.y + viewRect.height);
if (leadingTabIndex < 0) {
leadingTabIndex = 0;
}
}
else {
leadingTabIndex = getClosestTab(viewRect.x, viewRect.y);
}
// If the tab isn't right aligned, adjust it.
if (leadingTabIndex < _rects.length && leadingTabIndex >= _rects.length) {
switch (tabPlacement) {
case TOP:
case BOTTOM:
if (_rects[leadingTabIndex].x < viewRect.x) {
leadingTabIndex++;
}
break;
case LEFT:
case RIGHT:
if (_rects[leadingTabIndex].y < viewRect.y) {
leadingTabIndex++;
}
break;
}
}
Insets contentInsets = getContentBorderInsets(tabPlacement);
int checkX;
switch (tabPlacement) {
case LEFT:
_tabPane.repaint(vpRect.x + vpRect.width, vpRect.y, contentInsets.left, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case RIGHT:
_tabPane.repaint(vpRect.x - contentInsets.right, vpRect.y, contentInsets.right, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case BOTTOM:
_tabPane.repaint(vpRect.x, vpRect.y - contentInsets.bottom, vpRect.width, contentInsets.bottom);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
break;
case TOP:
default:
_tabPane.repaint(vpRect.x, vpRect.y + vpRect.height, vpRect.width, contentInsets.top);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
}
if (SystemInfo.isJdk15Above()) {
_tabPane.setComponentZOrder(_tabScroller.scrollForwardButton, 0);
_tabPane.setComponentZOrder(_tabScroller.scrollBackwardButton, 0);
}
_tabScroller.scrollForwardButton.repaint();
_tabScroller.scrollBackwardButton.repaint();
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount()) {
closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex));
}
}
@Override
public String toString() {
return "viewport.viewSize=" + viewport.getViewSize() + "\n" +
"viewport.viewRectangle=" + viewport.getViewRect() + "\n" +
"leadingTabIndex=" + leadingTabIndex + "\n" +
"tabViewPosition=" + tabViewPosition;
}
}
public class ScrollableTabViewport extends JViewport implements UIResource {
int _expectViewX = 0;
boolean _protectView = false;
public ScrollableTabViewport() {
super();
setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
setOpaque(false);
setLayout(new ViewportLayout() {
private static final long serialVersionUID = -1069760662716244442L;
@Override
public void layoutContainer(Container parent) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
_protectView = true;
}
try {
super.layoutContainer(parent);
}
finally {
_protectView = false;
}
}
});
}
/**
* Gets the background color of this component.
*
* @return this component's background color; if this component does not have a background color, the background
* color of its parent is returned
*/
@Override
public Color getBackground() {
return UIDefaultsLookup.getColor("JideTabbedPane.background");
}
// workaround for swing bug
@Override
public void setViewPosition(Point p) {
int oldX = _expectViewX;
_expectViewX = p.x;
super.setViewPosition(p); // to trigger state change event, so the adjustment for RTL need to be done at ScrollableTabPanel#setBounds()
if (_protectView) {
_expectViewX = oldX;
Point savedPosition = new Point(oldX, p.y);
super.setViewPosition(savedPosition);
}
}
public int getExpectedViewX() {
return _expectViewX;
}
}
public class ScrollableTabPanel extends JPanel implements UIResource {
public ScrollableTabPanel() {
setLayout(null);
}
@Override
public boolean isOpaque() {
return false;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_tabPane.isOpaque()) {
if (getTabShape() == JideTabbedPane.SHAPE_BOX) {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"));
}
else {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground"));
}
g.fillRect(0, 0, getWidth(), getHeight());
}
paintTabArea(g, _tabPane.getTabPlacement(), _tabPane.getSelectedIndex(), this);
}
// workaround for swing bug
@Override
public void scrollRectToVisible(Rectangle aRect) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
int startX = aRect.x + _tabScroller.viewport.getExpectedViewX();
if (startX < 0) {
int i;
for (i = _tabScroller.leadingTabIndex; i < _rects.length; i++) {
startX += _rects[i].width;
if (startX >= 0) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.min(i + 1, _rects.length - 1));
}
else if (startX > aRect.x + aRect.width) {
int i;
for (i = _tabScroller.leadingTabIndex - 1; i >= 0; i--) {
startX -= _rects[i].width;
if (startX <= aRect.x + aRect.width) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.max(i, 0));
}
return;
}
super.scrollRectToVisible(aRect);
}
// workaround for swing bug
@Override
public void setBounds(int x, int y, int width, int height) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
super.setBounds(0, y, width, height);
return;
}
super.setBounds(x, y, width, height);
}
// workaround for swing bug
// http://developer.java.sun.com/developer/bugParade/bugs/4668865.html
@Override
public void setToolTipText(String text) {
_tabPane.setToolTipText(text);
}
@Override
public String getToolTipText() {
return _tabPane.getToolTipText();
}
@Override
public String getToolTipText(MouseEvent event) {
return _tabPane.getToolTipText(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public Point getToolTipLocation(MouseEvent event) {
return _tabPane.getToolTipLocation(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public JToolTip createToolTip() {
return _tabPane.createToolTip();
}
}
protected Color _closeButtonSelectedColor = new Color(255, 162, 165);
protected Color _closeButtonColor = Color.BLACK;
protected Color _popupColor = Color.BLACK;
/**
* Close button on the tab.
*/
public class TabCloseButton extends JButton implements MouseMotionListener, MouseListener, UIResource {
public static final int CLOSE_BUTTON = 0;
public static final int EAST_BUTTON = 1;
public static final int WEST_BUTTON = 2;
public static final int NORTH_BUTTON = 3;
public static final int SOUTH_BUTTON = 4;
public static final int LIST_BUTTON = 5;
private int _type;
private int _index = -1;
private boolean _mouseOver = false;
private boolean _mousePressed = false;
/**
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
@Override
public void updateUI() {
super.updateUI();
setMargin(new Insets(0, 0, 0, 0));
setBorder(BorderFactory.createEmptyBorder());
setFocusPainted(false);
setFocusable(false);
setRequestFocusEnabled(false);
String name = getName();
if (name != null) setToolTipText(getResourceString(name));
}
public TabCloseButton() {
this(CLOSE_BUTTON);
}
public TabCloseButton(int type) {
addMouseMotionListener(this);
addMouseListener(this);
setFocusPainted(false);
setFocusable(false);
setType(type);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(5, 5);
}
public int getIndex() {
return _index;
}
public void setIndex(int index) {
_index = index;
}
@Override
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
@Override
protected void paintComponent(Graphics g) {
if (!isEnabled()) {
setMouseOver(false);
setMousePressed(false);
}
if (isMouseOver() && isMousePressed()) {
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
else if (isMouseOver()) {
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
g.setColor(UIDefaultsLookup.getColor("controlShadow").darker());
int centerX = getWidth() >> 1;
int centerY = getHeight() >> 1;
int type = getType();
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
if (type == EAST_BUTTON) {
type = WEST_BUTTON;
}
else if (type == WEST_BUTTON) {
type = EAST_BUTTON;
}
}
switch (type) {
case CLOSE_BUTTON:
if (isEnabled()) {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX - 4, centerY - 3, centerX + 2, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
g.drawLine(centerX + 2, centerY - 3, centerX - 4, centerY + 3);
}
else {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
}
break;
case EAST_BUTTON:
//
// |
// ||
// |||
// ||||
// ||||*
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX + 2, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 3, y - 3, x - 3, y + 3);
g.drawLine(x - 2, y - 2, x - 2, y + 2);
g.drawLine(x - 1, y - 1, x - 1, y + 1);
g.drawLine(x, y, x, y);
}
else {
g.drawLine(x - 4, y - 4, x, y);
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
else {
int x = centerX + 3, y = centerY - 2; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 7, y + 1, x - 1, y + 1);
g.drawLine(x - 6, y + 2, x - 2, y + 2);
g.drawLine(x - 5, y + 3, x - 3, y + 3);
g.drawLine(x - 4, y + 4, x - 4, y + 4);
}
else {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 8, y, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
}
break;
case WEST_BUTTON: {
//
// |
// ||
// |||
// ||||
// *||||
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX - 3, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x, y);
g.drawLine(x + 1, y - 1, x + 1, y + 1);
g.drawLine(x + 2, y - 2, x + 2, y + 2);
g.drawLine(x + 3, y - 3, x + 3, y + 3);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
else {
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x, y, x + 4, y + 4);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
}
else {
int x = centerX - 5, y = centerY + 3; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x + 8, y);
g.drawLine(x + 1, y - 1, x + 7, y - 1);
g.drawLine(x + 2, y - 2, x + 6, y - 2);
g.drawLine(x + 3, y - 3, x + 5, y - 3);
g.drawLine(x + 4, y - 4, x + 4, y - 4);
}
else {
g.drawLine(x, y, x + 8, y);
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x + 8, y, x + 4, y - 4);
}
}
}
break;
}
case LIST_BUTTON: {
int x = centerX + 2, y = centerY; // start point. mark as
// * above
g.drawLine(x - 6, y - 4, x - 6, y + 4);
g.drawLine(x + 1, y - 4, x + 1, y + 4);
g.drawLine(x - 6, y - 4, x + 1, y - 4);
g.drawLine(x - 4, y - 2, x - 1, y - 2);
g.drawLine(x - 4, y, x - 1, y);
g.drawLine(x - 4, y + 2, x - 1, y + 2);
g.drawLine(x - 6, y + 4, x + 1, y + 4);
break;
}
}
}
@Override
public boolean isFocusable() {
return false;
}
@Override
public void requestFocus() {
}
@Override
public boolean isOpaque() {
return false;
}
public boolean scrollsForward() {
return getType() == EAST_BUTTON || getType() == SOUTH_BUTTON;
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
setMousePressed(false);
}
public void mousePressed(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(true);
repaint();
}
public void mouseReleased(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(false);
setMouseOver(false);
}
public void mouseEntered(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseExited(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(false);
setMousePressed(false);
repaint();
_tabScroller.tabPanel.repaint();
}
public int getType() {
return _type;
}
public void setType(int type) {
_type = type;
}
public boolean isMouseOver() {
return _mouseOver;
}
public void setMouseOver(boolean mouseOver) {
_mouseOver = mouseOver;
}
public boolean isMousePressed() {
return _mousePressed;
}
public void setMousePressed(boolean mousePressed) {
_mousePressed = mousePressed;
}
}
// Controller: event listeners
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class PropertyChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
String name = e.getPropertyName();
if ("mnemonicAt".equals(name)) {
updateMnemonics();
pane.repaint();
}
else if ("displayedMnemonicIndexAt".equals(name)) {
pane.repaint();
}
else if (name.equals("indexForTitle")) {
int index = (Integer) e.getNewValue();
String title = getCurrentDisplayTitleAt(_tabPane, index);
if (BasicHTML.isHTMLString(title)) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(_tabPane, title);
htmlViews.setElementAt(v, index);
}
}
else {
if (htmlViews != null && htmlViews.elementAt(index) != null) {
htmlViews.setElementAt(null, index);
}
}
updateMnemonics();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(
_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(false);
}
}
else if (name.equals("tabLayoutPolicy")) {
_tabPane.updateUI();
}
else if (name.equals("closeTabAction")) {
updateCloseAction();
}
else if (name.equals(JideTabbedPane.PROPERTY_DRAG_OVER_DISABLED)) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_COLOR_PROVIDER)) {
_tabPane.repaint();
}
else if (name.equals("locale")) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.BOLDACTIVETAB_PROPERTY)) {
getTabPanel().invalidate();
_tabPane.invalidate();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_LEADING_COMPONENT)) {
ensureCurrentLayout();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(false);
_tabPane.remove(_tabLeadingComponent);
}
_tabLeadingComponent = (Component) e.getNewValue();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(true);
_tabPane.add(_tabLeadingComponent);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_TRAILING_COMPONENT)) {
ensureCurrentLayout();
if (_tabTrailingComponent != null) {
_tabTrailingComponent.setVisible(false);
_tabPane.remove(_tabTrailingComponent);
}
_tabTrailingComponent = (Component) e.getNewValue();
if (_tabTrailingComponent != null) {
_tabPane.add(_tabTrailingComponent);
_tabTrailingComponent.setVisible(true);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.SHRINK_TAB_PROPERTY) ||
name.equals(JideTabbedPane.HIDE_IF_ONE_TAB_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_AREA_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_CONTENT_PROPERTY) ||
name.equals(JideTabbedPane.BOX_STYLE_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.TAB_CLOSABLE_PROPERTY) ||
name.equals(JideTabbedPane.PROPERTY_TAB_SHAPE) ||
name.equals(JideTabbedPane.PROPERTY_COLOR_THEME) ||
name.equals(JideTabbedPane.PROPERTY_TAB_RESIZE_MODE) ||
name.equals(JideTabbedPane.SHOW_TAB_BUTTONS_PROPERTY)) {
if ((name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY))
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
ensureCloseButtonCreated();
}
_tabPane.updateUI();
}
}
}
protected void updateCloseAction() {
ensureCloseButtonCreated();
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabSelectionHandler implements ChangeListener {
public void stateChanged(ChangeEvent e) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
ensureCloseButtonCreated();
Runnable runnable = new Runnable() {
public void run() {
ensureActiveTabIsVisible(false);
}
};
SwingUtilities.invokeLater(runnable);
}
}
public class TabFocusListener implements FocusListener {
public void focusGained(FocusEvent e) {
repaintSelectedTab();
}
public void focusLost(FocusEvent e) {
repaintSelectedTab();
}
private void repaintSelectedTab() {
if (_tabPane.getTabCount() > 0) {
Rectangle rect = getTabBounds(_tabPane, _tabPane.getSelectedIndex());
if (rect != null) {
_tabPane.repaint(rect);
}
}
}
}
public class MouseMotionHandler extends MouseMotionAdapter {
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class MouseHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isMiddleMouseButton(e)) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
Action action = getActionMap().get("closeTabAction");
if (action != null && tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex) && _tabPane.isCloseTabOnMouseMiddleButton() && _tabPane.isTabClosableAt(tabIndex)) {
ActionEvent event = new ActionEvent(_tabPane, tabIndex, "middleMouseButtonClicked");
action.actionPerformed(event);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isLeftMouseButton(e) || _tabPane.isRightClickSelect()) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
_tabPane.processMouseSelection(tabIndex, e);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else if (_tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
});
}
else {
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else {
// first try to find a default component.
boolean foundInTab = JideSwingUtilities.compositeRequestFocus(comp);
if (!foundInTab) { // && !_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
if (!isTabEditing())
startEditing(e); // start editing tab
}
}
public class MouseWheelHandler implements MouseWheelListener {
public void mouseWheelMoved(MouseWheelEvent e) {
if (_tabPane.isScrollSelectedTabOnWheel()) {
// set selected tab to the currently selected tab plus the wheel rotation but between
// 0 and tabCount-1
_tabPane.setSelectedIndex(
Math.min(_tabPane.getTabCount() - 1, Math.max(0, _tabPane.getSelectedIndex() + e.getWheelRotation())));
}
else if (scrollableTabLayoutEnabled() && e.getWheelRotation() != 0) {
if (e.getWheelRotation() > 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollForward(_tabPane.getTabPlacement());
}
}
else if (e.getWheelRotation() < 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollBackward(_tabPane.getTabPlacement());
}
}
}
}
}
private class ComponentHandler implements ComponentListener {
public void componentResized(ComponentEvent e) {
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
/* GES 2/3/99:
The container listener code was added to support HTML
rendering of tab titles.
Ideally, we would be able to listen for property changes
when a tab is added or its text modified. At the moment
there are no such events because the Beans spec doesn't
allow 'indexed' property changes (i.e. tab 2's text changed
from A to B).
In order to get around this, we listen for tabs to be added
or removed by listening for the container events. we then
queue up a runnable (so the component has a chance to complete
the add) which checks the tab title of the new component to see
if it requires HTML rendering.
The Views (one per tab title requiring HTML rendering) are
stored in the htmlViews Vector, which is only allocated after
the first time we run into an HTML tab. Note that this vector
is kept in step with the number of pages, and nulls are added
for those pages whose tab title do not require HTML rendering.
This makes it easy for the paint and layout code to tell
whether to invoke the HTML engine without having to check
the string during time-sensitive operations.
When we have added a way to listen for tab additions and
changes to tab text, this code should be removed and
replaced by something which uses that. */
private class ContainerHandler implements ContainerListener {
public void componentAdded(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
int index = tp.indexOfComponent(child);
String title = getCurrentDisplayTitleAt(tp, index);
boolean isHTML = BasicHTML.isHTMLString(title);
if (isHTML) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(tp, title);
htmlViews.insertElementAt(v, index);
}
}
else { // Not HTML
if (htmlViews != null) { // Add placeholder
htmlViews.insertElementAt(null, index);
} // else nada!
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
}
public void componentRemoved(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
// NOTE 4/15/2002 (joutwate):
// This fix is implemented using client properties since there is
// currently no IndexPropertyChangeEvent. Once
// IndexPropertyChangeEvents have been added this code should be
// modified to use it.
Integer index =
(Integer) tp.getClientProperty("__index_to_remove__");
if (index != null) {
if (htmlViews != null && htmlViews.size() > index) {
htmlViews.removeElementAt(index);
}
tp.putClientProperty("__index_to_remove__", null);
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
// ensureActiveTabIsVisible(true);
}
}
private Vector createHTMLVector() {
Vector htmlViews = new Vector();
int count = _tabPane.getTabCount();
if (count > 0) {
for (int i = 0; i < count; i++) {
String title = getCurrentDisplayTitleAt(_tabPane, i);
if (BasicHTML.isHTMLString(title)) {
htmlViews.addElement(BasicHTML.createHTMLView(_tabPane, title));
}
else {
htmlViews.addElement(null);
}
}
}
return htmlViews;
}
@Override
public Component getTabPanel() {
if (scrollableTabLayoutEnabled())
return _tabScroller.tabPanel;
else
return _tabPane;
}
static class AbstractTab {
int width;
int id;
public void copy(AbstractTab tab) {
this.width = tab.width;
this.id = tab.id;
}
}
public static class TabSpaceAllocator {
static final int startOffset = 4;
private Insets insets = null;
static final int tabWidth = 24;
static final int textIconGap = 8;
private AbstractTab tabs[];
private void setInsets(Insets insets) {
this.insets = (Insets) insets.clone();
}
private void init(Rectangle rects[], Insets insets) {
setInsets(insets);
tabs = new AbstractTab[rects.length];
// fill up internal datastructure
for (int i = 0; i < rects.length; i++) {
tabs[i] = new AbstractTab();
tabs[i].id = i;
tabs[i].width = rects[i].width;
}
tabSort();
}
private void bestfit(AbstractTab tabs[], int freeWidth, int startTab) {
int tabCount = tabs.length;
int worstWidth;
int currentTabWidth;
int initialPos;
currentTabWidth = tabs[startTab].width;
initialPos = startTab;
if (startTab == tabCount - 1) {
// directly fill as worst case
tabs[startTab].width = freeWidth;
return;
}
worstWidth = freeWidth / (tabCount - startTab);
while (currentTabWidth < worstWidth) {
freeWidth -= currentTabWidth;
if (++startTab < tabCount - 1) {
currentTabWidth = tabs[startTab].width;
}
else {
tabs[startTab].width = worstWidth;
return;
}
}
if (startTab == initialPos) {
// didn't find anything smaller
for (int i = startTab; i < tabCount; i++) {
tabs[i].width = worstWidth;
}
}
else if (startTab < tabCount - 1) {
bestfit(tabs, freeWidth, startTab);
}
}
// bubble sort for now
private void tabSort() {
int tabCount = tabs.length;
AbstractTab tempTab = new AbstractTab();
for (int i = 0; i < tabCount - 1; i++) {
for (int j = i + 1; j < tabCount; j++) {
if (tabs[i].width > tabs[j].width) {
tempTab.copy(tabs[j]);
tabs[j].copy(tabs[i]);
tabs[i].copy(tempTab);
}
}
}
}
// directly modify the rects
private void outpush(Rectangle rects[]) {
for (AbstractTab tab : tabs) {
rects[tab.id].width = tab.width;
}
rects[0].x = startOffset;
for (int i = 1; i < rects.length; i++) {
rects[i].x = rects[i - 1].x + rects[i - 1].width;
}
}
public void reArrange(Rectangle rects[], Insets insets, int totalAvailableSpace) {
init(rects, insets);
bestfit(tabs, totalAvailableSpace, 0);
outpush(rects);
clearup();
}
private void clearup() {
for (int i = 0; i < tabs.length; i++) {
tabs[i] = null;
}
tabs = null;
}
}
@Override
public void ensureActiveTabIsVisible(boolean scrollLeft) {
if (_tabPane == null || _tabPane.getWidth() == 0) {
return;
}
if (scrollableTabLayoutEnabled()) {
ensureCurrentLayout();
if (scrollLeft && _rects.length > 0) {
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
_tabScroller.tabPanel.scrollRectToVisible(_rects[0]);
}
else {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
}
int index = _tabPane.getSelectedIndex();
if ((!scrollLeft || index != 0) && index < _rects.length && index != -1) {
if (index == 0) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
else {
if (index == _rects.length - 1) { // last one, scroll to the end
Rectangle lastRect = _rects[index];
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && _tabPane.getComponentOrientation().isLeftToRight()) {
lastRect.width = _tabScroller.tabPanel.getWidth() - lastRect.x;
}
_tabScroller.tabPanel.scrollRectToVisible(lastRect);
}
else {
_tabScroller.tabPanel.scrollRectToVisible(_rects[index]);
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.tabPanel.getParent().doLayout();
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabPane.revalidate();
_tabPane.repaintTabAreaAndContentBorder();
}
else {
_tabPane.repaint();
}
}
}
protected boolean isShowCloseButtonOnTab() {
if (_tabPane.isUseDefaultShowCloseButtonOnTab()) {
return _showCloseButtonOnTab;
}
else return _tabPane.isShowCloseButtonOnTab();
}
protected boolean isShowCloseButton() {
return _tabPane.isShowCloseButton();
}
public void ensureCloseButtonCreated() {
if (isShowCloseButton() && isShowCloseButtonOnTab() && scrollableTabLayoutEnabled()) {
if (_closeButtons == null) {
_closeButtons = new TabCloseButton[_tabPane.getTabCount()];
}
else if (_closeButtons.length > _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0, temp.length);
for (int i = temp.length; i < _closeButtons.length; i++) {
TabCloseButton tabCloseButton = _closeButtons[i];
_tabScroller.tabPanel.remove(tabCloseButton);
}
_closeButtons = temp;
}
else if (_closeButtons.length < _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0,
_closeButtons.length);
_closeButtons = temp;
}
ActionMap am = getActionMap();
for (int i = 0; i < _closeButtons.length; i++) {
TabCloseButton closeButton = _closeButtons[i];
if (closeButton == null) {
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName("JideTabbedPane.close");
_closeButtons[i] = closeButton;
closeButton.setBounds(0, 0, 0, 0);
Action action = _tabPane.getCloseAction();
closeButton.setAction(am.get("closeTabAction"));
updateButtonFromAction(closeButton, action);
_tabScroller.tabPanel.add(closeButton);
}
closeButton.setIndex(i);
}
}
}
private void updateButtonFromAction(TabCloseButton closeButton, Action action) {
if (action == null) {
return;
}
closeButton.setEnabled(action.isEnabled());
Object desc = action.getValue(Action.SHORT_DESCRIPTION);
if (desc instanceof String) {
closeButton.setToolTipText((String) desc);
}
Object icon = action.getValue(Action.SMALL_ICON);
if (icon instanceof Icon) {
closeButton.setIcon((Icon) icon);
}
}
protected boolean isShowTabButtons() {
return _tabPane.getTabCount() != 0 && _tabPane.isShowTabArea() && _tabPane.isShowTabButtons();
}
protected boolean isShrinkTabs() {
return _tabPane.getTabCount() != 0 && _tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT;
}
protected TabEditor _tabEditor;
protected boolean _isEditing;
protected int _editingTab = -1;
protected String _oldValue;
protected String _oldPrefix;
protected String _oldPostfix;
// mtf - changed
protected Component _originalFocusComponent;
@Override
public boolean isTabEditing() {
return _isEditing;
}
protected TabEditor createDefaultTabEditor() {
final TabEditor editor = new TabEditor();
editor.getDocument().addDocumentListener(this);
editor.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
return true;
}
public boolean shouldYieldFocus(JComponent input) {
boolean shouldStopEditing = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
shouldStopEditing = _tabPane.getTabEditingValidator().alertIfInvalid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (shouldStopEditing && _tabPane != null && _tabPane.isTabEditing()) {
_tabPane.stopTabEditing();
}
return shouldStopEditing;
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_originalFocusComponent = e.getOppositeComponent();
}
@Override
public void focusLost(FocusEvent e) {
}
});
editor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editor.transferFocus();
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (_isEditing && (e.getKeyCode() == KeyEvent.VK_ESCAPE)) {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldValue);
}
_tabPane.cancelTabEditing();
}
}
});
editor.setFont(_tabPane.getFont());
return editor;
}
@Override
public void stopTabEditing() {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
cancelTabEditing();
}
@Override
public void cancelTabEditing() {
if (_tabEditor != null) {
_isEditing = false;
((Container) getTabPanel()).remove(_tabEditor);
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
Rectangle tabRect = _tabPane.getBoundsAt(_editingTab);
getTabPanel().repaint(tabRect.x, tabRect.y,
tabRect.width, tabRect.height);
}
else {
getTabPanel().repaint();
}
if (_originalFocusComponent != null)
_originalFocusComponent.requestFocus(); // InWindow();
else
_tabPane.requestFocusForVisibleComponent();
_editingTab = -1;
_oldValue = null;
_tabPane.doLayout();
}
}
@Override
public boolean editTabAt(int tabIndex) {
if (_isEditing) {
return false;
}
// _tabPane.popupSelectedIndex(tabIndex);
if (_tabEditor == null)
_tabEditor = createDefaultTabEditor();
if (_tabEditor != null) {
prepareEditor(_tabEditor, tabIndex);
((Container) getTabPanel()).add(_tabEditor);
resizeEditor(tabIndex);
_editingTab = tabIndex;
_isEditing = true;
_tabEditor.requestFocusInWindow();
_tabEditor.selectAll();
return true;
}
return false;
}
@Override
public int getEditingTabIndex() {
return _editingTab;
}
protected void prepareEditor(TabEditor e, int tabIndex) {
Font font;
if (_tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (_tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
e.setFont(font);
_oldValue = _tabPane.getTitleAt(tabIndex);
if (_oldValue.startsWith("<HTML>") && _oldValue.endsWith("/HTML>")) {
_oldPrefix = "<HTML>";
_oldPostfix = "</HTML>";
String title = _oldValue.substring("<HTML>".length(), _oldValue.length() - "</HTML>".length());
if (title.startsWith("<B>") && title.endsWith("/B>")) {
title = title.substring("<B>".length(), title.length() - "</B>".length());
_oldPrefix += "<B>";
_oldPostfix = "</B>" + _oldPostfix;
}
e.setText(title);
}
else {
_oldPrefix = "";
_oldPostfix = "";
e.setText(_oldValue);
}
e.selectAll();
e.setForeground(_tabPane.getForegroundAt(tabIndex));
}
protected Rectangle getTabsTextBoundsAt(int tabIndex) {
Rectangle tabRect = _tabPane.getBoundsAt(tabIndex);
Rectangle iconRect = new Rectangle(),
textRect = new Rectangle();
if (tabRect.width < 200) // random max size;
tabRect.width = 200;
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
while (title == null || title.length() < 3)
title += " ";
Icon icon = _tabPane.getIconForTab(tabIndex);
Font font = _tabPane.getFont();
if (tabIndex == _tabPane.getSelectedIndex() && _tabPane.isBoldActiveTab()) {
font = font.deriveFont(Font.BOLD);
}
SwingUtilities.layoutCompoundLabel(_tabPane, _tabPane.getGraphics().getFontMetrics(font), title, icon,
SwingUtilities.CENTER, SwingUtilities.CENTER,
SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect,
iconRect, textRect, icon == null ? 0 : _textIconGap);
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
iconRect.x = tabRect.x + _iconMargin;
textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding);
textRect.width += 2;
}
else {
iconRect.y = tabRect.y + _iconMargin;
textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding);
iconRect.x = tabRect.x + 2;
textRect.x = tabRect.x + 2;
textRect.height += 2;
}
return textRect;
}
private void updateTab() {
if (_isEditing) {
resizeEditor(getEditingTabIndex());
}
}
public void insertUpdate(DocumentEvent e) {
updateTab();
}
public void removeUpdate(DocumentEvent e) {
updateTab();
}
public void changedUpdate(DocumentEvent e) {
updateTab();
}
protected void resizeEditor(int tabIndex) {
// note - this should use the logic of label paint text so that the text overlays exactly.
Rectangle tabsTextBoundsAt = getTabsTextBoundsAt(tabIndex);
if (tabsTextBoundsAt.isEmpty()) {
tabsTextBoundsAt = new Rectangle(14, 3); // note - 14 should be the font height but...
}
tabsTextBoundsAt.x = tabsTextBoundsAt.x - _tabEditor.getBorder().getBorderInsets(_tabEditor).left;
tabsTextBoundsAt.width = +tabsTextBoundsAt.width +
_tabEditor.getBorder().getBorderInsets(_tabEditor).left +
_tabEditor.getBorder().getBorderInsets(_tabEditor).right;
tabsTextBoundsAt.y = tabsTextBoundsAt.y - _tabEditor.getBorder().getBorderInsets(_tabEditor).top;
tabsTextBoundsAt.height = tabsTextBoundsAt.height +
_tabEditor.getBorder().getBorderInsets(_tabEditor).top +
_tabEditor.getBorder().getBorderInsets(_tabEditor).bottom;
_tabEditor.setBounds(SwingUtilities.convertRectangle(_tabPane, tabsTextBoundsAt, getTabPanel()));
_tabEditor.invalidate();
_tabEditor.validate();
// getTabPanel().invalidate();
// getTabPanel().validate();
// getTabPanel().repaint();
// getTabPanel().doLayout();
_tabPane.doLayout();
// mtf - note - this is an exteme repaint but we need to paint any content borders
getTabPanel().getParent().getParent().repaint();
}
protected String getCurrentDisplayTitleAt(JideTabbedPane tp, int index) {
String returnTitle = tp.getDisplayTitleAt(index);
if ((_isEditing) && (index == _editingTab))
returnTitle = _tabEditor.getText();
return returnTitle;
}
protected class TabEditor extends JTextField implements UIResource {
TabEditor() {
setOpaque(false);
// setBorder(BorderFactory.createEmptyBorder());
setBorder(BorderFactory
.createCompoundBorder(new PartialLineBorder(Color.BLACK, 1, true),
BorderFactory.createEmptyBorder(0, 2, 0, 2)));
}
public boolean stopEditing() {
return true;
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Composite orgComposite = g2.getComposite();
Color orgColor = g2.getColor();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.70f));
Object o = JideSwingUtilities.setupShapeAntialiasing(g);
g2.setColor(getBackground());
g.fillRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 1, 1);
JideSwingUtilities.restoreShapeAntialiasing(g, o);
g2.setColor(orgColor);
g2.setComposite(orgComposite);
super.paintComponent(g);
}
}
public void startEditing(MouseEvent e) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (!e.isPopupTrigger() && tabIndex >= 0
&& _tabPane.isEnabledAt(tabIndex)
&& _tabPane.isTabEditingAllowed() && (e.getClickCount() == 2)) {
boolean shouldEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldEdit = _tabPane.getTabEditingValidator().shouldStartEdit(tabIndex, e);
if (shouldEdit) {
e.consume();
_tabPane.editTabAt(tabIndex);
}
}
if (e.getClickCount() == 1) {
if (_tabPane.isTabEditing()) {
boolean shouldStopEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldStopEdit = _tabPane.getTabEditingValidator().alertIfInvalid(tabIndex, _oldPrefix + _tabEditor.getText() + _oldPostfix);
if (shouldStopEdit)
_tabPane.stopTabEditing();
}
}
}
public ThemePainter getPainter() {
return _painter;
}
private class DragOverTimer extends Timer implements ActionListener {
private int _index;
private static final long serialVersionUID = -2529347876574638854L;
public DragOverTimer(int index) {
super(500, null);
_index = index;
addActionListener(this);
setRepeats(false);
}
public void actionPerformed(ActionEvent e) {
if (_tabPane.getTabCount() == 0) {
return;
}
if (_index == _tabPane.getSelectedIndex()) {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
_tabPane.repaint(getTabBounds(_tabPane, _index));
}
}
else {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
}
_tabPane.setSelectedIndex(_index);
}
stop();
}
}
private class DropListener implements DropTargetListener {
private DragOverTimer _timer;
int _index = -1;
public DropListener() {
}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
if (!_tabPane.isEnabled()) {
return;
}
int tabIndex = getTabAtLocation(dtde.getLocation().x, dtde.getLocation().y);
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex()) {
// selected already, do nothing
}
else if (tabIndex == _index) {
// same tab, timer has started
}
else {
stopTimer();
startTimer(tabIndex);
_index = tabIndex; // save the index
}
}
else {
stopTimer();
}
dtde.rejectDrag();
}
private void startTimer(int tabIndex) {
_timer = new DragOverTimer(tabIndex);
_timer.start();
}
private void stopTimer() {
if (_timer != null) {
_timer.stop();
_timer = null;
_index = -1;
}
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dte) {
stopTimer();
}
public void drop(DropTargetDropEvent dtde) {
stopTimer();
}
}
protected void paintFocusIndicator(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect,
boolean isSelected) {
Rectangle tabRect = new Rectangle(rects[tabIndex]);
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
tabRect.x += _tabScroller.viewport.getExpectedViewX();
}
if (_tabPane.hasFocus() && isSelected) {
int x, y, w, h;
g.setColor(_focus);
switch (tabPlacement) {
case LEFT:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case RIGHT:
x = tabRect.x + 2;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case BOTTOM:
x = tabRect.x + 3;
y = tabRect.y + 2;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
break;
case TOP:
default:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
}
BasicGraphicsUtils.drawDashedRect(g, x, y, w, h);
}
}
protected boolean isRoundedCorner() {
return "true".equals(SecurityUtils.getProperty("shadingtheme", "false"));
}
protected int getTabShape() {
return _tabPane.getTabShape();
}
protected int getTabResizeMode() {
return _tabPane.getTabResizeMode();
}
protected int getColorTheme() {
return _tabPane.getColorTheme();
}
// for debug purpose
final protected boolean PAINT_TAB = true;
final protected boolean PAINT_TAB_BORDER = true;
final protected boolean PAINT_TAB_BACKGROUND = true;
final protected boolean PAINT_TABAREA = true;
final protected boolean PAINT_CONTENT_BORDER = true;
final protected boolean PAINT_CONTENT_BORDER_EDGE = true;
protected int getLeftMargin() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return OFFICE2003_LEFT_MARGIN;
}
else if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else {
return DEFAULT_LEFT_MARGIN;
}
}
protected int getTabGap() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return 4;
}
else {
return 0;
}
}
protected int getLayoutSize() {
int tabShape = getTabShape();
if (tabShape == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else if (tabShape == JideTabbedPane.SHAPE_ECLIPSE3X) {
return 15;
}
else if (_tabPane.getTabShape() == JideTabbedPane.SHAPE_FLAT || _tabPane.getTabShape() == JideTabbedPane.SHAPE_ROUNDED_FLAT) {
return 2;
}
else if (tabShape == JideTabbedPane.SHAPE_WINDOWS
|| tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return 6;
}
else {
return 0;
}
}
protected int getTabRightPadding() {
if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return 4;
}
else {
return 0;
}
}
protected MouseListener createMouseListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseHandler();
}
else {
return new MouseHandler();
}
}
protected MouseWheelListener createMouseWheelListener() {
return new MouseWheelHandler();
}
protected MouseMotionListener createMouseMotionListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseMotionHandler();
}
else {
return new MouseMotionHandler();
}
}
public class DefaultMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class DefaultMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
}
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
public class RolloverMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class RolloverMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
protected boolean isTabLeadingComponentVisible() {
return _tabPane.isTabShown() && _tabLeadingComponent != null && _tabLeadingComponent.isVisible();
}
protected boolean isTabTrailingComponentVisible() {
return _tabPane.isTabShown() && _tabTrailingComponent != null && _tabTrailingComponent.isVisible();
}
protected boolean isTabTopVisible(int tabPlacement) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement));
case TOP:
case BOTTOM:
default:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement));
}
}
protected boolean showFocusIndicator() {
return _tabPane.hasFocusComponent() && _showFocusIndicator;
}
private int getNumberOfTabButtons() {
int numberOfButtons = (!isShowTabButtons() || isShrinkTabs()) ? 1 : 4;
if (!isShowCloseButton() || isShowCloseButtonOnTab()) {
numberOfButtons--;
}
return numberOfButtons;
}
/**
* Gets the resource string used in DocumentPane. Subclass can override it to provide their own strings.
*
* @param key the resource key
* @return the localized string.
*/
protected String getResourceString(String key) {
return Resource.getResourceBundle(_tabPane != null ? _tabPane.getLocale() : Locale.getDefault()).getString(key);
}
}
| protected boolean requestFocusForVisibleComponent() {
Component visibleComponent = getVisibleComponent();
Component lastFocused = _tabPane.getLastFocusedComponent(visibleComponent);
if (lastFocused != null && lastFocused.requestFocusInWindow()) {
return true;
}
else if (visibleComponent != null && JideSwingUtilities.passesFocusabilityTest(visibleComponent)) { // visibleComponent.isFocusTraversable()) {
JideSwingUtilities.compositeRequestFocus(visibleComponent);
return true;
}
else if (visibleComponent instanceof JComponent) {
if (((JComponent) visibleComponent).requestDefaultFocus()) {
return true;
}
}
return false;
}
private static class RightAction extends AbstractAction {
private static final long serialVersionUID = -1759791760116532857L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(EAST);
}
}
private static class LeftAction extends AbstractAction {
private static final long serialVersionUID = 8670680299012169408L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(WEST);
}
}
private static class UpAction extends AbstractAction {
private static final long serialVersionUID = -6961702501242792445L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NORTH);
}
}
private static class DownAction extends AbstractAction {
private static final long serialVersionUID = -453174268282628886L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(SOUTH);
}
}
private static class NextAction extends AbstractAction {
private static final long serialVersionUID = -154035573464933924L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(NEXT);
}
}
private static class PreviousAction extends AbstractAction {
private static final long serialVersionUID = 2095403667386334865L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.navigateSelectedTab(PREVIOUS);
}
}
private static class PageUpAction extends AbstractAction {
private static final long serialVersionUID = 1154273528778779166L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(WEST);
}
else {
ui.navigateSelectedTab(NORTH);
}
}
}
private static class PageDownAction extends AbstractAction {
private static final long serialVersionUID = 4895454480954468453L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
int tabPlacement = pane.getTabPlacement();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
ui.navigateSelectedTab(EAST);
}
else {
ui.navigateSelectedTab(SOUTH);
}
}
}
private static class RequestFocusAction extends AbstractAction {
private static final long serialVersionUID = 3791111435639724577L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (!pane.requestFocusInWindow()) {
pane.requestFocus();
}
}
}
private static class RequestFocusForVisibleAction extends AbstractAction {
private static final long serialVersionUID = 6677797853998039155L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
ui.requestFocusForVisibleComponent();
}
}
/**
* Selects a tab in the JTabbedPane based on the String of the action command. The tab selected is based on the
* first tab that has a mnemonic matching the first character of the action command.
*/
private static class SetSelectedIndexAction extends AbstractAction {
private static final long serialVersionUID = 6216635910156115469L;
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
if (pane != null && (pane.getUI() instanceof BasicJideTabbedPaneUI)) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
String command = e.getActionCommand();
if (command != null && command.length() > 0) {
int mnemonic = (int) e.getActionCommand().charAt(0);
if (mnemonic >= 'a' && mnemonic <= 'z') {
mnemonic -= ('a' - 'A');
}
Integer index = (Integer) ui._mnemonicToIndexMap
.get(new Integer(mnemonic));
if (index != null && pane.isEnabledAt(index)) {
pane.setSelectedIndex(index);
}
}
}
}
}
protected TabCloseButton createNoFocusButton(int type) {
return new TabCloseButton(type);
}
private static class ScrollTabsForwardAction extends AbstractAction {
private static final long serialVersionUID = 8772616556895545931L;
public ScrollTabsForwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollForward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollForward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsBackwardAction extends AbstractAction {
private static final long serialVersionUID = -426408621939940046L;
public ScrollTabsBackwardAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollBackward"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
ui._tabScroller.scrollBackward(pane.getTabPlacement());
}
}
}
}
private static class ScrollTabsListAction extends AbstractAction {
private static final long serialVersionUID = 246103712600916771L;
public ScrollTabsListAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.showList"));
}
public void actionPerformed(ActionEvent e) {
JTabbedPane pane = null;
Object src = e.getSource();
if (src instanceof JTabbedPane) {
pane = (JTabbedPane) src;
}
else if (src instanceof TabCloseButton) {
pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src);
}
if (pane != null) {
BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI();
if (ui.scrollableTabLayoutEnabled()) {
if (ui._tabScroller._popup != null && ui._tabScroller._popup.isPopupVisible()) {
ui._tabScroller._popup.hidePopupImmediately();
ui._tabScroller._popup = null;
}
else {
ui._tabScroller.createPopup(pane.getTabPlacement());
}
}
}
}
}
protected void stopOrCancelEditing() {
boolean isEditValid = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
isEditValid = _tabPane.getTabEditingValidator().isValid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (isEditValid)
_tabPane.stopTabEditing();
else
_tabPane.cancelTabEditing();
}
private static class CloseTabAction extends AbstractAction {
private static final long serialVersionUID = 7779678389793199733L;
public CloseTabAction() {
super();
putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.close"));
}
public void actionPerformed(ActionEvent e) {
JideTabbedPane pane;
Object src = e.getSource();
int index;
boolean closeSelected = false;
if (src instanceof JideTabbedPane) {
pane = (JideTabbedPane) src;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof JideTabbedPane) {
pane = (JideTabbedPane) ((TabCloseButton) src).getParent();
closeSelected = true;
}
else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof ScrollableTabPanel) {
pane = (JideTabbedPane) SwingUtilities.getAncestorOfClass(JideTabbedPane.class, (TabCloseButton) src);
closeSelected = false;
}
else {
return; // shouldn't happen
}
if (pane.isTabEditing()) {
((BasicJideTabbedPaneUI) pane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
}
ActionEvent e2 = e;
if (src instanceof TabCloseButton) {
index = ((TabCloseButton) src).getIndex();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
else if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
Component compSrc = index != -1 ? pane.getComponentAt(index) : pane.getSelectedComponent();
// note - We create a new action because we could be in the middle of a chain and
// if we just use setSource we could cause problems.
// also the AWT documentation pooh-pooh this. (for good reason)
if (compSrc != null)
e2 = new ActionEvent(compSrc, e.getID(), e.getActionCommand(), e.getWhen(), e.getModifiers());
}
if (pane.getCloseAction() != null) {
pane.getCloseAction().actionPerformed(e2);
}
else {
if ("middleMouseButtonClicked".equals(e.getActionCommand())) {
index = e.getID();
if (index >= 0)
pane.removeTabAt(index);
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else if (closeSelected) {
if (pane.getSelectedIndex() >= 0)
pane.removeTabAt(pane.getSelectedIndex());
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
else {
int i = ((TabCloseButton) src).getIndex();
if (i != -1) {
int tabIndex = pane.getSelectedIndex();
pane.removeTabAt(i);
if (i < tabIndex) {
pane.setSelectedIndex(tabIndex - 1);
}
if (pane.getTabCount() == 0) {
pane.updateUI();
}
pane.doLayout();
if (pane.getSelectedIndex() >= 0) {
((BasicJideTabbedPaneUI) pane.getUI())._tabScroller.tabPanel.scrollRectToVisible(((BasicJideTabbedPaneUI) pane.getUI())._rects[pane.getSelectedIndex()]);
}
}
}
}
}
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabbedPaneLayout implements LayoutManager {
public void addLayoutComponent(String name, Component comp) {
}
public void removeLayoutComponent(Component comp) {
}
public Dimension preferredLayoutSize(Container parent) {
return calculateSize(false);
}
public Dimension minimumLayoutSize(Container parent) {
return calculateSize(true);
}
protected Dimension calculateSize(boolean minimum) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
Insets contentInsets = getContentBorderInsets(tabPlacement);
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
Dimension zeroSize = new Dimension(0, 0);
int height = contentInsets.top + contentInsets.bottom;
int width = contentInsets.left + contentInsets.right;
int cWidth = 0;
int cHeight = 0;
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
// Determine minimum size required to display largest
// child in each dimension
//
if (_tabPane.isShowTabContent()) {
for (int i = 0; i < _tabPane.getTabCount(); i++) {
Component component = _tabPane.getComponentAt(i);
if (component != null) {
Dimension size = zeroSize;
size = minimum ? component.getMinimumSize() :
component.getPreferredSize();
if (size != null) {
cHeight = Math.max(size.height, cHeight);
cWidth = Math.max(size.width, cWidth);
}
}
}
// Add content border insets to minimum size
width += cWidth;
height += cHeight;
}
int tabExtent;
// Calculate how much space the tabs will need, based on the
// minimum size required to display largest child + content border
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
height = Math.max(height, (minimum ? 0 : calculateMaxTabHeight(tabPlacement)) + tabAreaInsets.top + tabAreaInsets.bottom);
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.width, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.width, tabExtent);
}
width += tabExtent;
break;
case TOP:
case BOTTOM:
default:
if (_tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {
width = Math.max(width, (_tabPane.getTabCount() << 2) +
tabAreaInsets.left + tabAreaInsets.right);
}
else {
width = Math.max(width, (minimum ? 0 : calculateMaxTabWidth(tabPlacement)) +
tabAreaInsets.left + tabAreaInsets.right);
}
if (_tabPane.isTabShown()) {
tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
if (isTabLeadingComponentVisible()) {
tabExtent = Math.max(lsize.height, tabExtent);
}
if (isTabTrailingComponentVisible()) {
tabExtent = Math.max(tsize.height, tabExtent);
}
height += tabExtent;
}
}
}
return new Dimension(width + insets.left + insets.right,
height + insets.bottom + insets.top);
}
protected int preferredTabAreaHeight(int tabPlacement, int width) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int rows = 1;
int x = 0;
int maxTabHeight = calculateMaxTabHeight(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabWidth = calculateTabWidth(tabPlacement, i, metrics);
if (x != 0 && x + tabWidth > width) {
rows++;
x = 0;
}
x += tabWidth;
}
total = calculateTabAreaHeight(tabPlacement, rows, maxTabHeight);
}
return total;
}
protected int preferredTabAreaWidth(int tabPlacement, int height) {
int tabCount = _tabPane.getTabCount();
int total = 0;
if (tabCount > 0) {
int columns = 1;
int y = 0;
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
int tabHeight = calculateTabHeight(tabPlacement, i, metrics);
if (y != 0 && y + tabHeight > height) {
columns++;
y = 0;
}
y += tabHeight;
}
total = calculateTabAreaWidth(tabPlacement, columns, _maxTabWidth);
}
return total;
}
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
synchronized (this) {
ensureCloseButtonCreated();
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
int cx, cy, cw, ch;
int totalTabWidth = 0;
int totalTabHeight = 0;
Insets contentInsets = getContentBorderInsets(tabPlacement);
Component selectedComponent = _tabPane.getComponentAt(selectedIndex);
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + totalTabWidth + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case RIGHT:
totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case BOTTOM:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
break;
case TOP:
default:
totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight);
cx = insets.left + contentInsets.left;
cy = insets.top + totalTabHeight + contentInsets.top;
}
cw = bounds.width - totalTabWidth -
insets.left - insets.right -
contentInsets.left - contentInsets.right;
ch = bounds.height - totalTabHeight -
insets.top - insets.bottom -
contentInsets.top - contentInsets.bottom;
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
child.setBounds(cx, cy, cw, ch);
}
}
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
public void calculateLayoutInfo() {
int tabCount = _tabPane.getTabCount();
assureRectsCreated(tabCount);
calculateTabRects(_tabPane.getTabPlacement(), tabCount);
}
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
int selectedIndex = _tabPane.getSelectedIndex();
int tabRunOverlay;
int i, j;
int x, y;
int returnAt;
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
//
// Calculate bounds within which a tab run must fit
//
switch (tabPlacement) {
case LEFT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
x = size.width - insets.right - tabAreaInsets.right - _maxTabWidth;
y = insets.top + tabAreaInsets.top;
returnAt = size.height - (insets.bottom + tabAreaInsets.bottom);
break;
case BOTTOM:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = size.height - insets.bottom - tabAreaInsets.bottom - _maxTabHeight;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
x = insets.left + tabAreaInsets.left;
y = insets.top + tabAreaInsets.top;
returnAt = size.width - (insets.right + tabAreaInsets.right);
break;
}
tabRunOverlay = getTabRunOverlay(tabPlacement);
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
// Run through tabs and partition them into runs
Rectangle rect;
for (i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabWidth = 0;
rect.x = x;
}
rect.width = calculateTabWidth(tabPlacement, i, metrics);
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
// Never move a TAB down a run if it is in the first column.
// Even if there isn't enough room, moving it to a fresh
// line won't help.
if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.x = x;
}
// Initialize y position in case there's just one run
rect.y = y;
rect.height = _maxTabHeight/* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_runCount = 1;
_maxTabHeight = 0;
rect.y = y;
}
rect.height = calculateTabHeight(tabPlacement, i, metrics);
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
// Never move a TAB over a run if it is in the first run.
// Even if there isn't enough room, moving it to a fresh
// column won't help.
if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) {
if (_runCount > _tabRuns.length - 1) {
expandTabRunsArray();
}
_tabRuns[_runCount] = i;
_runCount++;
rect.y = y;
}
// Initialize x position in case there's just one column
rect.x = x;
rect.width = _maxTabWidth/* - 2 */;
}
if (i == selectedIndex) {
_selectedRun = _runCount - 1;
}
}
if (_runCount > 1) {
// Re-distribute tabs in case last run has leftover space
normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns ? y : x, returnAt);
_selectedRun = getRunForTab(tabCount, selectedIndex);
// Rotate run array so that selected run is first
if (shouldRotateTabRuns(tabPlacement)) {
rotateTabRuns(tabPlacement, _selectedRun);
}
}
// Step through runs from back to front to calculate
// tab y locations and to pad runs appropriately
for (i = _runCount - 1; i >= 0; i--) {
int start = _tabRuns[i];
int next = _tabRuns[i == (_runCount - 1) ? 0 : i + 1];
int end = (next != 0 ? next - 1 : tabCount - 1);
if (!verticalTabRuns) {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.y = y;
rect.x += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == BOTTOM) {
y -= (_maxTabHeight - tabRunOverlay);
}
else {
y += (_maxTabHeight - tabRunOverlay);
}
}
else {
for (j = start; j <= end; j++) {
rect = _rects[j];
rect.x = x;
rect.y += getTabRunIndent(tabPlacement, i);
}
if (shouldPadTabRun(tabPlacement, i)) {
padTabRun(tabPlacement, start, end, returnAt);
}
if (tabPlacement == RIGHT) {
x -= (_maxTabWidth - tabRunOverlay);
}
else {
x += (_maxTabWidth - tabRunOverlay);
}
}
}
// Pad the selected tab so that it appears raised in front
padSelectedTab(tabPlacement, selectedIndex);
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right);
for (i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width;
}
}
}
/*
* Rotates the run-index array so that the selected run is run[0]
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void rotateTabRuns(int tabPlacement, int selectedRun) {
for (int i = 0; i < selectedRun; i++) {
int save = _tabRuns[0];
for (int j = 1; j < _runCount; j++) {
_tabRuns[j - 1] = _tabRuns[j];
}
_tabRuns[_runCount - 1] = save;
}
}
protected void normalizeTabRuns(int tabPlacement, int tabCount,
int start, int max) {
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
int run = _runCount - 1;
boolean keepAdjusting = true;
double weight = 1.25;
// At this point the tab runs are packed to fit as many
// tabs as possible, which can leave the last run with a lot
// of extra space (resulting in very fat tabs on the last run).
// So we'll attempt to distribute this extra space more evenly
// across the runs in order to make the runs look more consistent.
//
// Starting with the last run, determine whether the last tab in
// the previous run would fit (generously) in this run; if so,
// move tab to current run and shift tabs accordingly. Cycle
// through remaining runs using the same algorithm.
//
while (keepAdjusting) {
int last = lastTabInRun(tabCount, run);
int prevLast = lastTabInRun(tabCount, run - 1);
int end;
int prevLastLen;
if (!verticalTabRuns) {
end = _rects[last].x + _rects[last].width;
prevLastLen = (int) (_maxTabWidth * weight);
}
else {
end = _rects[last].y + _rects[last].height;
prevLastLen = (int) (_maxTabHeight * weight * 2);
}
// Check if the run has enough extra space to fit the last tab
// from the previous row...
if (max - end > prevLastLen) {
// Insert tab from previous row and shift rest over
_tabRuns[run] = prevLast;
if (!verticalTabRuns) {
_rects[prevLast].x = start;
}
else {
_rects[prevLast].y = start;
}
for (int i = prevLast + 1; i <= last; i++) {
if (!verticalTabRuns) {
_rects[i].x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_rects[i].y = _rects[i - 1].y + _rects[i - 1].height;
}
}
}
else if (run == _runCount - 1) {
// no more room left in last run, so we're done!
keepAdjusting = false;
}
if (run - 1 > 0) {
// check previous run next...
run -= 1;
}
else {
// check last run again...but require a higher ratio
// of extraspace-to-tabsize because we don't want to
// end up with too many tabs on the last run!
run = _runCount - 1;
weight += .25;
}
}
}
protected void padTabRun(int tabPlacement, int start, int end, int max) {
Rectangle lastRect = _rects[end];
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
int runWidth = (lastRect.x + lastRect.width) - _rects[start].x;
int deltaWidth = max - (lastRect.x + lastRect.width);
float factor = (float) deltaWidth / (float) runWidth;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.x = _rects[j - 1].x + _rects[j - 1].width;
}
pastRect.width += Math.round((float) pastRect.width * factor);
}
lastRect.width = max - lastRect.x;
}
else {
int runHeight = (lastRect.y + lastRect.height) - _rects[start].y;
int deltaHeight = max - (lastRect.y + lastRect.height);
float factor = (float) deltaHeight / (float) runHeight;
for (int j = start; j <= end; j++) {
Rectangle pastRect = _rects[j];
if (j > start) {
pastRect.y = _rects[j - 1].y + _rects[j - 1].height;
}
pastRect.height += Math.round((float) pastRect.height * factor);
}
lastRect.height = max - lastRect.y;
}
}
protected void padSelectedTab(int tabPlacement, int selectedIndex) {
if (selectedIndex >= 0) {
Rectangle selRect = _rects[selectedIndex];
Insets padInsets = getSelectedTabPadInsets(tabPlacement);
selRect.x -= padInsets.left;
selRect.width += (padInsets.left + padInsets.right);
selRect.y -= padInsets.top;
selRect.height += (padInsets.top + padInsets.bottom);
}
}
}
protected TabSpaceAllocator tryTabSpacer = new TabSpaceAllocator();
protected class TabbedPaneScrollLayout extends TabbedPaneLayout {
@Override
protected int preferredTabAreaHeight(int tabPlacement, int width) {
return calculateMaxTabHeight(tabPlacement);
}
@Override
protected int preferredTabAreaWidth(int tabPlacement, int height) {
return calculateMaxTabWidth(tabPlacement);
}
@Override
public void layoutContainer(Container parent) {
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Insets insets = _tabPane.getInsets();
int selectedIndex = _tabPane.getSelectedIndex();
Component visibleComponent = getVisibleComponent();
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
JViewport viewport = null;
calculateLayoutInfo();
if (selectedIndex < 0) {
if (visibleComponent != null) {
// The last tab was removed, so remove the component
setVisibleComponent(null);
}
}
else {
Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89
boolean shouldChangeFocus = false;
// In order to allow programs to use a single component
// as the display for multiple tabs, we will not change
// the visible compnent if the currently selected tab
// has a null component. This is a bit dicey, as we don't
// explicitly state we support this in the spec, but since
// programs are now depending on this, we're making it work.
//
if (selectedComponent != null) {
if (selectedComponent != visibleComponent && visibleComponent != null) {
if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) {
shouldChangeFocus = true;
}
}
setVisibleComponent(selectedComponent);
}
int tx, ty, tw, th; // tab area bounds
int cx, cy, cw, ch; // content area bounds
Insets contentInsets = getContentBorderInsets(tabPlacement);
Rectangle bounds = _tabPane.getBounds();
int numChildren = _tabPane.getComponentCount();
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (numChildren > 0) {
switch (tabPlacement) {
case LEFT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = insets.left;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
}
}
// calculate content area bounds
cx = tx + tw + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case RIGHT:
// calculate tab area bounds
tw = calculateTabAreaHeight(TOP, _runCount,
_maxTabWidth);
th = bounds.height - insets.top - insets.bottom;
tx = bounds.width - insets.right - tw;
ty = insets.top;
if (isTabLeadingComponentVisible()) {
ty += lsize.height;
th -= lsize.height;
if (lsize.width > tw) {
tw = lsize.width;
tx = bounds.width - insets.right - tw;
}
}
if (isTabTrailingComponentVisible()) {
th -= tsize.height;
if (tsize.width > tw) {
tw = tsize.width;
tx = bounds.width - insets.right - tw;
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom;
break;
case BOTTOM:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = bounds.height - insets.bottom - th;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
ty = bounds.height - insets.bottom - th;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
ty = bounds.height - insets.bottom - th;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
break;
case TOP:
default:
// calculate tab area bounds
tw = bounds.width - insets.left - insets.right;
th = calculateTabAreaHeight(tabPlacement, _runCount,
_maxTabHeight);
tx = insets.left;
ty = insets.top;
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
tx += lsize.width;
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
if (isTabTrailingComponentVisible()) {
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
tx += tsize.width;
tw -= tsize.width;
if (tsize.height > th) {
th = tsize.height;
}
}
if (isTabLeadingComponentVisible()) {
tw -= lsize.width;
if (lsize.height > th) {
th = lsize.height;
}
}
}
// calculate content area bounds
cx = insets.left + contentInsets.left;
cy = insets.top + th + contentInsets.top;
cw = bounds.width - insets.left - insets.right
- contentInsets.left - contentInsets.right;
ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom;
}
// if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (tw < _rects[0].width + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
// else {
// if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) {
// int numberOfButtons = isShrinkTabs() ? 1 : 4;
// if (th < _rects[0].height + numberOfButtons * _buttonSize) {
// return;
// }
// }
// }
for (int i = 0; i < numChildren; i++) {
Component child = _tabPane.getComponent(i);
if (child instanceof ScrollableTabViewport) {
viewport = (JViewport) child;
// Rectangle viewRect = viewport.getViewRect();
int vw = tw;
int vh = th;
int numberOfButtons = getNumberOfTabButtons();
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (totalTabHeight > th || isShowTabButtons()) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
// if (totalTabHeight - viewRect.y <= vh) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vh = totalTabHeight - viewRect.y;
// }
}
else {
// Allow space for scrollbuttons
vh = Math.max(th - _buttonSize * numberOfButtons, 0);
}
if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) {
vh += getLayoutSize();
}
break;
case BOTTOM:
case TOP:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (isShowTabButtons() || !widthEnough) {
if (!isShowTabButtons()) numberOfButtons += 3;
// Need to allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
// if (totalTabWidth - viewRect.x <= vw) {
// // Scrolled to the end, so ensure the
// // viewport size is
// // such that the scroll offset aligns
// // with a tab
// vw = totalTabWidth - viewRect.x;
// }
}
else {
// Allow space for scrollbuttons
vw = Math.max(tw - _buttonSize * numberOfButtons, 0);
if (!leftToRight) {
tx = _buttonSize * numberOfButtons;
}
}
if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) {
vw += getLayoutSize();
if (!leftToRight) {
tx -= getLayoutSize();
}
}
break;
}
child.setBounds(tx, ty, vw, vh);
}
else if (child instanceof TabCloseButton) {
TabCloseButton scrollbutton = (TabCloseButton) child;
if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) {
Dimension bsize = scrollbutton.getPreferredSize();
int bx = 0;
int by = 0;
int bw = bsize.width;
int bh = bsize.height;
boolean visible = false;
switch (tabPlacement) {
case LEFT:
case RIGHT:
int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height;
if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) {
int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5;
break;
}
bx = tx + 2;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
by = bounds.height - insets.top - bsize.height - 5;
}
else {
visible = false;
by = 0;
}
bx = tx + 2;
}
}
if (isTabTrailingComponentVisible()) {
by = by - tsize.height;
}
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.width >= _rects[0].width) {
if (tabPlacement == LEFT) {
bx += lsize.width - _rects[0].width;
temp = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.width >= _rects[0].width
&& temp < tsize.width) {
if (tabPlacement == LEFT) {
bx += tsize.width - _rects[0].width;
}
}
}
break;
case TOP:
case BOTTOM:
default:
int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width;
boolean widthEnough = leftToRight ? totalTabWidth <= tw : _rects[tabCount - 1].x >= 0;
if (_tabPane.isTabShown() && (isShowTabButtons() || !widthEnough)) {
int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON
// NoFocusButton.WEST_BUTTON;
scrollbutton.setType(dir);
switch (dir) {
case TabCloseButton.CLOSE_BUTTON:
if (isShowCloseButton()) {
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
bx = insets.left - 5;
}
}
else {
visible = false;
bx = 0;
}
break;
case TabCloseButton.LIST_BUTTON:
visible = true;
if (leftToRight) {
bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (1 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.EAST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
case TabCloseButton.WEST_BUTTON:
visible = !isShrinkTabs();
if (leftToRight) {
bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5;
}
else {
bx = insets.left + (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width + 5;
}
break;
}
by = ((th - bsize.height) >> 1) + ty;
}
else {
int dir = scrollbutton.getType();
scrollbutton.setType(dir);
if (dir == TabCloseButton.CLOSE_BUTTON) {
if (isShowCloseButton()) {
visible = true;
bx = bounds.width - insets.left - bsize.width - 5;
}
else {
visible = false;
bx = 0;
}
by = ((th - bsize.height) >> 1) + ty;
}
}
if (isTabTrailingComponentVisible()) {
bx -= tsize.width;
}
temp = -1;
if (isTabLeadingComponentVisible()) {
if (lsize.height >= _rects[0].height) {
if (tabPlacement == TOP) {
by = ty + 2 + lsize.height - _rects[0].height;
temp = lsize.height;
}
else {
by = ty + 2;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tsize.height >= _rects[0].height
&& temp < tsize.height) {
if (tabPlacement == TOP) {
by = ty + 2 + tsize.height - _rects[0].height;
}
else {
by = ty + 2;
}
}
}
}
child.setVisible(visible);
if (visible) {
child.setBounds(bx, by, bw, bh);
}
}
else {
scrollbutton.setBounds(0, 0, 0, 0);
}
}
else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) {
if (_tabPane.isShowTabContent()) {
// All content children...
child.setBounds(cx, cy, cw, ch);
}
else {
child.setBounds(0, 0, 0, 0);
}
}
}
if (leftToRight) {
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
}
else {
if (isTabTrailingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height);
break;
case RIGHT:
_tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height);
break;
case BOTTOM:
_tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height);
break;
case TOP:
default:
_tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height);
break;
}
}
if (isTabLeadingComponentVisible()) {
switch (_tabPane.getTabPlacement()) {
case LEFT:
_tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height);
break;
case RIGHT:
_tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height);
break;
case BOTTOM:
_tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height);
break;
case TOP:
default:
_tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height);
break;
}
}
}
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
if (!leftToRight && !verticalTabRuns && viewport != null && !viewport.getSize().equals(_tabPane.getSize())) {
int offset = _tabPane.getWidth() - viewport.getWidth();
for (Rectangle rect : _rects) {
rect.x -= offset;
}
}
updateCloseButtons();
if (shouldChangeFocus) {
if (!requestFocusForVisibleComponent()) {
if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
@Override
protected void calculateTabRects(int tabPlacement, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(tabPlacement);
boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT);
boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight();
int x = tabAreaInsets.left;
int y = tabAreaInsets.top;
//
// Calculate bounds within which a tab run must fit
//
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
switch (tabPlacement) {
case LEFT:
case RIGHT:
_maxTabWidth = calculateMaxTabWidth(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < lsize.width) {
_maxTabWidth = lsize.width;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == RIGHT) {
if (_maxTabWidth < tsize.width) {
_maxTabWidth = tsize.width;
}
}
}
break;
case BOTTOM:
case TOP:
default:
_maxTabHeight = calculateMaxTabHeight(tabPlacement);
if (isTabLeadingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < lsize.height) {
_maxTabHeight = lsize.height;
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == BOTTOM) {
if (_maxTabHeight < tsize.height) {
_maxTabHeight = tsize.height;
}
}
}
}
_runCount = 0;
_selectedRun = -1;
if (tabCount == 0) {
return;
}
_selectedRun = 0;
_runCount = 1;
// Run through tabs and lay them out in a single run
Rectangle rect;
for (int i = 0; i < tabCount; i++) {
FontMetrics metrics = getFontMetrics(i);
rect = _rects[i];
if (!verticalTabRuns) {
// Tabs on TOP or BOTTOM....
if (i > 0) {
rect.x = _rects[i - 1].x + _rects[i - 1].width;
}
else {
_tabRuns[0] = 0;
_maxTabWidth = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.x = x + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.x = x;
}
}
rect.width = calculateTabWidth(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabWidth = Math.max(_maxTabWidth, rect.width);
rect.y = y;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < lsize.height) {
rect.y = y + lsize.height - _maxTabHeight - 2;
temp = lsize.height;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == TOP) {
if (_maxTabHeight < tsize.height
&& temp < tsize.height) {
rect.y = y + tsize.height - _maxTabHeight - 2;
if (_rectSizeExtend > 0) {
rect.y = rect.y + 2;
}
}
}
}
rect.height = calculateMaxTabHeight(tabPlacement);///* - 2 */;
}
else {
// Tabs on LEFT or RIGHT...
if (i > 0) {
rect.y = _rects[i - 1].y + _rects[i - 1].height;
}
else {
_tabRuns[0] = 0;
_maxTabHeight = 0;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
rect.y = y + getLeftMargin();// give the first tab arrow angle extra space
}
else {
rect.y = y;
}
}
rect.height = calculateTabHeight(tabPlacement, i, metrics) + _rectSizeExtend;
_maxTabHeight = Math.max(_maxTabHeight, rect.height);
rect.x = x;
int temp = -1;
if (isTabLeadingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < lsize.width) {
rect.x = x + lsize.width - _maxTabWidth - 2;
temp = lsize.width;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
if (isTabTrailingComponentVisible()) {
if (tabPlacement == LEFT) {
if (_maxTabWidth < tsize.width
&& temp < tsize.width) {
rect.x = x + tsize.width - _maxTabWidth - 2;
if (_rectSizeExtend > 0) {
rect.x = rect.x + 2;
}
}
}
}
rect.width = calculateMaxTabWidth(tabPlacement)/* - 2 */;
}
}
// if right to left and tab placement on the top or
// the bottom, flip x positions and adjust by widths
if (!leftToRight && !verticalTabRuns) {
int rightMargin = size.width
- (insets.right + tabAreaInsets.right) - _tabScroller.viewport.getLocation().x;
if (isTabLeadingComponentVisible()) {
rightMargin -= lsize.width;
}
int offset = 0;
if (isTabTrailingComponentVisible()) {
offset += tsize.width;
}
for (int i = 0; i < tabCount; i++) {
_rects[i].x = rightMargin - _rects[i].x - _rects[i].width - offset + tabAreaInsets.left;
// if(i == tabCount - 1) {
// _rects[i].width += getLeftMargin();
// _rects[i].x -= getLeftMargin();
// }
}
}
ensureCurrentRects(getLeftMargin(), tabCount);
}
}
protected void ensureCurrentRects(int leftMargin, int tabCount) {
Dimension size = _tabPane.getSize();
Insets insets = _tabPane.getInsets();
int totalWidth = 0;
int totalHeight = 0;
boolean verticalTabRuns = (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT);
boolean ltr = _tabPane.getComponentOrientation().isLeftToRight();
if (tabCount == 0) {
return;
}
Rectangle r = _rects[tabCount - 1];
Dimension lsize = new Dimension(0, 0);
Dimension tsize = new Dimension(0, 0);
if (isTabLeadingComponentVisible()) {
lsize = _tabLeadingComponent.getPreferredSize();
}
if (isTabTrailingComponentVisible()) {
tsize = _tabTrailingComponent.getPreferredSize();
}
if (verticalTabRuns) {
totalHeight = r.y + r.height;
if (_tabLeadingComponent != null) {
totalHeight -= lsize.height;
}
}
else {
// totalWidth = r.x + r.width;
for (Rectangle rect : _rects) {
totalWidth += rect.width;
}
if (ltr) {
totalWidth += _rects[0].x;
}
else {
totalWidth += size.width - _rects[0].x - _rects[0].width - _tabScroller.viewport.getLocation().x;
}
if (_tabLeadingComponent != null) {
totalWidth -= lsize.width;
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {// LayOut Style is Size to Fix
if (verticalTabRuns) {
int availHeight;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom - leftMargin - getTabRightPadding();// give the first tab extra space
}
else {
availHeight = (int) size.getHeight() - _fitStyleBoundSize
- insets.top - insets.bottom;
}
if (_tabPane.isShowCloseButton()) {
availHeight -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availHeight = availHeight - lsize.height;
}
if (isTabTrailingComponentVisible()) {
availHeight = availHeight - tsize.height;
}
int numberOfButtons = getNumberOfTabButtons();
availHeight -= _buttonSize * numberOfButtons;
if (totalHeight > availHeight) { // shrink is necessary
// calculate each tab width
int tabHeight = availHeight / tabCount;
totalHeight = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
_rects[k].height = tabHeight;
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
tabRect.y = totalHeight + leftMargin;// give the first tab extra space
}
else {
tabRect.y = totalHeight;
}
totalHeight += tabRect.height;
}
}
}
else {
int availWidth;
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right - leftMargin - getTabRightPadding();
}
else {
availWidth = (int) size.getWidth() - _fitStyleBoundSize
- insets.left - insets.right;
}
if (_tabPane.isShowCloseButton()) {
availWidth -= _buttonSize;
}
if (isTabLeadingComponentVisible()) {
availWidth -= lsize.width;
}
if (isTabTrailingComponentVisible()) {
availWidth -= tsize.width;
}
int numberOfButtons = getNumberOfTabButtons();
availWidth -= _buttonSize * numberOfButtons;
if (totalWidth > availWidth) { // shrink is necessary
// calculate each tab width
int tabWidth = availWidth / tabCount;
int gripperWidth = _tabPane.isShowGripper() ? _gripperWidth
: 0;
if (tabWidth < _textIconGap + _fitStyleTextMinWidth
+ _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleIconMinWidth + gripperWidth) // cannot
// hold any text but can hold an icon
tabWidth = _fitStyleIconMinWidth + gripperWidth;
if (tabWidth < _fitStyleIconMinWidth + gripperWidth
&& tabWidth > _fitStyleFirstTabMargin + gripperWidth) // cannot
// hold any icon but gripper
tabWidth = _fitStyleFirstTabMargin + gripperWidth;
tryTabSpacer.reArrange(_rects, insets, availWidth);
}
totalWidth = _fitStyleFirstTabMargin; // start
for (int k = 0; k < tabCount; k++) {
Rectangle tabRect = _rects[k];
if (getTabShape() != JideTabbedPane.SHAPE_BOX) {
if (ltr) {
tabRect.x = totalWidth + leftMargin;// give the first tab extra space when the style is not box style
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width + leftMargin;// give the first tab extra space when the style is not box style
}
}
else {
if (ltr) {
tabRect.x = totalWidth;
}
else {
tabRect.x = availWidth - totalWidth - tabRect.width;
}
}
totalWidth += tabRect.width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIXED) {// LayOut Style is Fix
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
_rects[k].height = _fixedStyleRectSize;// + _rectSizeExtend * 2;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].height += _closeButtons[k].getPreferredSize().height;
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
_rects[k].width = _fixedStyleRectSize;
if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) {
_rects[k].width += _closeButtons[k].getPreferredSize().width;
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED) {// LayOut Style is Compressed
if (verticalTabRuns) {
for (int k = 0; k < tabCount; k++) {
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab() && !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].height = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].height = icon.getIconHeight() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].height = _rects[k].height + _closeButtons[k].getPreferredSize().height + _compressedStyleCloseButtonMarginVertical;
}
}
if (k != 0) {
_rects[k].y = _rects[k - 1].y + _rects[k - 1].height;
}
totalHeight = _rects[k].y + _rects[k].height;
}
}
else {
for (int k = 0; k < tabCount; k++) {
int oldWidth = _rects[k].width;
if (k != _tabPane.getSelectedIndex()) {
if (!_tabPane.isShowIconsOnTab()
&& !_tabPane.isUseDefaultShowIconsOnTab()) {
_rects[k].width = _compressedStyleNoIconRectSize;
}
else {
Icon icon = _tabPane.getIconForTab(k);
_rects[k].width = icon.getIconWidth() + _compressedStyleIconMargin;
}
if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) {
_rects[k].width = _rects[k].width + _closeButtons[k].getPreferredSize().width + _compressedStyleCloseButtonMarginHorizon;
}
}
if (k == 0 && !ltr) {
_rects[k].x += oldWidth - _rects[k].width;
}
if (k != 0) {
if (ltr) {
_rects[k].x = _rects[k - 1].x + _rects[k - 1].width;
}
else {
_rects[k].x = _rects[k - 1].x - _rects[k - 1].width;
}
}
totalWidth = _rects[k].x + _rects[k].width;
}
}
}
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
totalWidth += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalWidth += lsize.width;
}
}
else {
totalHeight += getLayoutSize();
if (isTabLeadingComponentVisible()) {
totalHeight += tsize.height;
}
}
_tabScroller.tabPanel.setPreferredSize(new Dimension(totalWidth, totalHeight));
}
protected class ActivateTabAction extends AbstractAction {
int _tabIndex;
private static final long serialVersionUID = 3270152106579039554L;
public ActivateTabAction(String name, Icon icon, int tabIndex) {
super(name, icon);
_tabIndex = tabIndex;
}
public void actionPerformed(ActionEvent e) {
_tabPane.setSelectedIndex(_tabIndex);
}
}
protected ListCellRenderer getTabListCellRenderer() {
return _tabPane.getTabListCellRenderer();
}
public class ScrollableTabSupport implements ChangeListener {
public ScrollableTabViewport viewport;
public ScrollableTabPanel tabPanel;
public TabCloseButton scrollForwardButton;
public TabCloseButton scrollBackwardButton;
public TabCloseButton listButton;
public TabCloseButton closeButton;
public int leadingTabIndex;
private Point tabViewPosition = new Point(0, 0);
public JidePopup _popup;
@SuppressWarnings({"UnusedDeclaration"})
ScrollableTabSupport(int tabPlacement) {
viewport = new ScrollableTabViewport();
tabPanel = new ScrollableTabPanel();
viewport.setView(tabPanel);
viewport.addChangeListener(this);
scrollForwardButton = createNoFocusButton(TabCloseButton.EAST_BUTTON);
scrollForwardButton.setName(BUTTON_NAME_SCROLL_FORWARD);
scrollBackwardButton = createNoFocusButton(TabCloseButton.WEST_BUTTON);
scrollBackwardButton.setName(BUTTON_NAME_SCROLL_BACKWARD);
scrollForwardButton.setBackground(viewport.getBackground());
scrollBackwardButton.setBackground(viewport.getBackground());
listButton = createNoFocusButton(TabCloseButton.LIST_BUTTON);
listButton.setName(BUTTON_NAME_TAB_LIST);
listButton.setBackground(viewport.getBackground());
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName(BUTTON_NAME_CLOSE);
closeButton.setBackground(viewport.getBackground());
}
public void createPopupMenu(int tabPlacement) {
JPopupMenu popup = new JPopupMenu();
int totalCount = _tabPane.getTabCount();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
for (int i = 0; i < totalCount; i++) {
if (_tabPane.isEnabledAt(i)) {
JMenuItem item;
popup.add(item = new JCheckBoxMenuItem(new ActivateTabAction(_tabPane.getTitleAt(i), _tabPane.getIconForTab(i), i)));
item.setToolTipText(_tabPane.getToolTipTextAt(i));
item.setSelected(selectedIndex == i);
item.setHorizontalTextPosition(JMenuItem.RIGHT);
}
}
Dimension preferredSize = popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
switch (tabPlacement) {
case TOP:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y + bounds.height);
break;
case BOTTOM:
popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y - preferredSize.height);
break;
case LEFT:
popup.show(_tabPane, bounds.x + bounds.width, bounds.y + bounds.height - preferredSize.height);
break;
case RIGHT:
popup.show(_tabPane, bounds.x - preferredSize.width, bounds.y + bounds.height - preferredSize.height);
break;
}
}
public void createPopup(int tabPlacement) {
final JList list = new JList() {
// override this method to disallow deselect by ctrl-click
@Override
public void removeSelectionInterval(int index0, int index1) {
super.removeSelectionInterval(index0, index1);
if (getSelectedIndex() == -1) {
setSelectedIndex(index0);
}
}
@Override
public Dimension getPreferredScrollableViewportSize() {
Dimension preferredScrollableViewportSize = super.getPreferredScrollableViewportSize();
if (preferredScrollableViewportSize.width < 150) {
preferredScrollableViewportSize.width = 150;
}
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredScrollableViewportSize.width >= screenWidth) {
preferredScrollableViewportSize.width = screenWidth;
}
return preferredScrollableViewportSize;
}
@Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
int screenWidth = PortingUtils.getScreenSize(this).width;
if (preferredSize.width >= screenWidth) {
preferredSize.width = screenWidth;
}
return preferredSize;
}
};
new Sticky(list);
list.setBackground(_tabListBackground);
JScrollPane scroller = new JScrollPane(list);
scroller.setBorder(BorderFactory.createEmptyBorder());
scroller.getViewport().setOpaque(false);
scroller.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout());
panel.setBackground(_tabListBackground);
panel.setOpaque(true);
panel.add(scroller);
panel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
if (_popup != null) {
if (_popup.isPopupVisible()) {
_popup.hidePopupImmediately();
}
_popup = null;
}
_popup = com.jidesoft.popup.JidePopupFactory.getSharedInstance().createPopup();
_popup.setPopupBorder(BorderFactory.createLineBorder(_darkShadow));
_popup.add(panel);
_popup.addExcludedComponent(listButton);
_popup.setDefaultFocusComponent(list);
DefaultListModel listModel = new DefaultListModel();
// drop down menu items
int selectedIndex = _tabPane.getSelectedIndex();
int totalCount = _tabPane.getTabCount();
for (int i = 0; i < totalCount; i++) {
listModel.addElement(_tabPane);
}
list.setCellRenderer(getTabListCellRenderer());
list.setModel(listModel);
list.setSelectedIndex(selectedIndex);
list.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
componentSelected(list);
}
}
public void keyReleased(KeyEvent e) {
}
});
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
componentSelected(list);
}
});
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Insets insets = panel.getInsets();
int max = (PortingUtils.getLocalScreenSize(_tabPane).height - insets.top - insets.bottom) / list.getCellBounds(0, 0).height;
if (listModel.getSize() > max) {
list.setVisibleRowCount(max);
}
else {
list.setVisibleRowCount(listModel.getSize());
}
_popup.setOwner(_tabPane);
_popup.removeExcludedComponent(_tabPane);
Dimension size = _popup.getPreferredSize();
Rectangle bounds = listButton.getBounds();
Point p = listButton.getLocationOnScreen();
bounds.x = p.x;
bounds.y = p.y;
int x;
int y;
switch (tabPlacement) {
case TOP:
default:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y + bounds.height + 2;
break;
case BOTTOM:
if (_tabPane.getComponentOrientation().isLeftToRight()) {
x = bounds.x + bounds.width - size.width;
}
else {
x = bounds.x;
}
y = bounds.y - size.height - 2;
break;
case LEFT:
x = bounds.x + bounds.width + 2;
y = bounds.y + bounds.height - size.height;
break;
case RIGHT:
x = bounds.x - size.width - 2;
y = bounds.y + bounds.height - size.height;
break;
}
Rectangle screenBounds = PortingUtils.getScreenBounds(_tabPane);
int right = x + size.width + 3;
int bottom = y + size.height + 3;
if (right > screenBounds.x + screenBounds.width) {
x -= right - screenBounds.x - screenBounds.width; // move left so that the whole popup can fit in
}
if (x < screenBounds.x) {
x = screenBounds.x; // move right so that the whole popup can fit in
}
if (bottom > screenBounds.height) {
y -= bottom - screenBounds.height;
}
if (y < screenBounds.y) {
y = screenBounds.y;
}
_popup.showPopup(x, y);
}
private void componentSelected(JList list) {
int tabIndex = list.getSelectedIndex();
if (tabIndex != -1 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
Runnable runnable = new Runnable() {
public void run() {
_tabPane.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
Runnable runnable = new Runnable() {
public void run() {
if (lastFocused != null) {
lastFocused.requestFocus();
}
else if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocus();
}
}
};
SwingUtilities.invokeLater(runnable);
}
});
}
else {
final Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
Runnable runnable = new Runnable() {
public void run() {
lastFocused.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
else {
Container container;
if (comp instanceof Container) {
container = (Container) comp;
}
else {
container = comp.getFocusCycleRootAncestor();
}
FocusTraversalPolicy traversalPolicy = container.getFocusTraversalPolicy();
Component focusComponent;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(container);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(container);
}
}
else if (comp instanceof Container) {
// not sure if it is correct
focusComponent = findFocusableComponent((Container) comp);
}
else {
focusComponent = comp;
}
if (focusComponent != null) {
final Component theComponent = focusComponent;
Runnable runnable = new Runnable() {
public void run() {
theComponent.requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
}
}
ensureActiveTabIsVisible(false);
_popup.hidePopupImmediately();
_popup = null;
}
}
private Component findFocusableComponent(Container parent) {
FocusTraversalPolicy traversalPolicy = parent.getFocusTraversalPolicy();
Component focusComponent = null;
if (traversalPolicy != null) {
focusComponent = traversalPolicy.getDefaultComponent(parent);
if (focusComponent == null) {
focusComponent = traversalPolicy.getFirstComponent(parent);
}
}
if (focusComponent != null) {
return focusComponent;
}
int i = 0;
while (i < parent.getComponentCount()) {
Component comp = parent.getComponent(i);
if (comp instanceof Container) {
focusComponent = findFocusableComponent((Container) comp);
if (focusComponent != null) {
return focusComponent;
}
}
else if (comp.isFocusable()) {
return comp;
}
i++;
}
if (parent.isFocusable()) {
return parent;
}
return null;
}
public void scrollForward(int tabPlacement) {
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if (tabPlacement == TOP || tabPlacement == BOTTOM) {
if (viewRect.width >= viewSize.width - viewRect.x) {
return; // no room left to scroll
}
}
else { // tabPlacement == LEFT || tabPlacement == RIGHT
if (viewRect.height >= viewSize.height - viewRect.y) {
return;
}
}
setLeadingTabIndex(tabPlacement, leadingTabIndex + 1);
}
public void scrollBackward(int tabPlacement) {
setLeadingTabIndex(tabPlacement, leadingTabIndex > 0 ? leadingTabIndex - 1 : 0);
}
public void setLeadingTabIndex(int tabPlacement, int index) {
// make sure the index is in range
if (index < 0 || index >= _tabPane.getTabCount()) {
return;
}
leadingTabIndex = index;
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
switch (tabPlacement) {
case TOP:
case BOTTOM:
tabViewPosition.y = 0;
if (_tabPane.getComponentOrientation().isLeftToRight()) {
tabViewPosition.x = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].x;
}
else {
tabViewPosition.x = (_rects.length <= 0 || leadingTabIndex == 0) ? 0 : _rects[0].x - _rects[leadingTabIndex].x + (_rects[0].width - _rects[leadingTabIndex].width) + 25;
}
if ((viewSize.width - tabViewPosition.x) < viewRect.width) {
tabViewPosition.x = viewSize.width - viewRect.width;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewSize.width - tabViewPosition.x,
// viewRect.height);
// System.out.println("setExtendedSize: " + extentSize);
// viewport.setExtentSize(extentSize);
}
break;
case LEFT:
case RIGHT:
tabViewPosition.x = 0;
tabViewPosition.y = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].y;
if ((viewSize.height - tabViewPosition.y) < viewRect.height) {
tabViewPosition.y = viewSize.height - viewRect.height;
// // We've scrolled to the end, so adjust the viewport size
// // to ensure the view position remains aligned on a tab boundary
// Dimension extentSize = new Dimension(viewRect.width,
// viewSize.height - tabViewPosition.y);
// viewport.setExtentSize(extentSize);
}
break;
}
viewport.setViewPosition(tabViewPosition);
_tabPane.repaint();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight() && tabViewPosition.x == 0) {
// In current workaround, tabViewPosition set to 0 cannot trigger state change event
stateChanged(new ChangeEvent(viewport));
}
}
public void stateChanged(ChangeEvent e) {
if (_tabPane == null) return;
ensureCurrentLayout();
JViewport viewport = (JViewport) e.getSource();
int tabPlacement = _tabPane.getTabPlacement();
int tabCount = _tabPane.getTabCount();
Rectangle vpRect = viewport.getBounds();
Dimension viewSize = viewport.getViewSize();
Rectangle viewRect = viewport.getViewRect();
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
leadingTabIndex = getClosestTab(viewRect.x + viewRect.width, viewRect.y + viewRect.height);
if (leadingTabIndex < 0) {
leadingTabIndex = 0;
}
}
else {
leadingTabIndex = getClosestTab(viewRect.x, viewRect.y);
}
// If the tab isn't right aligned, adjust it.
if (leadingTabIndex < _rects.length && leadingTabIndex >= _rects.length) {
switch (tabPlacement) {
case TOP:
case BOTTOM:
if (_rects[leadingTabIndex].x < viewRect.x) {
leadingTabIndex++;
}
break;
case LEFT:
case RIGHT:
if (_rects[leadingTabIndex].y < viewRect.y) {
leadingTabIndex++;
}
break;
}
}
Insets contentInsets = getContentBorderInsets(tabPlacement);
int checkX;
switch (tabPlacement) {
case LEFT:
_tabPane.repaint(vpRect.x + vpRect.width, vpRect.y, contentInsets.left, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case RIGHT:
_tabPane.repaint(vpRect.x - contentInsets.right, vpRect.y, contentInsets.right, vpRect.height);
scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0);
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height);
break;
case BOTTOM:
_tabPane.repaint(vpRect.x, vpRect.y - contentInsets.bottom, vpRect.width, contentInsets.bottom);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
break;
case TOP:
default:
_tabPane.repaint(vpRect.x, vpRect.y + vpRect.height, vpRect.width, contentInsets.top);
scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0);
checkX = _tabPane.getComponentOrientation().isLeftToRight() ? viewRect.x : _tabScroller.viewport.getExpectedViewX();
scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - checkX > viewRect.width);
}
if (SystemInfo.isJdk15Above()) {
_tabPane.setComponentZOrder(_tabScroller.scrollForwardButton, 0);
_tabPane.setComponentZOrder(_tabScroller.scrollBackwardButton, 0);
}
_tabScroller.scrollForwardButton.repaint();
_tabScroller.scrollBackwardButton.repaint();
int selectedIndex = _tabPane.getSelectedIndex();
if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount()) {
closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex));
}
}
@Override
public String toString() {
return "viewport.viewSize=" + viewport.getViewSize() + "\n" +
"viewport.viewRectangle=" + viewport.getViewRect() + "\n" +
"leadingTabIndex=" + leadingTabIndex + "\n" +
"tabViewPosition=" + tabViewPosition;
}
}
public class ScrollableTabViewport extends JViewport implements UIResource {
int _expectViewX = 0;
boolean _protectView = false;
public ScrollableTabViewport() {
super();
setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
setOpaque(false);
setLayout(new ViewportLayout() {
private static final long serialVersionUID = -1069760662716244442L;
@Override
public void layoutContainer(Container parent) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
_protectView = true;
}
try {
super.layoutContainer(parent);
}
finally {
_protectView = false;
}
}
});
}
/**
* Gets the background color of this component.
*
* @return this component's background color; if this component does not have a background color, the background
* color of its parent is returned
*/
@Override
public Color getBackground() {
return UIDefaultsLookup.getColor("JideTabbedPane.background");
}
// workaround for swing bug
@Override
public void setViewPosition(Point p) {
int oldX = _expectViewX;
_expectViewX = p.x;
super.setViewPosition(p); // to trigger state change event, so the adjustment for RTL need to be done at ScrollableTabPanel#setBounds()
if (_protectView) {
_expectViewX = oldX;
Point savedPosition = new Point(oldX, p.y);
super.setViewPosition(savedPosition);
}
}
public int getExpectedViewX() {
return _expectViewX;
}
}
public class ScrollableTabPanel extends JPanel implements UIResource {
public ScrollableTabPanel() {
setLayout(null);
}
@Override
public boolean isOpaque() {
return false;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_tabPane.isOpaque()) {
if (getTabShape() == JideTabbedPane.SHAPE_BOX) {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"));
}
else {
g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground"));
}
g.fillRect(0, 0, getWidth(), getHeight());
}
paintTabArea(g, _tabPane.getTabPlacement(), _tabPane.getSelectedIndex(), this);
}
// workaround for swing bug
@Override
public void scrollRectToVisible(Rectangle aRect) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
int startX = aRect.x + _tabScroller.viewport.getExpectedViewX();
if (startX < 0) {
int i;
for (i = _tabScroller.leadingTabIndex; i < _rects.length; i++) {
startX += _rects[i].width;
if (startX >= 0) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.min(i + 1, _rects.length - 1));
}
else if (startX > aRect.x + aRect.width) {
int i;
for (i = _tabScroller.leadingTabIndex - 1; i >= 0; i--) {
startX -= _rects[i].width;
if (startX <= aRect.x + aRect.width) {
break;
}
}
_tabScroller.setLeadingTabIndex(_tabPane.getTabPlacement(), Math.max(i, 0));
}
return;
}
super.scrollRectToVisible(aRect);
}
// workaround for swing bug
@Override
public void setBounds(int x, int y, int width, int height) {
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
super.setBounds(0, y, width, height);
return;
}
super.setBounds(x, y, width, height);
}
// workaround for swing bug
// http://developer.java.sun.com/developer/bugParade/bugs/4668865.html
@Override
public void setToolTipText(String text) {
_tabPane.setToolTipText(text);
}
@Override
public String getToolTipText() {
return _tabPane.getToolTipText();
}
@Override
public String getToolTipText(MouseEvent event) {
return _tabPane.getToolTipText(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public Point getToolTipLocation(MouseEvent event) {
return _tabPane.getToolTipLocation(SwingUtilities.convertMouseEvent(this, event, _tabPane));
}
@Override
public JToolTip createToolTip() {
return _tabPane.createToolTip();
}
}
protected Color _closeButtonSelectedColor = new Color(255, 162, 165);
protected Color _closeButtonColor = Color.BLACK;
protected Color _popupColor = Color.BLACK;
/**
* Close button on the tab.
*/
public class TabCloseButton extends JButton implements MouseMotionListener, MouseListener, UIResource {
public static final int CLOSE_BUTTON = 0;
public static final int EAST_BUTTON = 1;
public static final int WEST_BUTTON = 2;
public static final int NORTH_BUTTON = 3;
public static final int SOUTH_BUTTON = 4;
public static final int LIST_BUTTON = 5;
private int _type;
private int _index = -1;
private boolean _mouseOver = false;
private boolean _mousePressed = false;
/**
* Resets the UI property to a value from the current look and feel.
*
* @see JComponent#updateUI
*/
@Override
public void updateUI() {
super.updateUI();
setMargin(new Insets(0, 0, 0, 0));
setBorder(BorderFactory.createEmptyBorder());
setFocusPainted(false);
setFocusable(false);
setRequestFocusEnabled(false);
String name = getName();
if (name != null) setToolTipText(getResourceString(name));
}
public TabCloseButton() {
this(CLOSE_BUTTON);
}
public TabCloseButton(int type) {
addMouseMotionListener(this);
addMouseListener(this);
setFocusPainted(false);
setFocusable(false);
setType(type);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(5, 5);
}
public int getIndex() {
return _index;
}
public void setIndex(int index) {
_index = index;
}
@Override
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
@Override
protected void paintComponent(Graphics g) {
if (!isEnabled()) {
setMouseOver(false);
setMousePressed(false);
}
if (isMouseOver() && isMousePressed()) {
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
else if (isMouseOver()) {
g.setColor(UIDefaultsLookup.getColor("control"));
g.drawLine(0, 0, getWidth() - 1, 0);
g.drawLine(0, getHeight() - 2, 0, 1);
g.setColor(UIDefaultsLookup.getColor("controlDkShadow"));
g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2);
g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1);
}
g.setColor(UIDefaultsLookup.getColor("controlShadow").darker());
int centerX = getWidth() >> 1;
int centerY = getHeight() >> 1;
int type = getType();
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
if (type == EAST_BUTTON) {
type = WEST_BUTTON;
}
else if (type == WEST_BUTTON) {
type = EAST_BUTTON;
}
}
switch (type) {
case CLOSE_BUTTON:
if (isEnabled()) {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX - 4, centerY - 3, centerX + 2, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
g.drawLine(centerX + 2, centerY - 3, centerX - 4, centerY + 3);
}
else {
g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3);
g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3);
}
break;
case EAST_BUTTON:
//
// |
// ||
// |||
// ||||
// ||||*
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX + 2, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 3, y - 3, x - 3, y + 3);
g.drawLine(x - 2, y - 2, x - 2, y + 2);
g.drawLine(x - 1, y - 1, x - 1, y + 1);
g.drawLine(x, y, x, y);
}
else {
g.drawLine(x - 4, y - 4, x, y);
g.drawLine(x - 4, y - 4, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
else {
int x = centerX + 3, y = centerY - 2; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 7, y + 1, x - 1, y + 1);
g.drawLine(x - 6, y + 2, x - 2, y + 2);
g.drawLine(x - 5, y + 3, x - 3, y + 3);
g.drawLine(x - 4, y + 4, x - 4, y + 4);
}
else {
g.drawLine(x - 8, y, x, y);
g.drawLine(x - 8, y, x - 4, y + 4);
g.drawLine(x - 4, y + 4, x, y);
}
}
}
break;
case WEST_BUTTON: {
//
// |
// ||
// |||
// ||||
// *||||
// ||||
// |||
// ||
// |
//
{
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
int x = centerX - 3, y = centerY; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x, y);
g.drawLine(x + 1, y - 1, x + 1, y + 1);
g.drawLine(x + 2, y - 2, x + 2, y + 2);
g.drawLine(x + 3, y - 3, x + 3, y + 3);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
else {
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x, y, x + 4, y + 4);
g.drawLine(x + 4, y - 4, x + 4, y + 4);
}
}
else {
int x = centerX - 5, y = centerY + 3; // start point. mark as * above
if (isEnabled()) {
g.drawLine(x, y, x + 8, y);
g.drawLine(x + 1, y - 1, x + 7, y - 1);
g.drawLine(x + 2, y - 2, x + 6, y - 2);
g.drawLine(x + 3, y - 3, x + 5, y - 3);
g.drawLine(x + 4, y - 4, x + 4, y - 4);
}
else {
g.drawLine(x, y, x + 8, y);
g.drawLine(x, y, x + 4, y - 4);
g.drawLine(x + 8, y, x + 4, y - 4);
}
}
}
break;
}
case LIST_BUTTON: {
int x = centerX + 2, y = centerY; // start point. mark as
// * above
g.drawLine(x - 6, y - 4, x - 6, y + 4);
g.drawLine(x + 1, y - 4, x + 1, y + 4);
g.drawLine(x - 6, y - 4, x + 1, y - 4);
g.drawLine(x - 4, y - 2, x - 1, y - 2);
g.drawLine(x - 4, y, x - 1, y);
g.drawLine(x - 4, y + 2, x - 1, y + 2);
g.drawLine(x - 6, y + 4, x + 1, y + 4);
break;
}
}
}
@Override
public boolean isFocusable() {
return false;
}
@Override
public void requestFocus() {
}
@Override
public boolean isOpaque() {
return false;
}
public boolean scrollsForward() {
return getType() == EAST_BUTTON || getType() == SOUTH_BUTTON;
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseClicked(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
setMousePressed(false);
}
public void mousePressed(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(true);
repaint();
}
public void mouseReleased(MouseEvent e) {
if (!isEnabled()) return;
setMousePressed(false);
setMouseOver(false);
}
public void mouseEntered(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(true);
repaint();
}
public void mouseExited(MouseEvent e) {
if (!isEnabled()) return;
setMouseOver(false);
setMousePressed(false);
repaint();
_tabScroller.tabPanel.repaint();
}
public int getType() {
return _type;
}
public void setType(int type) {
_type = type;
}
public boolean isMouseOver() {
return _mouseOver;
}
public void setMouseOver(boolean mouseOver) {
_mouseOver = mouseOver;
}
public boolean isMousePressed() {
return _mousePressed;
}
public void setMousePressed(boolean mousePressed) {
_mousePressed = mousePressed;
}
}
// Controller: event listeners
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class PropertyChangeHandler implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
JTabbedPane pane = (JTabbedPane) e.getSource();
String name = e.getPropertyName();
if ("mnemonicAt".equals(name)) {
updateMnemonics();
pane.repaint();
}
else if ("displayedMnemonicIndexAt".equals(name)) {
pane.repaint();
}
else if (name.equals("indexForTitle")) {
int index = (Integer) e.getNewValue();
String title = getCurrentDisplayTitleAt(_tabPane, index);
if (BasicHTML.isHTMLString(title)) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(_tabPane, title);
htmlViews.setElementAt(v, index);
}
}
else {
if (htmlViews != null && htmlViews.elementAt(index) != null) {
htmlViews.setElementAt(null, index);
}
}
updateMnemonics();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(
_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(false);
}
}
else if (name.equals("tabLayoutPolicy")) {
_tabPane.updateUI();
}
else if (name.equals("closeTabAction")) {
updateCloseAction();
}
else if (name.equals(JideTabbedPane.PROPERTY_DRAG_OVER_DISABLED)) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_COLOR_PROVIDER)) {
_tabPane.repaint();
}
else if (name.equals("locale")) {
_tabPane.updateUI();
}
else if (name.equals(JideTabbedPane.BOLDACTIVETAB_PROPERTY)) {
getTabPanel().invalidate();
_tabPane.invalidate();
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_LEADING_COMPONENT)) {
ensureCurrentLayout();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(false);
_tabPane.remove(_tabLeadingComponent);
}
_tabLeadingComponent = (Component) e.getNewValue();
if (_tabLeadingComponent != null) {
_tabLeadingComponent.setVisible(true);
_tabPane.add(_tabLeadingComponent);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.PROPERTY_TAB_TRAILING_COMPONENT)) {
ensureCurrentLayout();
if (_tabTrailingComponent != null) {
_tabTrailingComponent.setVisible(false);
_tabPane.remove(_tabTrailingComponent);
}
_tabTrailingComponent = (Component) e.getNewValue();
if (_tabTrailingComponent != null) {
_tabPane.add(_tabTrailingComponent);
_tabTrailingComponent.setVisible(true);
}
_tabScroller.tabPanel.updateUI();
}
else if (name.equals(JideTabbedPane.SHRINK_TAB_PROPERTY) ||
name.equals(JideTabbedPane.HIDE_IF_ONE_TAB_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_AREA_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_TAB_CONTENT_PROPERTY) ||
name.equals(JideTabbedPane.BOX_STYLE_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_ICONS_PROPERTY) ||
name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) ||
name.equals(JideTabbedPane.TAB_CLOSABLE_PROPERTY) ||
name.equals(JideTabbedPane.PROPERTY_TAB_SHAPE) ||
name.equals(JideTabbedPane.PROPERTY_COLOR_THEME) ||
name.equals(JideTabbedPane.PROPERTY_TAB_RESIZE_MODE) ||
name.equals(JideTabbedPane.SHOW_TAB_BUTTONS_PROPERTY)) {
if ((name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY))
&& isShowCloseButton() && isShowCloseButtonOnTab()) {
ensureCloseButtonCreated();
}
_tabPane.updateUI();
}
else if (name.equals("__index_to_remove__")) {
setVisibleComponent(null);
}
}
}
protected void updateCloseAction() {
ensureCloseButtonCreated();
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class TabSelectionHandler implements ChangeListener {
public void stateChanged(ChangeEvent e) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//pane.stopTabEditing();
ensureCloseButtonCreated();
Runnable runnable = new Runnable() {
public void run() {
ensureActiveTabIsVisible(false);
}
};
SwingUtilities.invokeLater(runnable);
}
}
public class TabFocusListener implements FocusListener {
public void focusGained(FocusEvent e) {
repaintSelectedTab();
}
public void focusLost(FocusEvent e) {
repaintSelectedTab();
}
private void repaintSelectedTab() {
if (_tabPane.getTabCount() > 0) {
Rectangle rect = getTabBounds(_tabPane, _tabPane.getSelectedIndex());
if (rect != null) {
_tabPane.repaint(rect);
}
}
}
}
public class MouseMotionHandler extends MouseMotionAdapter {
}
/**
* This inner class is marked "public" due to a compiler bug. This class should be treated as a
* "protected" inner class. Instantiate it only within subclasses of VsnetJideTabbedPaneUI.
*/
public class MouseHandler extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isMiddleMouseButton(e)) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
Action action = getActionMap().get("closeTabAction");
if (action != null && tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex) && _tabPane.isCloseTabOnMouseMiddleButton() && _tabPane.isTabClosableAt(tabIndex)) {
ActionEvent event = new ActionEvent(_tabPane, tabIndex, "middleMouseButtonClicked");
action.actionPerformed(event);
}
}
}
@Override
public void mousePressed(MouseEvent e) {
if (_tabPane == null || !_tabPane.isEnabled()) {
return;
}
if (SwingUtilities.isLeftMouseButton(e) || _tabPane.isRightClickSelect()) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) {
if (_tabPane.isAutoFocusOnTabHideClose() && _tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
else {
_tabPane.setSelectedIndex(tabIndex);
_tabPane.processMouseSelection(tabIndex, e);
final Component comp = _tabPane.getComponentAt(tabIndex);
if (_tabPane.isAutoFocusOnTabHideClose() && !comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) {
comp.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
// remove the listener
comp.removeComponentListener(this);
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else if (_tabPane.isRequestFocusEnabled()) {
// if (!_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
// }
}
}
});
}
else {
Component lastFocused = _tabPane.getLastFocusedComponent(comp);
if (lastFocused != null) {
// this code works in JDK6 but on JDK5
// if (!lastFocused.requestFocusInWindow()) {
lastFocused.requestFocus();
// }
}
else {
// first try to find a default component.
boolean foundInTab = JideSwingUtilities.compositeRequestFocus(comp);
if (!foundInTab) { // && !_tabPane.requestFocusInWindow()) {
_tabPane.requestFocus();
}
}
}
}
}
}
if (!isTabEditing())
startEditing(e); // start editing tab
}
}
public class MouseWheelHandler implements MouseWheelListener {
public void mouseWheelMoved(MouseWheelEvent e) {
if (_tabPane.isScrollSelectedTabOnWheel()) {
// set selected tab to the currently selected tab plus the wheel rotation but between
// 0 and tabCount-1
_tabPane.setSelectedIndex(
Math.min(_tabPane.getTabCount() - 1, Math.max(0, _tabPane.getSelectedIndex() + e.getWheelRotation())));
}
else if (scrollableTabLayoutEnabled() && e.getWheelRotation() != 0) {
if (e.getWheelRotation() > 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollForward(_tabPane.getTabPlacement());
}
}
else if (e.getWheelRotation() < 0) {
for (int i = 0; i < e.getScrollAmount(); i++) {
_tabScroller.scrollBackward(_tabPane.getTabPlacement());
}
}
}
}
}
private class ComponentHandler implements ComponentListener {
public void componentResized(ComponentEvent e) {
if (scrollableTabLayoutEnabled() && (_tabPane.getTabPlacement() == EAST || _tabPane.getTabPlacement() == WEST || _tabPane.getComponentOrientation().isLeftToRight())) {
_tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height));
ensureActiveTabIsVisible(true);
}
}
public void componentMoved(ComponentEvent e) {
}
public void componentShown(ComponentEvent e) {
}
public void componentHidden(ComponentEvent e) {
}
}
/* GES 2/3/99:
The container listener code was added to support HTML
rendering of tab titles.
Ideally, we would be able to listen for property changes
when a tab is added or its text modified. At the moment
there are no such events because the Beans spec doesn't
allow 'indexed' property changes (i.e. tab 2's text changed
from A to B).
In order to get around this, we listen for tabs to be added
or removed by listening for the container events. we then
queue up a runnable (so the component has a chance to complete
the add) which checks the tab title of the new component to see
if it requires HTML rendering.
The Views (one per tab title requiring HTML rendering) are
stored in the htmlViews Vector, which is only allocated after
the first time we run into an HTML tab. Note that this vector
is kept in step with the number of pages, and nulls are added
for those pages whose tab title do not require HTML rendering.
This makes it easy for the paint and layout code to tell
whether to invoke the HTML engine without having to check
the string during time-sensitive operations.
When we have added a way to listen for tab additions and
changes to tab text, this code should be removed and
replaced by something which uses that. */
private class ContainerHandler implements ContainerListener {
public void componentAdded(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
int index = tp.indexOfComponent(child);
String title = getCurrentDisplayTitleAt(tp, index);
boolean isHTML = BasicHTML.isHTMLString(title);
if (isHTML) {
if (htmlViews == null) { // Initialize vector
htmlViews = createHTMLVector();
}
else { // Vector already exists
View v = BasicHTML.createHTMLView(tp, title);
htmlViews.insertElementAt(v, index);
}
}
else { // Not HTML
if (htmlViews != null) { // Add placeholder
htmlViews.insertElementAt(null, index);
} // else nada!
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
}
public void componentRemoved(ContainerEvent e) {
JideTabbedPane tp = (JideTabbedPane) e.getContainer();
// updateTabPanel();
Component child = e.getChild();
if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) {
return;
}
// NOTE 4/15/2002 (joutwate):
// This fix is implemented using client properties since there is
// currently no IndexPropertyChangeEvent. Once
// IndexPropertyChangeEvents have been added this code should be
// modified to use it.
Integer index =
(Integer) tp.getClientProperty("__index_to_remove__");
if (index != null) {
if (htmlViews != null && htmlViews.size() > index) {
htmlViews.removeElementAt(index);
}
tp.putClientProperty("__index_to_remove__", null);
}
if (_tabPane.isTabEditing()) {
((BasicJideTabbedPaneUI) _tabPane.getUI()).stopOrCancelEditing();//_tabPane.stopTabEditing();
}
ensureCloseButtonCreated();
// ensureActiveTabIsVisible(true);
}
}
private Vector createHTMLVector() {
Vector htmlViews = new Vector();
int count = _tabPane.getTabCount();
if (count > 0) {
for (int i = 0; i < count; i++) {
String title = getCurrentDisplayTitleAt(_tabPane, i);
if (BasicHTML.isHTMLString(title)) {
htmlViews.addElement(BasicHTML.createHTMLView(_tabPane, title));
}
else {
htmlViews.addElement(null);
}
}
}
return htmlViews;
}
@Override
public Component getTabPanel() {
if (scrollableTabLayoutEnabled())
return _tabScroller.tabPanel;
else
return _tabPane;
}
static class AbstractTab {
int width;
int id;
public void copy(AbstractTab tab) {
this.width = tab.width;
this.id = tab.id;
}
}
public static class TabSpaceAllocator {
static final int startOffset = 4;
private Insets insets = null;
static final int tabWidth = 24;
static final int textIconGap = 8;
private AbstractTab tabs[];
private void setInsets(Insets insets) {
this.insets = (Insets) insets.clone();
}
private void init(Rectangle rects[], Insets insets) {
setInsets(insets);
tabs = new AbstractTab[rects.length];
// fill up internal datastructure
for (int i = 0; i < rects.length; i++) {
tabs[i] = new AbstractTab();
tabs[i].id = i;
tabs[i].width = rects[i].width;
}
tabSort();
}
private void bestfit(AbstractTab tabs[], int freeWidth, int startTab) {
int tabCount = tabs.length;
int worstWidth;
int currentTabWidth;
int initialPos;
currentTabWidth = tabs[startTab].width;
initialPos = startTab;
if (startTab == tabCount - 1) {
// directly fill as worst case
tabs[startTab].width = freeWidth;
return;
}
worstWidth = freeWidth / (tabCount - startTab);
while (currentTabWidth < worstWidth) {
freeWidth -= currentTabWidth;
if (++startTab < tabCount - 1) {
currentTabWidth = tabs[startTab].width;
}
else {
tabs[startTab].width = worstWidth;
return;
}
}
if (startTab == initialPos) {
// didn't find anything smaller
for (int i = startTab; i < tabCount; i++) {
tabs[i].width = worstWidth;
}
}
else if (startTab < tabCount - 1) {
bestfit(tabs, freeWidth, startTab);
}
}
// bubble sort for now
private void tabSort() {
int tabCount = tabs.length;
AbstractTab tempTab = new AbstractTab();
for (int i = 0; i < tabCount - 1; i++) {
for (int j = i + 1; j < tabCount; j++) {
if (tabs[i].width > tabs[j].width) {
tempTab.copy(tabs[j]);
tabs[j].copy(tabs[i]);
tabs[i].copy(tempTab);
}
}
}
}
// directly modify the rects
private void outpush(Rectangle rects[]) {
for (AbstractTab tab : tabs) {
rects[tab.id].width = tab.width;
}
rects[0].x = startOffset;
for (int i = 1; i < rects.length; i++) {
rects[i].x = rects[i - 1].x + rects[i - 1].width;
}
}
public void reArrange(Rectangle rects[], Insets insets, int totalAvailableSpace) {
init(rects, insets);
bestfit(tabs, totalAvailableSpace, 0);
outpush(rects);
clearup();
}
private void clearup() {
for (int i = 0; i < tabs.length; i++) {
tabs[i] = null;
}
tabs = null;
}
}
@Override
public void ensureActiveTabIsVisible(boolean scrollLeft) {
if (_tabPane == null || _tabPane.getWidth() == 0) {
return;
}
if (scrollableTabLayoutEnabled()) {
ensureCurrentLayout();
if (scrollLeft && _rects.length > 0) {
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
_tabScroller.tabPanel.scrollRectToVisible(_rects[0]);
}
else {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
}
int index = _tabPane.getSelectedIndex();
if ((!scrollLeft || index != 0) && index < _rects.length && index != -1) {
if (index == 0) {
_tabScroller.viewport.setViewPosition(new Point(0, 0));
}
else {
if (index == _rects.length - 1) { // last one, scroll to the end
Rectangle lastRect = _rects[index];
if ((_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) && _tabPane.getComponentOrientation().isLeftToRight()) {
lastRect.width = _tabScroller.tabPanel.getWidth() - lastRect.x;
}
_tabScroller.tabPanel.scrollRectToVisible(lastRect);
}
else {
_tabScroller.tabPanel.scrollRectToVisible(_rects[index]);
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabScroller.tabPanel.getParent().doLayout();
}
}
if (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT || _tabPane.getComponentOrientation().isLeftToRight()) {
_tabPane.revalidate();
_tabPane.repaintTabAreaAndContentBorder();
}
else {
_tabPane.repaint();
}
}
}
protected boolean isShowCloseButtonOnTab() {
if (_tabPane.isUseDefaultShowCloseButtonOnTab()) {
return _showCloseButtonOnTab;
}
else return _tabPane.isShowCloseButtonOnTab();
}
protected boolean isShowCloseButton() {
return _tabPane.isShowCloseButton();
}
public void ensureCloseButtonCreated() {
if (isShowCloseButton() && isShowCloseButtonOnTab() && scrollableTabLayoutEnabled()) {
if (_closeButtons == null) {
_closeButtons = new TabCloseButton[_tabPane.getTabCount()];
}
else if (_closeButtons.length > _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0, temp.length);
for (int i = temp.length; i < _closeButtons.length; i++) {
TabCloseButton tabCloseButton = _closeButtons[i];
_tabScroller.tabPanel.remove(tabCloseButton);
}
_closeButtons = temp;
}
else if (_closeButtons.length < _tabPane.getTabCount()) {
TabCloseButton[] temp = new TabCloseButton[_tabPane
.getTabCount()];
System.arraycopy(_closeButtons, 0, temp, 0,
_closeButtons.length);
_closeButtons = temp;
}
ActionMap am = getActionMap();
for (int i = 0; i < _closeButtons.length; i++) {
TabCloseButton closeButton = _closeButtons[i];
if (closeButton == null) {
closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON);
closeButton.setName("JideTabbedPane.close");
_closeButtons[i] = closeButton;
closeButton.setBounds(0, 0, 0, 0);
Action action = _tabPane.getCloseAction();
closeButton.setAction(am.get("closeTabAction"));
updateButtonFromAction(closeButton, action);
_tabScroller.tabPanel.add(closeButton);
}
closeButton.setIndex(i);
}
}
}
private void updateButtonFromAction(TabCloseButton closeButton, Action action) {
if (action == null) {
return;
}
closeButton.setEnabled(action.isEnabled());
Object desc = action.getValue(Action.SHORT_DESCRIPTION);
if (desc instanceof String) {
closeButton.setToolTipText((String) desc);
}
Object icon = action.getValue(Action.SMALL_ICON);
if (icon instanceof Icon) {
closeButton.setIcon((Icon) icon);
}
}
protected boolean isShowTabButtons() {
return _tabPane.getTabCount() != 0 && _tabPane.isShowTabArea() && _tabPane.isShowTabButtons();
}
protected boolean isShrinkTabs() {
return _tabPane.getTabCount() != 0 && _tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT;
}
protected TabEditor _tabEditor;
protected boolean _isEditing;
protected int _editingTab = -1;
protected String _oldValue;
protected String _oldPrefix;
protected String _oldPostfix;
// mtf - changed
protected Component _originalFocusComponent;
@Override
public boolean isTabEditing() {
return _isEditing;
}
protected TabEditor createDefaultTabEditor() {
final TabEditor editor = new TabEditor();
editor.getDocument().addDocumentListener(this);
editor.setInputVerifier(new InputVerifier() {
@Override
public boolean verify(JComponent input) {
return true;
}
public boolean shouldYieldFocus(JComponent input) {
boolean shouldStopEditing = true;
if (_tabPane != null && _tabPane.isTabEditing() && _tabPane.getTabEditingValidator() != null) {
shouldStopEditing = _tabPane.getTabEditingValidator().alertIfInvalid(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
if (shouldStopEditing && _tabPane != null && _tabPane.isTabEditing()) {
_tabPane.stopTabEditing();
}
return shouldStopEditing;
}
});
editor.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
_originalFocusComponent = e.getOppositeComponent();
}
@Override
public void focusLost(FocusEvent e) {
}
});
editor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editor.transferFocus();
}
});
editor.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (_isEditing && (e.getKeyCode() == KeyEvent.VK_ESCAPE)) {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldValue);
}
_tabPane.cancelTabEditing();
}
}
});
editor.setFont(_tabPane.getFont());
return editor;
}
@Override
public void stopTabEditing() {
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
_tabPane.setTitleAt(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix);
}
cancelTabEditing();
}
@Override
public void cancelTabEditing() {
if (_tabEditor != null) {
_isEditing = false;
((Container) getTabPanel()).remove(_tabEditor);
if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) {
Rectangle tabRect = _tabPane.getBoundsAt(_editingTab);
getTabPanel().repaint(tabRect.x, tabRect.y,
tabRect.width, tabRect.height);
}
else {
getTabPanel().repaint();
}
if (_originalFocusComponent != null)
_originalFocusComponent.requestFocus(); // InWindow();
else
_tabPane.requestFocusForVisibleComponent();
_editingTab = -1;
_oldValue = null;
_tabPane.doLayout();
}
}
@Override
public boolean editTabAt(int tabIndex) {
if (_isEditing) {
return false;
}
// _tabPane.popupSelectedIndex(tabIndex);
if (_tabEditor == null)
_tabEditor = createDefaultTabEditor();
if (_tabEditor != null) {
prepareEditor(_tabEditor, tabIndex);
((Container) getTabPanel()).add(_tabEditor);
resizeEditor(tabIndex);
_editingTab = tabIndex;
_isEditing = true;
_tabEditor.requestFocusInWindow();
_tabEditor.selectAll();
return true;
}
return false;
}
@Override
public int getEditingTabIndex() {
return _editingTab;
}
protected void prepareEditor(TabEditor e, int tabIndex) {
Font font;
if (_tabPane.getSelectedTabFont() != null) {
font = _tabPane.getSelectedTabFont();
}
else {
font = _tabPane.getFont();
}
if (_tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) {
font = font.deriveFont(Font.BOLD);
}
e.setFont(font);
_oldValue = _tabPane.getTitleAt(tabIndex);
if (_oldValue.startsWith("<HTML>") && _oldValue.endsWith("/HTML>")) {
_oldPrefix = "<HTML>";
_oldPostfix = "</HTML>";
String title = _oldValue.substring("<HTML>".length(), _oldValue.length() - "</HTML>".length());
if (title.startsWith("<B>") && title.endsWith("/B>")) {
title = title.substring("<B>".length(), title.length() - "</B>".length());
_oldPrefix += "<B>";
_oldPostfix = "</B>" + _oldPostfix;
}
e.setText(title);
}
else {
_oldPrefix = "";
_oldPostfix = "";
e.setText(_oldValue);
}
e.selectAll();
e.setForeground(_tabPane.getForegroundAt(tabIndex));
}
protected Rectangle getTabsTextBoundsAt(int tabIndex) {
Rectangle tabRect = _tabPane.getBoundsAt(tabIndex);
Rectangle iconRect = new Rectangle(),
textRect = new Rectangle();
if (tabRect.width < 200) // random max size;
tabRect.width = 200;
String title = getCurrentDisplayTitleAt(_tabPane, tabIndex);
while (title == null || title.length() < 3)
title += " ";
Icon icon = _tabPane.getIconForTab(tabIndex);
Font font = _tabPane.getFont();
if (tabIndex == _tabPane.getSelectedIndex() && _tabPane.isBoldActiveTab()) {
font = font.deriveFont(Font.BOLD);
}
SwingUtilities.layoutCompoundLabel(_tabPane, _tabPane.getGraphics().getFontMetrics(font), title, icon,
SwingUtilities.CENTER, SwingUtilities.CENTER,
SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect,
iconRect, textRect, icon == null ? 0 : _textIconGap);
if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) {
iconRect.x = tabRect.x + _iconMargin;
textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding);
textRect.width += 2;
}
else {
iconRect.y = tabRect.y + _iconMargin;
textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding);
iconRect.x = tabRect.x + 2;
textRect.x = tabRect.x + 2;
textRect.height += 2;
}
return textRect;
}
private void updateTab() {
if (_isEditing) {
resizeEditor(getEditingTabIndex());
}
}
public void insertUpdate(DocumentEvent e) {
updateTab();
}
public void removeUpdate(DocumentEvent e) {
updateTab();
}
public void changedUpdate(DocumentEvent e) {
updateTab();
}
protected void resizeEditor(int tabIndex) {
// note - this should use the logic of label paint text so that the text overlays exactly.
Rectangle tabsTextBoundsAt = getTabsTextBoundsAt(tabIndex);
if (tabsTextBoundsAt.isEmpty()) {
tabsTextBoundsAt = new Rectangle(14, 3); // note - 14 should be the font height but...
}
tabsTextBoundsAt.x = tabsTextBoundsAt.x - _tabEditor.getBorder().getBorderInsets(_tabEditor).left;
tabsTextBoundsAt.width = +tabsTextBoundsAt.width +
_tabEditor.getBorder().getBorderInsets(_tabEditor).left +
_tabEditor.getBorder().getBorderInsets(_tabEditor).right;
tabsTextBoundsAt.y = tabsTextBoundsAt.y - _tabEditor.getBorder().getBorderInsets(_tabEditor).top;
tabsTextBoundsAt.height = tabsTextBoundsAt.height +
_tabEditor.getBorder().getBorderInsets(_tabEditor).top +
_tabEditor.getBorder().getBorderInsets(_tabEditor).bottom;
_tabEditor.setBounds(SwingUtilities.convertRectangle(_tabPane, tabsTextBoundsAt, getTabPanel()));
_tabEditor.invalidate();
_tabEditor.validate();
// getTabPanel().invalidate();
// getTabPanel().validate();
// getTabPanel().repaint();
// getTabPanel().doLayout();
_tabPane.doLayout();
// mtf - note - this is an exteme repaint but we need to paint any content borders
getTabPanel().getParent().getParent().repaint();
}
protected String getCurrentDisplayTitleAt(JideTabbedPane tp, int index) {
String returnTitle = tp.getDisplayTitleAt(index);
if ((_isEditing) && (index == _editingTab))
returnTitle = _tabEditor.getText();
return returnTitle;
}
protected class TabEditor extends JTextField implements UIResource {
TabEditor() {
setOpaque(false);
// setBorder(BorderFactory.createEmptyBorder());
setBorder(BorderFactory
.createCompoundBorder(new PartialLineBorder(Color.BLACK, 1, true),
BorderFactory.createEmptyBorder(0, 2, 0, 2)));
}
public boolean stopEditing() {
return true;
}
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Composite orgComposite = g2.getComposite();
Color orgColor = g2.getColor();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.70f));
Object o = JideSwingUtilities.setupShapeAntialiasing(g);
g2.setColor(getBackground());
g.fillRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 1, 1);
JideSwingUtilities.restoreShapeAntialiasing(g, o);
g2.setColor(orgColor);
g2.setComposite(orgComposite);
super.paintComponent(g);
}
}
public void startEditing(MouseEvent e) {
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (!e.isPopupTrigger() && tabIndex >= 0
&& _tabPane.isEnabledAt(tabIndex)
&& _tabPane.isTabEditingAllowed() && (e.getClickCount() == 2)) {
boolean shouldEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldEdit = _tabPane.getTabEditingValidator().shouldStartEdit(tabIndex, e);
if (shouldEdit) {
e.consume();
_tabPane.editTabAt(tabIndex);
}
}
if (e.getClickCount() == 1) {
if (_tabPane.isTabEditing()) {
boolean shouldStopEdit = true;
if (_tabPane.getTabEditingValidator() != null)
shouldStopEdit = _tabPane.getTabEditingValidator().alertIfInvalid(tabIndex, _oldPrefix + _tabEditor.getText() + _oldPostfix);
if (shouldStopEdit)
_tabPane.stopTabEditing();
}
}
}
public ThemePainter getPainter() {
return _painter;
}
private class DragOverTimer extends Timer implements ActionListener {
private int _index;
private static final long serialVersionUID = -2529347876574638854L;
public DragOverTimer(int index) {
super(500, null);
_index = index;
addActionListener(this);
setRepeats(false);
}
public void actionPerformed(ActionEvent e) {
if (_tabPane.getTabCount() == 0) {
return;
}
if (_index == _tabPane.getSelectedIndex()) {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
_tabPane.repaint(getTabBounds(_tabPane, _index));
}
}
else {
if (_tabPane.isRequestFocusEnabled()) {
_tabPane.requestFocusInWindow();
}
_tabPane.setSelectedIndex(_index);
}
stop();
}
}
private class DropListener implements DropTargetListener {
private DragOverTimer _timer;
int _index = -1;
public DropListener() {
}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
if (!_tabPane.isEnabled()) {
return;
}
int tabIndex = getTabAtLocation(dtde.getLocation().x, dtde.getLocation().y);
if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) {
if (tabIndex == _tabPane.getSelectedIndex()) {
// selected already, do nothing
}
else if (tabIndex == _index) {
// same tab, timer has started
}
else {
stopTimer();
startTimer(tabIndex);
_index = tabIndex; // save the index
}
}
else {
stopTimer();
}
dtde.rejectDrag();
}
private void startTimer(int tabIndex) {
_timer = new DragOverTimer(tabIndex);
_timer.start();
}
private void stopTimer() {
if (_timer != null) {
_timer.stop();
_timer = null;
_index = -1;
}
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dte) {
stopTimer();
}
public void drop(DropTargetDropEvent dtde) {
stopTimer();
}
}
protected void paintFocusIndicator(Graphics g, int tabPlacement,
Rectangle[] rects, int tabIndex,
Rectangle iconRect, Rectangle textRect,
boolean isSelected) {
Rectangle tabRect = new Rectangle(rects[tabIndex]);
if ((tabPlacement == TOP || tabPlacement == BOTTOM) && !_tabPane.getComponentOrientation().isLeftToRight()) {
tabRect.x += _tabScroller.viewport.getExpectedViewX();
}
if (_tabPane.hasFocus() && isSelected) {
int x, y, w, h;
g.setColor(_focus);
switch (tabPlacement) {
case LEFT:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case RIGHT:
x = tabRect.x + 2;
y = tabRect.y + 3;
w = tabRect.width - 5;
h = tabRect.height - 6 - getTabGap();
break;
case BOTTOM:
x = tabRect.x + 3;
y = tabRect.y + 2;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
break;
case TOP:
default:
x = tabRect.x + 3;
y = tabRect.y + 3;
w = tabRect.width - 6 - getTabGap();
h = tabRect.height - 5;
}
BasicGraphicsUtils.drawDashedRect(g, x, y, w, h);
}
}
protected boolean isRoundedCorner() {
return "true".equals(SecurityUtils.getProperty("shadingtheme", "false"));
}
protected int getTabShape() {
return _tabPane.getTabShape();
}
protected int getTabResizeMode() {
return _tabPane.getTabResizeMode();
}
protected int getColorTheme() {
return _tabPane.getColorTheme();
}
// for debug purpose
final protected boolean PAINT_TAB = true;
final protected boolean PAINT_TAB_BORDER = true;
final protected boolean PAINT_TAB_BACKGROUND = true;
final protected boolean PAINT_TABAREA = true;
final protected boolean PAINT_CONTENT_BORDER = true;
final protected boolean PAINT_CONTENT_BORDER_EDGE = true;
protected int getLeftMargin() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return OFFICE2003_LEFT_MARGIN;
}
else if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else {
return DEFAULT_LEFT_MARGIN;
}
}
protected int getTabGap() {
if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) {
return 4;
}
else {
return 0;
}
}
protected int getLayoutSize() {
int tabShape = getTabShape();
if (tabShape == JideTabbedPane.SHAPE_EXCEL) {
return EXCEL_LEFT_MARGIN;
}
else if (tabShape == JideTabbedPane.SHAPE_ECLIPSE3X) {
return 15;
}
else if (_tabPane.getTabShape() == JideTabbedPane.SHAPE_FLAT || _tabPane.getTabShape() == JideTabbedPane.SHAPE_ROUNDED_FLAT) {
return 2;
}
else if (tabShape == JideTabbedPane.SHAPE_WINDOWS
|| tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return 6;
}
else {
return 0;
}
}
protected int getTabRightPadding() {
if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) {
return 4;
}
else {
return 0;
}
}
protected MouseListener createMouseListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseHandler();
}
else {
return new MouseHandler();
}
}
protected MouseWheelListener createMouseWheelListener() {
return new MouseWheelHandler();
}
protected MouseMotionListener createMouseMotionListener() {
if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) {
return new RolloverMouseMotionHandler();
}
else {
return new MouseMotionHandler();
}
}
public class DefaultMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class DefaultMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
}
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = getTabAtLocation(e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
public class RolloverMouseMotionHandler extends MouseMotionAdapter {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
if (tabIndex != _indexMouseOver) {
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
}
}
public class RolloverMouseHandler extends BasicJideTabbedPaneUI.MouseHandler {
@Override
public void mouseEntered(MouseEvent e) {
super.mouseEntered(e);
int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY());
_mouseEnter = true;
_indexMouseOver = tabIndex;
_tabPane.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
_indexMouseOver = -1;
_mouseEnter = false;
_tabPane.repaint();
}
}
protected boolean isTabLeadingComponentVisible() {
return _tabPane.isTabShown() && _tabLeadingComponent != null && _tabLeadingComponent.isVisible();
}
protected boolean isTabTrailingComponentVisible() {
return _tabPane.isTabShown() && _tabTrailingComponent != null && _tabTrailingComponent.isVisible();
}
protected boolean isTabTopVisible(int tabPlacement) {
switch (tabPlacement) {
case LEFT:
case RIGHT:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement));
case TOP:
case BOTTOM:
default:
return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement)) ||
(isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement));
}
}
protected boolean showFocusIndicator() {
return _tabPane.hasFocusComponent() && _showFocusIndicator;
}
private int getNumberOfTabButtons() {
int numberOfButtons = (!isShowTabButtons() || isShrinkTabs()) ? 1 : 4;
if (!isShowCloseButton() || isShowCloseButtonOnTab()) {
numberOfButtons--;
}
return numberOfButtons;
}
/**
* Gets the resource string used in DocumentPane. Subclass can override it to provide their own strings.
*
* @param key the resource key
* @return the localized string.
*/
protected String getResourceString(String key) {
return Resource.getResourceBundle(_tabPane != null ? _tabPane.getLocale() : Locale.getDefault()).getString(key);
}
}
|
diff --git a/ripple-client/src/main/java/com/ripple/client/transactions/TransactionManager.java b/ripple-client/src/main/java/com/ripple/client/transactions/TransactionManager.java
index 9ee5a85..f19ced2 100644
--- a/ripple-client/src/main/java/com/ripple/client/transactions/TransactionManager.java
+++ b/ripple-client/src/main/java/com/ripple/client/transactions/TransactionManager.java
@@ -1,482 +1,479 @@
package com.ripple.client.transactions;
import com.ripple.client.Client;
import com.ripple.client.enums.Command;
import com.ripple.client.pubsub.CallbackContext;
import com.ripple.client.pubsub.Publisher;
import com.ripple.client.requests.Request;
import com.ripple.client.responses.Response;
import com.ripple.client.subscriptions.AccountRoot;
import com.ripple.client.subscriptions.ServerInfo;
import com.ripple.core.enums.TransactionEngineResult;
import com.ripple.core.enums.TransactionType;
import com.ripple.core.coretypes.AccountID;
import com.ripple.core.coretypes.Amount;
import com.ripple.core.coretypes.hash.Hash256;
import com.ripple.core.coretypes.uint.UInt32;
import com.ripple.crypto.ecdsa.IKeyPair;
import java.util.*;
public class TransactionManager extends Publisher<TransactionManager.events> {
public static abstract class events<T> extends Publisher.Callback<T> {}
// This event is emitted with the Sequence of the AccountRoot
public static abstract class OnValidatedSequence extends events<UInt32> {}
Client client;
AccountRoot accountRoot;
AccountID accountID;
IKeyPair keyPair;
AccountTransactionsRequester txnRequester;
private ArrayList<ManagedTxn> pending = new ArrayList<ManagedTxn>();
public TransactionManager(Client client, final AccountRoot accountRoot, AccountID accountID, IKeyPair keyPair) {
this.client = client;
this.accountRoot = accountRoot;
this.accountID = accountID;
this.keyPair = keyPair;
// We'd be subscribed yeah ;)
this.client.on(Client.OnLedgerClosed.class, new Client.OnLedgerClosed() {
@Override
public void called(ServerInfo serverInfo) {
checkAccountTransactions(serverInfo.ledger_index);
if (!canSubmit() || getPending().isEmpty()) {
return;
}
ArrayList<ManagedTxn> sorted = pendingSequenceSorted();
ManagedTxn first = sorted.get(0);
Submission previous = first.lastSubmission();
if (previous != null) {
long ledgersClosed = serverInfo.ledger_index - previous.ledgerSequence;
if (ledgersClosed > 5) {
resubmitWithSameSequence(first);
}
}
}
});
}
Set<Long> seenValidatedSequences = new TreeSet<Long>();
public long sequence = 0;
private UInt32 locallyPreemptedSubmissionSequence() {
if (!accountRoot.primed()) {
throw new IllegalStateException("The AccountRoot hasn't been populated from the server");
}
long server = accountRoot.Sequence.longValue();
if (server > sequence) {
sequence = server;
}
return new UInt32(sequence++);
}
private boolean txnNotFinalizedAndSeenValidatedSequence(ManagedTxn txn) {
return !txn.isFinalized() &&
seenValidatedSequences.contains(txn.sequence().longValue());
}
public void queue(final ManagedTxn tx) {
if (accountRoot.primed()) {
queue(tx, locallyPreemptedSubmissionSequence());
} else {
accountRoot.once(AccountRoot.OnUpdate.class, new AccountRoot.OnUpdate() {
@Override
public void called(AccountRoot accountRoot) {
queue(tx, locallyPreemptedSubmissionSequence());
}
});
}
}
// TODO: data structure that keeps txns in sequence sorted order
public ArrayList<ManagedTxn> getPending() {
return pending;
}
public ArrayList<ManagedTxn> pendingSequenceSorted() {
ArrayList<ManagedTxn> queued = new ArrayList<ManagedTxn>(getPending());
Collections.sort(queued, new Comparator<ManagedTxn>() {
@Override
public int compare(ManagedTxn lhs, ManagedTxn rhs) {
return lhs.sequence().compareTo(rhs.sequence());
}
});
return queued;
}
public int txnsPending() {
return getPending().size();
}
// TODO, maybe this is an instance configurable strategy parameter
public static long LEDGERS_BETWEEN_ACCOUNT_TX = 15;
public static long ACCOUNT_TX_TIMEOUT = 5;
private long lastTxnRequesterUpdate = 0;
private long lastLedgerCheckedAccountTxns = 0;
AccountTransactionsRequester.OnPage onTxnsPage = new AccountTransactionsRequester.OnPage() {
@Override
public void onPage(AccountTransactionsRequester.Page page) {
lastTxnRequesterUpdate = client.serverInfo.ledger_index;
if (page.hasNext()) {
page.requestNext();
} else {
lastLedgerCheckedAccountTxns = Math.max(lastLedgerCheckedAccountTxns, page.ledgerMax());
txnRequester = null;
}
for (TransactionResult tr : page.transactionResults()) {
if (tr.initiatingAccount().equals(accountID)) {
notifyTransactionResult(tr);
}
}
}
};
private void checkAccountTransactions(int currentLedgerIndex) {
if (pending.size() == 0) {
lastLedgerCheckedAccountTxns = 0;
return;
}
long ledgersPassed = currentLedgerIndex - lastLedgerCheckedAccountTxns;
if ((lastLedgerCheckedAccountTxns == 0 || ledgersPassed >= LEDGERS_BETWEEN_ACCOUNT_TX)) {
if (lastLedgerCheckedAccountTxns == 0) {
lastLedgerCheckedAccountTxns = currentLedgerIndex;
for (ManagedTxn txn : pending) {
for (Submission submission : txn.submissions) {
lastLedgerCheckedAccountTxns = Math.min(lastLedgerCheckedAccountTxns, submission.ledgerSequence);
}
}
return; // and wait for next ledger close
}
if (txnRequester != null) {
if ((currentLedgerIndex - lastTxnRequesterUpdate) >= ACCOUNT_TX_TIMEOUT) {
txnRequester.abort(); // no more OnPage
txnRequester = null; // and wait for next ledger close
}
// else keep waiting ;)
} else {
lastTxnRequesterUpdate = currentLedgerIndex;
txnRequester = new AccountTransactionsRequester(client,
accountID,
onTxnsPage,
/* for good measure */
lastLedgerCheckedAccountTxns - 5);
// Very important VVVVV
txnRequester.setForward(true);
txnRequester.request();
}
}
}
private void queue(final ManagedTxn txn, final UInt32 sequence) {
getPending().add(txn);
makeSubmitRequest(txn, sequence);
}
public boolean canSubmit() {
return client.connected &&
client.serverInfo.primed() &&
client.serverInfo.load_factor < 768 &&
accountRoot.primed();
}
private void makeSubmitRequest(final ManagedTxn txn, final UInt32 sequence) {
if (canSubmit()) {
doSubmitRequest(txn, sequence);
}
else {
// If we have submitted again, before this gets to execute
// we should just bail out early, and not submit again.
final int n = txn.submissions.size();
client.on(Client.OnStateChange.class, new CallbackContext() {
@Override
public boolean shouldExecute() {
return canSubmit() && !shouldRemove();
}
@Override
public boolean shouldRemove() {
// The next state change should cause this to remove
return txn.isFinalized() || n != txn.submissions.size();
}
}, new Client.OnStateChange() {
@Override
public void called(Client client) {
doSubmitRequest(txn, sequence);
}
});
}
}
private Request doSubmitRequest(final ManagedTxn txn, UInt32 sequence) {
// Compute the fee for the current load_factor
Amount fee = client.serverInfo.transactionFee(txn);
// Inside prepare we check if Fee and Sequence are the same, and if so
// we don't recreate tx_blob, or resign ;)
long currentLedgerIndex = client.serverInfo.ledger_index;
UInt32 lastLedgerSequence = new UInt32(currentLedgerIndex + 8);
Submission submission = txn.lastSubmission();
if (submission != null) {
if (currentLedgerIndex - submission.lastLedgerSequence.longValue() < 8) {
lastLedgerSequence = submission.lastLedgerSequence;
}
}
txn.prepare(keyPair, fee, sequence, lastLedgerSequence);
final Request req = client.newRequest(Command.submit);
// tx_blob is a hex string, right o' the bat
req.json("tx_blob", txn.tx_blob);
req.once(Request.OnSuccess.class, new Request.OnSuccess() {
@Override
public void called(Response response) {
handleSubmitSuccess(txn, response);
}
});
req.once(Request.OnError.class, new Request.OnError() {
@Override
public void called(Response response) {
handleSubmitError(txn, response);
}
});
// Keep track of the submission, including the hash submitted
// to the network, and the ledger_index at that point in time.
txn.trackSubmitRequest(req, client.serverInfo);
req.request();
return req;
}
public void handleSubmitError(ManagedTxn txn, Response res) {
if (txn.finalizedOrResponseIsToPriorSubmission(res)) {
return;
}
switch (res.rpcerr) {
case noNetwork:
resubmitWithSameSequence(txn);
break;
default:
// TODO, what other cases should this retry?
// TODO, what if this actually eventually clears?
// TOOD, need to use LastLedgerSequence
finalizeTxnAndRemoveFromQueue(txn);
txn.publisher().emit(ManagedTxn.OnSubmitError.class, res);
break;
}
}
/**
* We handle various transaction engine results specifically
* and then by class of result.
*/
public void handleSubmitSuccess(final ManagedTxn txn, final Response res) {
if (txn.finalizedOrResponseIsToPriorSubmission(res)) {
return;
}
TransactionEngineResult ter = res.engineResult();
final UInt32 submitSequence = res.getSubmitSequence();
switch (ter) {
case tesSUCCESS:
txn.publisher().emit(ManagedTxn.OnSubmitSuccess.class, res);
return;
case tefPAST_SEQ:
resubmitWithNewSequence(txn);
break;
case tefMAX_LEDGER:
resubmit(txn, submitSequence);
break;
case terPRE_SEQ:
on(OnValidatedSequence.class, new OnValidatedSequence() {
@Override
public void called(UInt32 sequence) {
if (txn.finalizedOrResponseIsToPriorSubmission(res)) {
removeListener(OnValidatedSequence.class, this);
} else {
if (sequence.equals(submitSequence)) {
// resubmit:
resubmit(txn, submitSequence);
removeListener(OnValidatedSequence.class, this);
}
}
}
});
break;
case telINSUF_FEE_P:
resubmit(txn, submitSequence);
break;
case tefALREADY:
// We only get this if we are submitting with exact same transactionID
// Do nothing, the transaction has already been submitted
break;
default:
switch (ter.resultClass()) {
case tecCLAIMED:
// Sequence was consumed, do nothing
finalizeTxnAndRemoveFromQueue(txn);
txn.publisher().emit(ManagedTxn.OnSubmitFailure.class, res);
break;
// These are, according to the wiki, all of a final disposition
case temMALFORMED:
case tefFAILURE:
- finalizeTxnAndRemoveFromQueue(txn);
- txn.publisher().emit(ManagedTxn.OnSubmitFailure.class, res);
- break;
// TODO: Handle these with more panache
case telLOCAL_ERROR:
case terRETRY:
// TODO: txn.setAbortedAwaitingFinal();
finalizeTxnAndRemoveFromQueue(txn);
if (getPending().isEmpty()) {
sequence--;
} else {
// Plug a Sequence gap and preemptively resubmit some txns
// rather than waiting for `OnValidatedSequence` which will take
// quite some ledgers.
queueSequencePlugTxn(submitSequence);
resubmitGreaterThan(submitSequence);
}
txn.publisher().emit(ManagedTxn.OnSubmitFailure.class, res);
break;
}
break;
}
}
private void resubmitGreaterThan(UInt32 submitSequence) {
for (ManagedTxn txn : getPending()) {
if (txn.sequence().compareTo(submitSequence) == 1) {
resubmitWithSameSequence(txn);
}
}
}
private void queueSequencePlugTxn(UInt32 sequence) {
ManagedTxn plug = transaction(TransactionType.AccountSet);
plug.setSequencePlug(true);
queue(plug, sequence);
}
public void finalizeTxnAndRemoveFromQueue(ManagedTxn transaction) {
transaction.setFinalized();
getPending().remove(transaction);
}
private void resubmitFirstTransactionWithTakenSequence(UInt32 sequence) {
for (ManagedTxn txn : getPending()) {
if (txn.sequence().compareTo(sequence) == 0) {
resubmitWithNewSequence(txn);
break;
}
}
}
// We only EVER resubmit a txn with a new Sequence if we have actually
// seen that the Sequence has been consumed by a transaction we didn't
// submit ourselves.
// This is the method that handles that,
private void resubmitWithNewSequence(final ManagedTxn txn) {
// A sequence plug's sole purpose is to plug a Sequence
// so that transactions may clear.
if (txn.isSequencePlug()) {
// The sequence has already been plugged (somehow)
// So:
return; // without further ado.
}
// ONLY ONLY ONLY if we've actually seen the Sequence
if (txnNotFinalizedAndSeenValidatedSequence(txn)) {
resubmit(txn, locallyPreemptedSubmissionSequence());
} else {
// requesting account_tx now and then (as we do) should ensure that
// this doesn't stall forever. We'll either finalize the transaction
// or Sequence will be seen to have been consumed by another txn.
on(OnValidatedSequence.class,
new CallbackContext() {
@Override
public boolean shouldExecute() {
return !txn.isFinalized();
}
@Override
public boolean shouldRemove() {
return txn.isFinalized();
}
},
new OnValidatedSequence() {
@Override
public void called(UInt32 uInt32) {
// Again, just to be safe.
if (txnNotFinalizedAndSeenValidatedSequence(txn)) {
resubmit(txn, locallyPreemptedSubmissionSequence());
}
}
});
}
}
private void resubmit(ManagedTxn txn, UInt32 sequence) {
if (txn.abortedAwaitingFinal()) {
return;
}
makeSubmitRequest(txn, sequence);
}
private void resubmitWithSameSequence(ManagedTxn txn) {
UInt32 previouslySubmitted = txn.sequence();
resubmit(txn, previouslySubmitted);
}
public ManagedTxn payment() {
return transaction(TransactionType.Payment);
}
public ManagedTxn transaction(TransactionType tt) {
ManagedTxn txn = new ManagedTxn(tt);
txn.put(AccountID.Account, accountID);
return txn;
}
public void notifyTransactionResult(TransactionResult tr) {
if (!tr.validated || !(tr.initiatingAccount().equals(accountID))) {
return;
}
UInt32 txnSequence = tr.transaction.get(UInt32.Sequence);
seenValidatedSequences.add(txnSequence.longValue());
ManagedTxn txn = submittedTransactionForHash(tr.hash);
if (txn != null) {
// TODO: icky
// A result doesn't have a ManagedTxn
// a ManagedTxn has a result
tr.submittedTransaction = txn;
finalizeTxnAndRemoveFromQueue(txn);
txn.publisher().emit(ManagedTxn.OnTransactionValidated.class, tr);
} else {
// preempt the terPRE_SEQ
resubmitFirstTransactionWithTakenSequence(txnSequence);
// Some transactions are waiting on this event before resubmission
emit(OnValidatedSequence.class, txnSequence.add(new UInt32(1)));
}
}
private ManagedTxn submittedTransactionForHash(Hash256 hash) {
for (ManagedTxn transaction : getPending()) {
if (transaction.wasSubmittedWith(hash)) {
return transaction;
}
}
return null;
}
}
| true | true | public void handleSubmitSuccess(final ManagedTxn txn, final Response res) {
if (txn.finalizedOrResponseIsToPriorSubmission(res)) {
return;
}
TransactionEngineResult ter = res.engineResult();
final UInt32 submitSequence = res.getSubmitSequence();
switch (ter) {
case tesSUCCESS:
txn.publisher().emit(ManagedTxn.OnSubmitSuccess.class, res);
return;
case tefPAST_SEQ:
resubmitWithNewSequence(txn);
break;
case tefMAX_LEDGER:
resubmit(txn, submitSequence);
break;
case terPRE_SEQ:
on(OnValidatedSequence.class, new OnValidatedSequence() {
@Override
public void called(UInt32 sequence) {
if (txn.finalizedOrResponseIsToPriorSubmission(res)) {
removeListener(OnValidatedSequence.class, this);
} else {
if (sequence.equals(submitSequence)) {
// resubmit:
resubmit(txn, submitSequence);
removeListener(OnValidatedSequence.class, this);
}
}
}
});
break;
case telINSUF_FEE_P:
resubmit(txn, submitSequence);
break;
case tefALREADY:
// We only get this if we are submitting with exact same transactionID
// Do nothing, the transaction has already been submitted
break;
default:
switch (ter.resultClass()) {
case tecCLAIMED:
// Sequence was consumed, do nothing
finalizeTxnAndRemoveFromQueue(txn);
txn.publisher().emit(ManagedTxn.OnSubmitFailure.class, res);
break;
// These are, according to the wiki, all of a final disposition
case temMALFORMED:
case tefFAILURE:
finalizeTxnAndRemoveFromQueue(txn);
txn.publisher().emit(ManagedTxn.OnSubmitFailure.class, res);
break;
// TODO: Handle these with more panache
case telLOCAL_ERROR:
case terRETRY:
// TODO: txn.setAbortedAwaitingFinal();
finalizeTxnAndRemoveFromQueue(txn);
if (getPending().isEmpty()) {
sequence--;
} else {
// Plug a Sequence gap and preemptively resubmit some txns
// rather than waiting for `OnValidatedSequence` which will take
// quite some ledgers.
queueSequencePlugTxn(submitSequence);
resubmitGreaterThan(submitSequence);
}
txn.publisher().emit(ManagedTxn.OnSubmitFailure.class, res);
break;
}
break;
}
}
| public void handleSubmitSuccess(final ManagedTxn txn, final Response res) {
if (txn.finalizedOrResponseIsToPriorSubmission(res)) {
return;
}
TransactionEngineResult ter = res.engineResult();
final UInt32 submitSequence = res.getSubmitSequence();
switch (ter) {
case tesSUCCESS:
txn.publisher().emit(ManagedTxn.OnSubmitSuccess.class, res);
return;
case tefPAST_SEQ:
resubmitWithNewSequence(txn);
break;
case tefMAX_LEDGER:
resubmit(txn, submitSequence);
break;
case terPRE_SEQ:
on(OnValidatedSequence.class, new OnValidatedSequence() {
@Override
public void called(UInt32 sequence) {
if (txn.finalizedOrResponseIsToPriorSubmission(res)) {
removeListener(OnValidatedSequence.class, this);
} else {
if (sequence.equals(submitSequence)) {
// resubmit:
resubmit(txn, submitSequence);
removeListener(OnValidatedSequence.class, this);
}
}
}
});
break;
case telINSUF_FEE_P:
resubmit(txn, submitSequence);
break;
case tefALREADY:
// We only get this if we are submitting with exact same transactionID
// Do nothing, the transaction has already been submitted
break;
default:
switch (ter.resultClass()) {
case tecCLAIMED:
// Sequence was consumed, do nothing
finalizeTxnAndRemoveFromQueue(txn);
txn.publisher().emit(ManagedTxn.OnSubmitFailure.class, res);
break;
// These are, according to the wiki, all of a final disposition
case temMALFORMED:
case tefFAILURE:
// TODO: Handle these with more panache
case telLOCAL_ERROR:
case terRETRY:
// TODO: txn.setAbortedAwaitingFinal();
finalizeTxnAndRemoveFromQueue(txn);
if (getPending().isEmpty()) {
sequence--;
} else {
// Plug a Sequence gap and preemptively resubmit some txns
// rather than waiting for `OnValidatedSequence` which will take
// quite some ledgers.
queueSequencePlugTxn(submitSequence);
resubmitGreaterThan(submitSequence);
}
txn.publisher().emit(ManagedTxn.OnSubmitFailure.class, res);
break;
}
break;
}
}
|
diff --git a/src/com/agodwin/hideseek/Events.java b/src/com/agodwin/hideseek/Events.java
index 9a58d6e..0f0390c 100644
--- a/src/com/agodwin/hideseek/Events.java
+++ b/src/com/agodwin/hideseek/Events.java
@@ -1,60 +1,63 @@
package com.agodwin.hideseek;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.metadata.FixedMetadataValue;
public class Events implements Listener {
@EventHandler
public void onBreak(BlockBreakEvent e) {
if (Main.inArena.containsKey(e.getPlayer().getName())) {
e.setCancelled(true);
}
}
@EventHandler
public void onPlace(BlockPlaceEvent e) {
if (Main.inArena.containsKey(e.getPlayer().getName())) {
e.setCancelled(true);
}
}
@EventHandler
public void onHit(EntityDamageByEntityEvent e) {
if (e.getDamager().hasMetadata("team")
&& e.getEntity().hasMetadata("team")
&& e.getDamager().getMetadata("team").get(0).asString()
.equals("seeker")
&& e.getDamager() instanceof Player
&& !e.getEntity().getMetadata("team").get(0).asString()
.equals("seeker") && e.getEntity() instanceof Player) {
// switch that team motha fucka
Player killed = (Player) e.getEntity();
killed.setHealth(0);
}
}
@EventHandler
public void playerRespawnEvent(PlayerRespawnEvent e) {
+ if (!Main.inArena.containsKey(e.getPlayer().getName())) {
+ return;
+ }
// set respawn,
// change death message
// set new meta
Main m = new Main();
e.setRespawnLocation(m.loc(e.getPlayer()));
if (e.getPlayer().hasMetadata("team")
&& !e.getPlayer().getMetadata("team").get(0).asString()
.equals("seeker")) {
Bukkit.broadcastMessage(ChatColor.BLUE + e.getPlayer().getName()
+ ChatColor.RED + " is now a seeker! Watch out!");
e.getPlayer().setMetadata("team",
new FixedMetadataValue(Main.getPlugin(), "seeker"));
}
}
}
| true | true | public void playerRespawnEvent(PlayerRespawnEvent e) {
// set respawn,
// change death message
// set new meta
Main m = new Main();
e.setRespawnLocation(m.loc(e.getPlayer()));
if (e.getPlayer().hasMetadata("team")
&& !e.getPlayer().getMetadata("team").get(0).asString()
.equals("seeker")) {
Bukkit.broadcastMessage(ChatColor.BLUE + e.getPlayer().getName()
+ ChatColor.RED + " is now a seeker! Watch out!");
e.getPlayer().setMetadata("team",
new FixedMetadataValue(Main.getPlugin(), "seeker"));
}
}
| public void playerRespawnEvent(PlayerRespawnEvent e) {
if (!Main.inArena.containsKey(e.getPlayer().getName())) {
return;
}
// set respawn,
// change death message
// set new meta
Main m = new Main();
e.setRespawnLocation(m.loc(e.getPlayer()));
if (e.getPlayer().hasMetadata("team")
&& !e.getPlayer().getMetadata("team").get(0).asString()
.equals("seeker")) {
Bukkit.broadcastMessage(ChatColor.BLUE + e.getPlayer().getName()
+ ChatColor.RED + " is now a seeker! Watch out!");
e.getPlayer().setMetadata("team",
new FixedMetadataValue(Main.getPlugin(), "seeker"));
}
}
|
diff --git a/src/com/android/mms/transaction/MmsSystemEventReceiver.java b/src/com/android/mms/transaction/MmsSystemEventReceiver.java
index e152b3a7..92511338 100644
--- a/src/com/android/mms/transaction/MmsSystemEventReceiver.java
+++ b/src/com/android/mms/transaction/MmsSystemEventReceiver.java
@@ -1,102 +1,105 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-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.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.util.Log;
import com.android.mms.LogTag;
import com.android.mms.MmsApp;
/**
* MmsSystemEventReceiver receives the
* {@link android.content.intent.ACTION_BOOT_COMPLETED},
* {@link com.android.internal.telephony.TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED}
* and performs a series of operations which may include:
* <ul>
* <li>Show/hide the icon in notification area which is used to indicate
* whether there is new incoming message.</li>
* <li>Resend the MM's in the outbox.</li>
* </ul>
*/
public class MmsSystemEventReceiver extends BroadcastReceiver {
private static final String TAG = "MmsSystemEventReceiver";
private static ConnectivityManager mConnMgr = null;
public static void wakeUpService(Context context) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "wakeUpService: start transaction service ...");
}
context.startService(new Intent(context, TransactionService.class));
}
@Override
public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (!mConnMgr.getMobileDataEnabled()) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "mobile data turned off, bailing");
}
return;
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
- boolean available = mmsNetworkInfo.isAvailable();
- boolean isConnected = mmsNetworkInfo.isConnected();
+ if (mmsNetworkInfo!=null)
+ {
+ boolean available = mmsNetworkInfo.isAvailable();
+ boolean isConnected = mmsNetworkInfo.isConnected();
- if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
- Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
+ if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
+ Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
- }
+ }
- // Wake up transact service when MMS data is available and isn't connected.
- if (available && !isConnected) {
- wakeUpService(context);
+ // Wake up transact service when MMS data is available and isn't connected.
+ if (available && !isConnected) {
+ wakeUpService(context);
+ }
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
}
| false | true | public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (!mConnMgr.getMobileDataEnabled()) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "mobile data turned off, bailing");
}
return;
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
| public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
if (!mConnMgr.getMobileDataEnabled()) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "mobile data turned off, bailing");
}
return;
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
if (mmsNetworkInfo!=null)
{
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
|
diff --git a/zorka-central-web/src/main/java/com/jitlogic/zorka/central/client/portal/WelcomePanel.java b/zorka-central-web/src/main/java/com/jitlogic/zorka/central/client/portal/WelcomePanel.java
index 9563240c..d2b9c17f 100644
--- a/zorka-central-web/src/main/java/com/jitlogic/zorka/central/client/portal/WelcomePanel.java
+++ b/zorka-central-web/src/main/java/com/jitlogic/zorka/central/client/portal/WelcomePanel.java
@@ -1,152 +1,152 @@
/**
* Copyright 2012-2013 Rafal Lewczuk <[email protected]>
* <p/>
* This 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.
* <p/>
* 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 General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jitlogic.zorka.central.client.portal;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.*;
import com.google.inject.Inject;
import com.jitlogic.zorka.central.client.Resources;
import com.jitlogic.zorka.central.client.ZorkaCentralShell;
import com.jitlogic.zorka.central.client.api.AdminApi;
import com.jitlogic.zorka.central.client.api.SystemApi;
import com.jitlogic.zorka.central.client.panels.PanelFactory;
import com.jitlogic.zorka.central.client.panels.TraceTemplatePanel;
import com.sencha.gxt.widget.core.client.Portlet;
import com.sencha.gxt.widget.core.client.button.ToolButton;
import com.sencha.gxt.widget.core.client.container.PortalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import org.fusesource.restygwt.client.Method;
import org.fusesource.restygwt.client.MethodCallback;
import javax.inject.Provider;
import java.util.Map;
public class WelcomePanel implements IsWidget {
private PortalLayoutContainer portal;
private AdminApi adminApi;
private Provider<ZorkaCentralShell> shell;
private SystemInfoPortlet systemInfoPortlet;
private PanelFactory panelFactory;
@Inject
public WelcomePanel(AdminApi adminApi, SystemInfoPortlet systemInfoPortlet,
PanelFactory panelFactory, Provider<ZorkaCentralShell> shell) {
this.adminApi = adminApi;
this.systemInfoPortlet = systemInfoPortlet;
this.panelFactory = panelFactory;
this.shell = shell;
}
@Override
public Widget asWidget() {
if (portal == null) {
createPortal();
}
return portal;
}
private void createPortal() {
portal = new PortalLayoutContainer(3);
portal.getElement().getStyle().setBackgroundColor("white");
portal.setColumnWidth(0, .50);
portal.setColumnWidth(1, .25);
portal.setColumnWidth(2, .25);
createHelpPortlet();
- Portlet wndTopHosts = newPortlet("Top Hosts", false);
- wndTopHosts.add(new HTML("TBD"));
- portal.add(wndTopHosts, 1);
+ //Portlet wndTopHosts = newPortlet("Top Hosts", false);
+ //wndTopHosts.add(new HTML("TBD"));
+ //portal.add(wndTopHosts, 1);
- Portlet wndTopOffenders = newPortlet("Top Offenders", false);
- wndTopOffenders.add(new HTML("TBD"));
- portal.add(wndTopOffenders, 1);
+ //Portlet wndTopOffenders = newPortlet("Top Offenders", false);
+ //wndTopOffenders.add(new HTML("TBD"));
+ //portal.add(wndTopOffenders, 1);
portal.add(systemInfoPortlet, 2);
createAdminPortlet();
}
private void createHelpPortlet() {
Portlet wndHelp = newPortlet("Welcome", true);
HTML htmlHelp = new HTML(Resources.INSTANCE.tipsHtml().getText());
VerticalLayoutContainer vp = new VerticalLayoutContainer();
vp.add(htmlHelp);
wndHelp.add(vp);
portal.add(wndHelp, 0);
}
private void createAdminPortlet() {
Portlet wndAdmin = newPortlet("Admin tasks", false);
VerticalLayoutContainer vp = new VerticalLayoutContainer();
Hyperlink lnkTraceDisplayTemplates = new Hyperlink("Trace List Display Templates", "");
vp.add(lnkTraceDisplayTemplates);
lnkTraceDisplayTemplates.addHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
openTemplatePanel();
}
}, ClickEvent.getType());
//Hyperlink lnkUsersAccess = new Hyperlink("Users & Access Privileges", "");
//vp.add(lnkUsersAccess);
wndAdmin.add(vp);
portal.add(wndAdmin, 2);
}
private void openTemplatePanel() {
adminApi.getTidMap(new MethodCallback<Map<String, String>>() {
@Override
public void onFailure(Method method, Throwable exception) {
GWT.log("Error calling method " + method, exception);
}
@Override
public void onSuccess(Method method, Map<String, String> response) {
shell.get().addView(panelFactory.traceTemplatePanel(response), "Templates");
}
});
}
private Portlet newPortlet(String title, boolean closeable) {
final Portlet portlet = new Portlet();
portlet.setHeadingText(title);
portlet.setCollapsible(true);
if (closeable) {
portlet.getHeader().addTool(new ToolButton(ToolButton.CLOSE, new SelectEvent.SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
portlet.removeFromParent();
}
}));
}
return portlet;
}
}
| false | true | private void createPortal() {
portal = new PortalLayoutContainer(3);
portal.getElement().getStyle().setBackgroundColor("white");
portal.setColumnWidth(0, .50);
portal.setColumnWidth(1, .25);
portal.setColumnWidth(2, .25);
createHelpPortlet();
Portlet wndTopHosts = newPortlet("Top Hosts", false);
wndTopHosts.add(new HTML("TBD"));
portal.add(wndTopHosts, 1);
Portlet wndTopOffenders = newPortlet("Top Offenders", false);
wndTopOffenders.add(new HTML("TBD"));
portal.add(wndTopOffenders, 1);
portal.add(systemInfoPortlet, 2);
createAdminPortlet();
}
| private void createPortal() {
portal = new PortalLayoutContainer(3);
portal.getElement().getStyle().setBackgroundColor("white");
portal.setColumnWidth(0, .50);
portal.setColumnWidth(1, .25);
portal.setColumnWidth(2, .25);
createHelpPortlet();
//Portlet wndTopHosts = newPortlet("Top Hosts", false);
//wndTopHosts.add(new HTML("TBD"));
//portal.add(wndTopHosts, 1);
//Portlet wndTopOffenders = newPortlet("Top Offenders", false);
//wndTopOffenders.add(new HTML("TBD"));
//portal.add(wndTopOffenders, 1);
portal.add(systemInfoPortlet, 2);
createAdminPortlet();
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/snooper/response/PlayerInfoResonce.java b/src/FE_SRC_COMMON/com/ForgeEssentials/snooper/response/PlayerInfoResonce.java
index f30e59c86..e6710324d 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/snooper/response/PlayerInfoResonce.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/snooper/response/PlayerInfoResonce.java
@@ -1,152 +1,152 @@
package com.ForgeEssentials.snooper.response;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.common.Configuration;
import com.ForgeEssentials.api.economy.EconManager;
import com.ForgeEssentials.api.json.JSONException;
import com.ForgeEssentials.api.json.JSONObject;
import com.ForgeEssentials.api.permissions.PermissionsAPI;
import com.ForgeEssentials.api.snooper.Response;
import com.ForgeEssentials.api.snooper.TextFormatter;
import com.ForgeEssentials.core.PlayerInfo;
import com.ForgeEssentials.util.AreaSelector.WorldPoint;
public class PlayerInfoResonce extends Response
{
private boolean sendhome;
private boolean sendpotions;
private boolean sendXP;
private boolean sendArmorAndHealth;
private boolean sendFood;
private boolean sendCapabilities;
private boolean sendMoney;
private boolean sendPosition;
@SuppressWarnings("unchecked")
@Override
public JSONObject getResponce(JSONObject input) throws JSONException
{
JSONObject PlayerData = new JSONObject();
JSONObject tempMap = new JSONObject();
if (!input.has("username"))
return new JSONObject().put(getName(), "This responce needs a username!");
EntityPlayerMP player = server.getConfigurationManager().getPlayerForUsername(input.getString("username"));
if (player == null)
return new JSONObject().put(getName(), input.getString("username") + " not online!");
PlayerInfo pi = PlayerInfo.getPlayerInfo(player.username);
if (pi != null && sendhome)
{
if (pi.home != null)
{
PlayerData.put("Home", pi.home.toJSON());
}
if (pi.back != null)
{
PlayerData.put("Back", pi.back.toJSON());
}
}
if (sendArmorAndHealth)
{
PlayerData.put("Armor", "" + player.inventory.getTotalArmorValue());
PlayerData.put("Health", "" + player.getHealth());
}
try
{
if (sendMoney)
{
- PlayerData.put("Money", "" + EconManager.getWallet(player));
+ PlayerData.put("Money", "" + EconManager.getWallet(player.username));
}
}
catch (Exception e)
{
}
if (sendPosition)
{
PlayerData.put("Position", new WorldPoint(player).toJSON());
}
PlayerData.put("Ping", "" + player.ping);
PlayerData.put("Gamemode", player.theItemInWorldManager.getGameType().getName());
if (!player.getActivePotionEffects().isEmpty() && sendpotions)
{
PlayerData.put("Potions", TextFormatter.toJSON(player.getActivePotionEffects()));
}
if (sendXP)
{
tempMap = new JSONObject();
tempMap.put("lvl", "" + player.experienceLevel);
tempMap.put("bar", "" + player.experience);
PlayerData.put("XP", tempMap);
}
if (sendFood)
{
tempMap = new JSONObject();
tempMap.put("Food", "" + player.getFoodStats().getFoodLevel());
tempMap.put("Saturation", "" + player.getFoodStats().getSaturationLevel());
PlayerData.put("FoodStats", tempMap);
}
if (sendCapabilities)
{
tempMap = new JSONObject();
tempMap.put("edit", "" + player.capabilities.allowEdit);
tempMap.put("allowFly", "" + player.capabilities.allowFlying);
tempMap.put("isFly", "" + player.capabilities.isFlying);
tempMap.put("noDamage", "" + player.capabilities.disableDamage);
}
PlayerData.put("Capabilities", tempMap);
try
{
PlayerData.put("group", PermissionsAPI.getHighestGroup(player).name);
}
catch (Exception e)
{
}
PlayerData.put("firstJoin", PlayerInfo.getPlayerInfo(player.username).getFirstJoin());
PlayerData.put("timePlayed", PlayerInfo.getPlayerInfo(player.username).getTimePlayed());
return new JSONObject().put(getName(), PlayerData);
}
@Override
public String getName()
{
return "PlayerInfoResonce";
}
@Override
public void readConfig(String category, Configuration config)
{
sendhome = config.get(category, "sendHome", true).getBoolean(true);
sendpotions = config.get(category, "sendpotions", true).getBoolean(true);
sendXP = config.get(category, "sendXP", true).getBoolean(true);
sendArmorAndHealth = config.get(category, "sendArmorAndHealth", true).getBoolean(true);
sendFood = config.get(category, "sendFood", true).getBoolean(true);
sendCapabilities = config.get(category, "sendCapabilities", true).getBoolean(true);
sendMoney = config.get(category, "sendMoney", true).getBoolean(true);
sendPosition = config.get(category, "sendPosition", true).getBoolean(true);
}
@Override
public void writeConfig(String category, Configuration config)
{
config.get(category, "sendHome", true).value = "" + sendhome;
config.get(category, "sendpotions", true).value = "" + sendpotions;
config.get(category, "sendXP", true).value = "" + sendXP;
config.get(category, "sendArmorAndHealth", true).value = "" + sendArmorAndHealth;
config.get(category, "sendFood", true).value = "" + sendFood;
config.get(category, "sendCapabilities", true).value = "" + sendCapabilities;
config.get(category, "sendMoney", true).value = sendMoney + "";
config.get(category, "sendPosition", true).value = sendPosition + "";
}
}
| true | true | public JSONObject getResponce(JSONObject input) throws JSONException
{
JSONObject PlayerData = new JSONObject();
JSONObject tempMap = new JSONObject();
if (!input.has("username"))
return new JSONObject().put(getName(), "This responce needs a username!");
EntityPlayerMP player = server.getConfigurationManager().getPlayerForUsername(input.getString("username"));
if (player == null)
return new JSONObject().put(getName(), input.getString("username") + " not online!");
PlayerInfo pi = PlayerInfo.getPlayerInfo(player.username);
if (pi != null && sendhome)
{
if (pi.home != null)
{
PlayerData.put("Home", pi.home.toJSON());
}
if (pi.back != null)
{
PlayerData.put("Back", pi.back.toJSON());
}
}
if (sendArmorAndHealth)
{
PlayerData.put("Armor", "" + player.inventory.getTotalArmorValue());
PlayerData.put("Health", "" + player.getHealth());
}
try
{
if (sendMoney)
{
PlayerData.put("Money", "" + EconManager.getWallet(player));
}
}
catch (Exception e)
{
}
if (sendPosition)
{
PlayerData.put("Position", new WorldPoint(player).toJSON());
}
PlayerData.put("Ping", "" + player.ping);
PlayerData.put("Gamemode", player.theItemInWorldManager.getGameType().getName());
if (!player.getActivePotionEffects().isEmpty() && sendpotions)
{
PlayerData.put("Potions", TextFormatter.toJSON(player.getActivePotionEffects()));
}
if (sendXP)
{
tempMap = new JSONObject();
tempMap.put("lvl", "" + player.experienceLevel);
tempMap.put("bar", "" + player.experience);
PlayerData.put("XP", tempMap);
}
if (sendFood)
{
tempMap = new JSONObject();
tempMap.put("Food", "" + player.getFoodStats().getFoodLevel());
tempMap.put("Saturation", "" + player.getFoodStats().getSaturationLevel());
PlayerData.put("FoodStats", tempMap);
}
if (sendCapabilities)
{
tempMap = new JSONObject();
tempMap.put("edit", "" + player.capabilities.allowEdit);
tempMap.put("allowFly", "" + player.capabilities.allowFlying);
tempMap.put("isFly", "" + player.capabilities.isFlying);
tempMap.put("noDamage", "" + player.capabilities.disableDamage);
}
PlayerData.put("Capabilities", tempMap);
try
{
PlayerData.put("group", PermissionsAPI.getHighestGroup(player).name);
}
catch (Exception e)
{
}
PlayerData.put("firstJoin", PlayerInfo.getPlayerInfo(player.username).getFirstJoin());
PlayerData.put("timePlayed", PlayerInfo.getPlayerInfo(player.username).getTimePlayed());
return new JSONObject().put(getName(), PlayerData);
}
| public JSONObject getResponce(JSONObject input) throws JSONException
{
JSONObject PlayerData = new JSONObject();
JSONObject tempMap = new JSONObject();
if (!input.has("username"))
return new JSONObject().put(getName(), "This responce needs a username!");
EntityPlayerMP player = server.getConfigurationManager().getPlayerForUsername(input.getString("username"));
if (player == null)
return new JSONObject().put(getName(), input.getString("username") + " not online!");
PlayerInfo pi = PlayerInfo.getPlayerInfo(player.username);
if (pi != null && sendhome)
{
if (pi.home != null)
{
PlayerData.put("Home", pi.home.toJSON());
}
if (pi.back != null)
{
PlayerData.put("Back", pi.back.toJSON());
}
}
if (sendArmorAndHealth)
{
PlayerData.put("Armor", "" + player.inventory.getTotalArmorValue());
PlayerData.put("Health", "" + player.getHealth());
}
try
{
if (sendMoney)
{
PlayerData.put("Money", "" + EconManager.getWallet(player.username));
}
}
catch (Exception e)
{
}
if (sendPosition)
{
PlayerData.put("Position", new WorldPoint(player).toJSON());
}
PlayerData.put("Ping", "" + player.ping);
PlayerData.put("Gamemode", player.theItemInWorldManager.getGameType().getName());
if (!player.getActivePotionEffects().isEmpty() && sendpotions)
{
PlayerData.put("Potions", TextFormatter.toJSON(player.getActivePotionEffects()));
}
if (sendXP)
{
tempMap = new JSONObject();
tempMap.put("lvl", "" + player.experienceLevel);
tempMap.put("bar", "" + player.experience);
PlayerData.put("XP", tempMap);
}
if (sendFood)
{
tempMap = new JSONObject();
tempMap.put("Food", "" + player.getFoodStats().getFoodLevel());
tempMap.put("Saturation", "" + player.getFoodStats().getSaturationLevel());
PlayerData.put("FoodStats", tempMap);
}
if (sendCapabilities)
{
tempMap = new JSONObject();
tempMap.put("edit", "" + player.capabilities.allowEdit);
tempMap.put("allowFly", "" + player.capabilities.allowFlying);
tempMap.put("isFly", "" + player.capabilities.isFlying);
tempMap.put("noDamage", "" + player.capabilities.disableDamage);
}
PlayerData.put("Capabilities", tempMap);
try
{
PlayerData.put("group", PermissionsAPI.getHighestGroup(player).name);
}
catch (Exception e)
{
}
PlayerData.put("firstJoin", PlayerInfo.getPlayerInfo(player.username).getFirstJoin());
PlayerData.put("timePlayed", PlayerInfo.getPlayerInfo(player.username).getTimePlayed());
return new JSONObject().put(getName(), PlayerData);
}
|
diff --git a/src/main/java/org/atlasapi/equiv/generators/FilmEquivalenceGenerator.java b/src/main/java/org/atlasapi/equiv/generators/FilmEquivalenceGenerator.java
index 054f63c5f..f267ef678 100644
--- a/src/main/java/org/atlasapi/equiv/generators/FilmEquivalenceGenerator.java
+++ b/src/main/java/org/atlasapi/equiv/generators/FilmEquivalenceGenerator.java
@@ -1,103 +1,103 @@
package org.atlasapi.equiv.generators;
import static com.google.common.collect.Iterables.filter;
import java.util.List;
import org.atlasapi.application.ApplicationConfiguration;
import org.atlasapi.equiv.results.description.ResultDescription;
import org.atlasapi.equiv.results.scores.DefaultScoredEquivalents;
import org.atlasapi.equiv.results.scores.DefaultScoredEquivalents.ScoredEquivalentsBuilder;
import org.atlasapi.equiv.results.scores.Score;
import org.atlasapi.equiv.results.scores.ScoredEquivalents;
import org.atlasapi.media.entity.Film;
import org.atlasapi.media.entity.Identified;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.persistence.content.SearchResolver;
import org.atlasapi.search.model.SearchQuery;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.metabroadcast.common.query.Selection;
public class FilmEquivalenceGenerator implements ContentEquivalenceGenerator<Film> {
private static final ApplicationConfiguration config = new ApplicationConfiguration(ImmutableSet.of(Publisher.PREVIEW_NETWORKS), null);
private static final float TITLE_WEIGHTING = 1.0f;
private static final float BROADCAST_WEIGHTING = 0.0f;
private static final float CATCHUP_WEIGHTING = 0.0f;
private final SearchResolver searchResolver;
public FilmEquivalenceGenerator(SearchResolver searchResolver) {
this.searchResolver = searchResolver;
}
@Override
public ScoredEquivalents<Film> generate(Film film, ResultDescription desc) {
ScoredEquivalentsBuilder<Film> scores = DefaultScoredEquivalents.<Film> fromSource("Film");
desc.startStage("Film equivalence generator");
if (film.getYear() == null || Strings.isNullOrEmpty(film.getTitle())) {
- desc.appendText("Can't continue: year '%s', title '%'", film.getYear(), film.getTitle()).finishStage();
+ desc.appendText("Can't continue: year '%s', title '%s'", film.getYear(), film.getTitle()).finishStage();
return scores.build();
} else {
desc.appendText("Using year %s, title %s", film.getYear(), film.getTitle());
}
List<Identified> possibleEquivalentFilms = searchResolver.search(new SearchQuery(film.getTitle(), Selection.ALL, ImmutableList.of(Publisher.PREVIEW_NETWORKS), TITLE_WEIGHTING,
BROADCAST_WEIGHTING, CATCHUP_WEIGHTING), config);
Iterable<Film> foundFilms = filter(possibleEquivalentFilms, Film.class);
desc.appendText("Found %s films through title search", Iterables.size(foundFilms));
for (Film equivFilm : foundFilms) {
if(sameYear(film, equivFilm)) {
Score score = Score.valueOf(titleMatch(film, equivFilm));
desc.appendText("%s (%s) scored %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), score);
scores.addEquivalent(equivFilm, score);
} else {
desc.appendText("%s (%s) ignored. Wrong year %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), equivFilm.getYear());
scores.addEquivalent(equivFilm, Score.valueOf(0.0));
}
}
desc.finishStage();
return scores.build();
}
private double titleMatch(Film film, Film equivFilm) {
return match(removeThe(alphaNumeric(film.getTitle())), removeThe(alphaNumeric(equivFilm.getTitle())));
}
public double match(String subjectTitle, String equivalentTitle) {
double commonPrefix = commonPrefixLength(subjectTitle, equivalentTitle);
double difference = Math.abs(equivalentTitle.length() - commonPrefix) / equivalentTitle.length();
return commonPrefix / (subjectTitle.length() / 1.0) - difference;
}
private String removeThe(String title) {
if(title.startsWith("the")) {
return title.substring(3);
}
return title;
}
private String alphaNumeric(String title) {
return title.replaceAll("[^\\d\\w]", "").toLowerCase();
}
private double commonPrefixLength(String t1, String t2) {
int i = 0;
for (; i < Math.min(t1.length(), t2.length()) && t1.charAt(i) == t2.charAt(i); i++) {
}
return i;
}
private boolean sameYear(Film film, Film equivFilm) {
return film.getYear().equals(equivFilm.getYear());
}
}
| true | true | public ScoredEquivalents<Film> generate(Film film, ResultDescription desc) {
ScoredEquivalentsBuilder<Film> scores = DefaultScoredEquivalents.<Film> fromSource("Film");
desc.startStage("Film equivalence generator");
if (film.getYear() == null || Strings.isNullOrEmpty(film.getTitle())) {
desc.appendText("Can't continue: year '%s', title '%'", film.getYear(), film.getTitle()).finishStage();
return scores.build();
} else {
desc.appendText("Using year %s, title %s", film.getYear(), film.getTitle());
}
List<Identified> possibleEquivalentFilms = searchResolver.search(new SearchQuery(film.getTitle(), Selection.ALL, ImmutableList.of(Publisher.PREVIEW_NETWORKS), TITLE_WEIGHTING,
BROADCAST_WEIGHTING, CATCHUP_WEIGHTING), config);
Iterable<Film> foundFilms = filter(possibleEquivalentFilms, Film.class);
desc.appendText("Found %s films through title search", Iterables.size(foundFilms));
for (Film equivFilm : foundFilms) {
if(sameYear(film, equivFilm)) {
Score score = Score.valueOf(titleMatch(film, equivFilm));
desc.appendText("%s (%s) scored %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), score);
scores.addEquivalent(equivFilm, score);
} else {
desc.appendText("%s (%s) ignored. Wrong year %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), equivFilm.getYear());
scores.addEquivalent(equivFilm, Score.valueOf(0.0));
}
}
desc.finishStage();
return scores.build();
}
| public ScoredEquivalents<Film> generate(Film film, ResultDescription desc) {
ScoredEquivalentsBuilder<Film> scores = DefaultScoredEquivalents.<Film> fromSource("Film");
desc.startStage("Film equivalence generator");
if (film.getYear() == null || Strings.isNullOrEmpty(film.getTitle())) {
desc.appendText("Can't continue: year '%s', title '%s'", film.getYear(), film.getTitle()).finishStage();
return scores.build();
} else {
desc.appendText("Using year %s, title %s", film.getYear(), film.getTitle());
}
List<Identified> possibleEquivalentFilms = searchResolver.search(new SearchQuery(film.getTitle(), Selection.ALL, ImmutableList.of(Publisher.PREVIEW_NETWORKS), TITLE_WEIGHTING,
BROADCAST_WEIGHTING, CATCHUP_WEIGHTING), config);
Iterable<Film> foundFilms = filter(possibleEquivalentFilms, Film.class);
desc.appendText("Found %s films through title search", Iterables.size(foundFilms));
for (Film equivFilm : foundFilms) {
if(sameYear(film, equivFilm)) {
Score score = Score.valueOf(titleMatch(film, equivFilm));
desc.appendText("%s (%s) scored %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), score);
scores.addEquivalent(equivFilm, score);
} else {
desc.appendText("%s (%s) ignored. Wrong year %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), equivFilm.getYear());
scores.addEquivalent(equivFilm, Score.valueOf(0.0));
}
}
desc.finishStage();
return scores.build();
}
|
diff --git a/AeroControl/src/com/aero/control/fragments/CPUFragment.java b/AeroControl/src/com/aero/control/fragments/CPUFragment.java
index cfc4d21..b167466 100644
--- a/AeroControl/src/com/aero/control/fragments/CPUFragment.java
+++ b/AeroControl/src/com/aero/control/fragments/CPUFragment.java
@@ -1,704 +1,712 @@
package com.aero.control.fragments;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.aero.control.AeroActivity;
import com.aero.control.R;
import com.aero.control.helpers.PreferenceHandler;
import com.espian.showcaseview.ShowcaseView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
/**
* Created by ac on 03.10.13.
*
* TODO: Simplify those static strings
*
*/
public class CPUFragment extends PreferenceFragment {
public static final String CPU_BASE_PATH = "/sys/devices/system/cpu/cpu";
public static final String CPU_AVAILABLE_FREQ = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies";
public static final String ALL_GOV_AVAILABLE = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors";
public static final String CURRENT_GOV_AVAILABLE = "/cpufreq/scaling_governor";
public static final String CPU_MAX_FREQ = "/cpufreq/scaling_max_freq";
public static final String CPU_MIN_FREQ = "/cpufreq/scaling_min_freq";
public static final String CPU_GOV_SET_BASE = "/sys/devices/system/cpu/cpufreq/";
public static final String CPU_VSEL = "/proc/overclock/mpu_opps";
public static final String CPU_VSEL_MAX = "/proc/overclock/max_vsel";
public static final String CPU_MAX_RATE = "/proc/overclock/max_rate";
public static final String CPU_FREQ_TABLE = "/proc/overclock/freq_table";
public static final String FILENAME = "firstrun_cpu";
public PreferenceScreen root;
public PreferenceCategory PrefCat;
public ListPreference listPref;
public ListPreference min_frequency;
public ListPreference max_frequency;
public boolean mVisible = true;
private SharedPreferences prefs;
public ShowcaseView.ConfigOptions mConfigOptions;
public ShowcaseView mShowCase;
public static final int mNumCpus = Runtime.getRuntime().availableProcessors();
@Override
final public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// We have to load the xml layout first;
addPreferencesFromResource(R.layout.cpu_fragment);
root = this.getPreferenceScreen();
// Remove until back in Kernel;
PreferenceCategory cpuCategory = (PreferenceCategory) findPreference("cpu_settings");
// I don't like the following, can we simplify it?
// Find our ListPreference (max_frequency);
max_frequency = (ListPreference) root.findPreference("max_frequency");
updateMaxFreq();
max_frequency.setDialogIcon(R.drawable.lightning_dark);
// Find our ListPreference (min_frequency);
min_frequency = (ListPreference) root.findPreference("min_frequency");
updateMinFreq();
min_frequency.setDialogIcon(R.drawable.lightning_dark);
final Preference cpu_hotplug = root.findPreference("hotplug_control");
if (new File("/sys/kernel/hotplug_control").exists()) {
cpu_hotplug.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new CPUHotplugFragment())
.addToBackStack("Hotplug")
.commit();
return true;
}
});
} else {
cpuCategory.removePreference(cpu_hotplug);
}
final Preference voltage_control = root.findPreference("undervolt_control");
if (new File("/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table").exists()) {
voltage_control.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new VoltageFragment())
.addToBackStack("Voltage")
.commit();
return true;
}
});
} else {
cpuCategory.removePreference(voltage_control);
}
final Preference cpu_oc_uc = (Preference) root.findPreference("cpu_oc_uc");
if (AeroActivity.shell.getInfo(CPU_VSEL).equals("Unavailable")) {
cpu_oc_uc.setEnabled(false);
cpuCategory.removePreference(cpu_oc_uc);
}
cpu_oc_uc.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// Set up Alert Dialog and view;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.cpu_oc_uc, null);
builder.setIcon(R.drawable.lightbulb_dark);
String[] cpufreq = AeroActivity.shell.getInfoArray(CPU_AVAILABLE_FREQ, 0, 0);
// Our cpu values list;
final ArrayList<String> cpu_list = new ArrayList<String>();
final String overclockOutput = AeroActivity.shell.getRootInfo("cat", CPU_VSEL);
// Set up our EditText fields;
final EditText value1 = (EditText) layout.findViewById(R.id.value1);
final EditText value2 = (EditText) layout.findViewById(R.id.value2);
final EditText value3 = (EditText) layout.findViewById(R.id.value3);
final EditText value4 = (EditText) layout.findViewById(R.id.value4);
final EditText value5 = (EditText) layout.findViewById(R.id.value5);
final EditText value6 = (EditText) layout.findViewById(R.id.value6);
final EditText value7 = (EditText) layout.findViewById(R.id.value7);
final EditText value8 = (EditText) layout.findViewById(R.id.value8);
// Left side (cpu frequencies);
value1.setText(cpufreq[0]);
value3.setText(cpufreq[1]);
value5.setText(cpufreq[2]);
value7.setText(cpufreq[3]);
// Substring is not ideal, but it gets the job done;
value2.setText(overclockOutput.substring(42, 44));
// In case somebody uses very high frequencies;
if (Integer.parseInt(cpufreq[1]) >= 1000000) {
value4.setText(overclockOutput.substring(105, 107));
value6.setText(overclockOutput.substring(167, 169));
value8.setText(overclockOutput.substring(229, 231));
} else {
value4.setText(overclockOutput.substring(104, 106));
value6.setText(overclockOutput.substring(166, 168));
value8.setText(overclockOutput.substring(228, 230));
}
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(layout)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
AeroActivity.shell.setOverclockAddress();
// Objects;
final Object f = (value1.getText());
final Object g = (value3.getText());
final Object h = (value5.getText());
final Object i = (value7.getText());
Runnable runnable = new Runnable() {
int a, b, c, d;
int vsel1, vsel2, vsel3, vsel4;
@Override
public void run() {
// Cast objects to integer (frequencies;
a = Integer.parseInt(f.toString());
b = Integer.parseInt(g.toString());
c = Integer.parseInt(h.toString());
d = Integer.parseInt(i.toString());
try {
// Cast voltages;
vsel1 = Integer.parseInt(value2.getText().toString());
vsel2 = Integer.parseInt(value4.getText().toString());
vsel3 = Integer.parseInt(value6.getText().toString());
vsel4 = Integer.parseInt(value8.getText().toString());
} catch (NumberFormatException e) {
// Go back to default, if wrong values;
vsel1 = 62;
vsel2 = 58;
vsel3 = 48;
vsel4 = 33;
Log.e("Aero", "These are wrong values, back to default.", e);
}
// Check if there are valid values;
if (a <= 1500000 && a > b && b > c && c > d
&& vsel1 < 80 && vsel1 > vsel2 && vsel2 > vsel3 && vsel3 > vsel4 && vsel4 >= 15) {
if (a > 300000 && b > 300000 && c > 300000 && d >= 300000) {
try {
// Set our max vsel after we changed the max freq
cpu_list.add("echo " + vsel1 + " > " + CPU_VSEL_MAX);
cpu_list.add("echo " + "4" + " " + a + "000" + " " + vsel1 + " > " + CPU_VSEL);
cpu_list.add("echo " + "3" + " " + b + "000" + " " + vsel2 + " > " + CPU_VSEL);
cpu_list.add("echo " + "2" + " " + c + "000" + " " + vsel3 + " > " + CPU_VSEL);
cpu_list.add("echo " + "1" + " " + d + "000" + " " + vsel4 + " > " + CPU_VSEL);
cpu_list.add("echo " + "0" + " " + a + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1" + " " + b + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "2" + " " + c + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "3" + " " + d + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + f + " > " + CPU_MAX_RATE);
cpu_list.add("echo " + i + " > " + CPU_BASE_PATH + 0 + CPU_MIN_FREQ);
String[] commands = cpu_list.toArray(new String[0]);
// Throw them all in!
AeroActivity.shell.setRootInfo(commands);
//** store preferences
//** note that this time we put to preferences commands instead of single values,
//** rebuild the commands in the bootService would have been a little expensive
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
preference.edit().putStringSet("cpu_commands", new HashSet<String>(Arrays.asList(commands))).commit();
} catch (Exception e) {
Log.e("Aero", "An Error occurred while setting values", e);
Toast.makeText(getActivity(), "An Error occurred, check logcat!", Toast.LENGTH_SHORT).show();
}
} else {
Log.e("Aero", "The frequencies you have set are to low!");
}
} else {
Log.e("Aero", "Cannot apply values, they are not in range.");
}
}
};
try {
Thread cpuUpdateThread = new Thread(runnable);
cpuUpdateThread.start();
} catch (Exception e) {
Log.e("Aero", "Something went completely wrong.", e);
}
// Start our background refresher Task;
try {
// Only start if not already alive
if (!mRefreshThread.isAlive()) {
mRefreshThread.start();
mRefreshThread.setPriority(Thread.MIN_PRIORITY);
}
} catch (NullPointerException e) {
Log.e("Aero", "Couldn't start Refresher Thread.", e);
}
}
})
.setNeutralButton(R.string.default_values, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
AeroActivity.shell.setOverclockAddress();
// Set our max vsel after we changed the max freq
cpu_list.add("echo " + "62" + " > " + CPU_VSEL_MAX);
cpu_list.add("echo " + "4" + " 1000000000" + " 62" + " > " + CPU_VSEL);
cpu_list.add("echo " + "3" + " 800000000" + " 58" + " > " + CPU_VSEL);
cpu_list.add("echo " + "2" + " 600000000" + " 48" + " > " + CPU_VSEL);
cpu_list.add("echo " + "1" + " 300000000" + " 33" + " > " + CPU_VSEL);
cpu_list.add("echo " + "0" + " 1000000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1" + " 800000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "2" + " 600000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "3" + " 300000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1000000" + " > " + CPU_MAX_RATE);
cpu_list.add("echo " + "300000" + " > " + CPU_MIN_FREQ);
String[] commands = cpu_list.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
try {
Thread.sleep(350);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
//** store preferences
//** note that this time we put to preferences commands instead of single values,
//** rebuild the commands in the bootService would have been a little expensive
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
preference.edit().putStringSet("cpu_commands", new HashSet<String>(Arrays.asList(commands))).commit();
} catch (Exception e) {
Log.e("Aero", "An Error occurred while setting values", e);
Toast.makeText(getActivity(), "An Error occurred, check logcat!", Toast.LENGTH_SHORT).show();
}
// Start our background refresher Task;
try {
// Only start if not already alive
if (!mRefreshThread.isAlive()) {
mRefreshThread.start();
mRefreshThread.setPriority(Thread.MIN_PRIORITY);
}
} catch (NullPointerException e) {
Log.e("Aero", "Couldn't start Refresher Thread.", e);
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setTitle(R.string.perf_live_oc_uc).show();
return false;
}
});
// Find our ListPreference (governor_settings);
listPref = (ListPreference) root.findPreference("set_governor");
// Just throw in our frequencies;
listPref.setEntries(AeroActivity.shell.getInfoArray(ALL_GOV_AVAILABLE, 0, 0));
listPref.setEntryValues(AeroActivity.shell.getInfoArray(ALL_GOV_AVAILABLE, 0, 0));
listPref.setValue(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
listPref.setSummary(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
listPref.setDialogIcon(R.drawable.cpu_dark);
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
//different listener for each element
listPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
/*
* I need to cast the object to a string first, but setRootInfo
* will take the object instead (its casted again there).
* The intention behind this is, is to solve the slow UI reaction
* and the slow file write process. Otherwise the UI would show the
* value _before_ the value actually was changed.
*/
String a = (String) o;
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
// Change governor for each available CPU;
setGovernor(a);
/*
* Probably the kernel takes a while to update the dictionaries
* and therefore we sleep for a short interval;
*/
try {
Thread.sleep(350);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
listPref.setSummary(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
// store preferences
preference.getEditor().commit();
return true;
}
;
});
max_frequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
/*
* Its pretty much the same like on the governor, except we only deal with numbers
* Also this should make no problems when the user is using different
* Clocks than default...
*/
String a = (String) o;
ArrayList<String> array = new ArrayList<String>();
- if (Integer.parseInt(a) < Integer.parseInt(min_frequency.getValue()))
+ try {
+ if (Integer.parseInt(a) < Integer.parseInt(min_frequency.getValue()))
+ return false;
+ } catch (NullPointerException e) {
return false;
+ }
for (int k = 0; k < mNumCpus; k++) {
array.add("echo " + a + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ);
//** store preferences
preference.getEditor().commit();
}
max_frequency.setSummary(AeroActivity.shell.toMHz(a));
String[] commands = array.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
return true;
};
});
min_frequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
String a = (String) o;
ArrayList<String> array = new ArrayList<String>();
- if (Integer.parseInt(a) > Integer.parseInt(max_frequency.getValue()))
+ try {
+ if (Integer.parseInt(a) > Integer.parseInt(max_frequency.getValue()))
+ return false;
+ } catch (NullPointerException e) {
return false;
+ }
for (int k = 0; k < mNumCpus; k++) {
array.add("echo " + a + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ);
//** store preferences
preference.getEditor().commit();
}
min_frequency.setSummary(AeroActivity.shell.toMHz(a));
String[] commands = array.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
return true;
};
});
}
// Create our options menu;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String a = prefs.getString("app_theme", null);
if (a == null)
a = "";
if (a.equals("red"))
inflater.inflate(R.menu.cpu_menu, menu);
else if (a.equals("light"))
inflater.inflate(R.menu.cpu_menu, menu);
else if (a.equals("dark"))
inflater.inflate(R.menu.cpu_menu_light, menu);
else
inflater.inflate(R.menu.cpu_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_governor_settings:
final String complete_path = CPU_GOV_SET_BASE + listPref.getValue();
ArrayList<String> al = new ArrayList<String>();
/*
* Before we can get governor specific parameters,
* we need permissions first. Since we don't want to use "su"
* here, we change the current governor shortly to performance.
*/
try {
String completeParamterList[] = AeroActivity.shell.getDirInfo(complete_path, true);
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
PrefCat = new PreferenceCategory(getActivity());
PrefCat.setTitle(R.string.pref_gov_set);
root.addPreference(PrefCat);
/*
* Sometimes its just all about permissions;
*/
for (String b : completeParamterList) {
al.add("chmod 644 " + complete_path + "/" + b);
al.add("chown system:root " + complete_path + "/" + b);
}
String[] commands = al.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
final PreferenceHandler h = new PreferenceHandler(getActivity(), PrefCat, getPreferenceManager());
h.genPrefFromDictionary(completeParamterList, complete_path);
// Probably the wrong place, should be in getDirInfo ?
} catch (NullPointerException e) {
Toast.makeText(getActivity(), "Looks like there are no parameter for this governor?", Toast.LENGTH_LONG).show();
Log.e("Aero", "There isn't any folder i can check. Does this governor has parameters?", e);
return true;
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onPause() {
super.onPause();
mVisible = false;
// To clean up the UI;
if (PrefCat != null)
root.removePreference(PrefCat);
}
@Override
public void onResume() {
super.onResume();
mVisible = true;
}
public void setGovernor(String s) {
ArrayList<String> array = new ArrayList<String>();
// Change governor for each available CPU;
for (int k = 0; k < mNumCpus; k++) {
// To ensure we get proper permissions, change the governor to performance first;
//array.add("echo " + "performance" + " > " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE);
array.add("echo " + s + " > " + CPU_BASE_PATH + k + CURRENT_GOV_AVAILABLE);
}
String[] commands = array.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
}
public void updateMinFreq() {
// Just throw in our frequencies;
min_frequency.setEntries(AeroActivity.shell.getInfoArray(CPU_AVAILABLE_FREQ, 1, 0));
min_frequency.setEntryValues(AeroActivity.shell.getInfoArray(CPU_AVAILABLE_FREQ, 0, 0));
try {
min_frequency.setValue(AeroActivity.shell.getInfoArray(CPU_BASE_PATH + 0 + CPU_MIN_FREQ, 0, 0)[0]);
min_frequency.setSummary(AeroActivity.shell.getInfoArray(CPU_BASE_PATH + 0 + CPU_MIN_FREQ, 1, 0)[0]);
} catch (ArrayIndexOutOfBoundsException e) {
min_frequency.setValue("Unavailable");
min_frequency.setSummary("Unavailable");
}
//** store preferences
min_frequency.getEditor().commit();
}
public void updateMaxFreq() {
// Just throw in our frequencies;
max_frequency.setEntries(AeroActivity.shell.getInfoArray(CPU_AVAILABLE_FREQ, 1, 0));
max_frequency.setEntryValues(AeroActivity.shell.getInfoArray(CPU_AVAILABLE_FREQ, 0, 0));
try {
max_frequency.setValue(AeroActivity.shell.getInfoArray(CPU_BASE_PATH + 0 + CPU_MAX_FREQ, 0, 0)[0]);
max_frequency.setSummary(AeroActivity.shell.getInfoArray(CPU_BASE_PATH + 0 + CPU_MAX_FREQ, 1, 0)[0]);
} catch (ArrayIndexOutOfBoundsException e) {
max_frequency.setValue("Unavailable");
max_frequency.setSummary("Unavailable");
}
//** store preferences
max_frequency.getEditor().commit();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Prepare Showcase;
mConfigOptions = new ShowcaseView.ConfigOptions();
mConfigOptions.hideOnClickOutside = false;
mConfigOptions.shotType = ShowcaseView.TYPE_ONE_SHOT;
// Set up our file;
int output = 0;
final byte[] buffer = new byte[1024];
try {
final FileInputStream fis = getActivity().openFileInput(FILENAME);
output = fis.read(buffer);
fis.close();
} catch (IOException e) {
Log.e("Aero", "Couldn't open File... " + output);
}
// Only show showcase once;
if (output == 0)
DrawFirstStart(R.string.showcase_cpu_fragment_governor, R.string.showcase_cpu_fragment_governor_sum);
}
public void DrawFirstStart(int header, int content) {
try {
final FileOutputStream fos = getActivity().openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write("1".getBytes());
fos.close();
}
catch (IOException e) {
Log.e("Aero", "Could not save file. ", e);
}
mShowCase = ShowcaseView.insertShowcaseViewWithType(ShowcaseView.ITEM_ACTION_ITEM , R.id.action_governor_settings, getActivity(), header, content, mConfigOptions);
}
private class RefreshThread extends Thread {
private boolean mInterrupt = false;
public void interrupt() {
mInterrupt = true;
}
@Override
public void run() {
try {
while (!mInterrupt) {
sleep(1000);
mRefreshHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
}
}
};
private RefreshThread mRefreshThread = new RefreshThread();
private Handler mRefreshHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what >= 1) {
if (isVisible() && mVisible) {
updateMaxFreq();
updateMinFreq();
mVisible = true;
} else {
// Do nothing
}
}
}
};
}
| false | true | final public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// We have to load the xml layout first;
addPreferencesFromResource(R.layout.cpu_fragment);
root = this.getPreferenceScreen();
// Remove until back in Kernel;
PreferenceCategory cpuCategory = (PreferenceCategory) findPreference("cpu_settings");
// I don't like the following, can we simplify it?
// Find our ListPreference (max_frequency);
max_frequency = (ListPreference) root.findPreference("max_frequency");
updateMaxFreq();
max_frequency.setDialogIcon(R.drawable.lightning_dark);
// Find our ListPreference (min_frequency);
min_frequency = (ListPreference) root.findPreference("min_frequency");
updateMinFreq();
min_frequency.setDialogIcon(R.drawable.lightning_dark);
final Preference cpu_hotplug = root.findPreference("hotplug_control");
if (new File("/sys/kernel/hotplug_control").exists()) {
cpu_hotplug.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new CPUHotplugFragment())
.addToBackStack("Hotplug")
.commit();
return true;
}
});
} else {
cpuCategory.removePreference(cpu_hotplug);
}
final Preference voltage_control = root.findPreference("undervolt_control");
if (new File("/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table").exists()) {
voltage_control.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new VoltageFragment())
.addToBackStack("Voltage")
.commit();
return true;
}
});
} else {
cpuCategory.removePreference(voltage_control);
}
final Preference cpu_oc_uc = (Preference) root.findPreference("cpu_oc_uc");
if (AeroActivity.shell.getInfo(CPU_VSEL).equals("Unavailable")) {
cpu_oc_uc.setEnabled(false);
cpuCategory.removePreference(cpu_oc_uc);
}
cpu_oc_uc.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// Set up Alert Dialog and view;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.cpu_oc_uc, null);
builder.setIcon(R.drawable.lightbulb_dark);
String[] cpufreq = AeroActivity.shell.getInfoArray(CPU_AVAILABLE_FREQ, 0, 0);
// Our cpu values list;
final ArrayList<String> cpu_list = new ArrayList<String>();
final String overclockOutput = AeroActivity.shell.getRootInfo("cat", CPU_VSEL);
// Set up our EditText fields;
final EditText value1 = (EditText) layout.findViewById(R.id.value1);
final EditText value2 = (EditText) layout.findViewById(R.id.value2);
final EditText value3 = (EditText) layout.findViewById(R.id.value3);
final EditText value4 = (EditText) layout.findViewById(R.id.value4);
final EditText value5 = (EditText) layout.findViewById(R.id.value5);
final EditText value6 = (EditText) layout.findViewById(R.id.value6);
final EditText value7 = (EditText) layout.findViewById(R.id.value7);
final EditText value8 = (EditText) layout.findViewById(R.id.value8);
// Left side (cpu frequencies);
value1.setText(cpufreq[0]);
value3.setText(cpufreq[1]);
value5.setText(cpufreq[2]);
value7.setText(cpufreq[3]);
// Substring is not ideal, but it gets the job done;
value2.setText(overclockOutput.substring(42, 44));
// In case somebody uses very high frequencies;
if (Integer.parseInt(cpufreq[1]) >= 1000000) {
value4.setText(overclockOutput.substring(105, 107));
value6.setText(overclockOutput.substring(167, 169));
value8.setText(overclockOutput.substring(229, 231));
} else {
value4.setText(overclockOutput.substring(104, 106));
value6.setText(overclockOutput.substring(166, 168));
value8.setText(overclockOutput.substring(228, 230));
}
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(layout)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
AeroActivity.shell.setOverclockAddress();
// Objects;
final Object f = (value1.getText());
final Object g = (value3.getText());
final Object h = (value5.getText());
final Object i = (value7.getText());
Runnable runnable = new Runnable() {
int a, b, c, d;
int vsel1, vsel2, vsel3, vsel4;
@Override
public void run() {
// Cast objects to integer (frequencies;
a = Integer.parseInt(f.toString());
b = Integer.parseInt(g.toString());
c = Integer.parseInt(h.toString());
d = Integer.parseInt(i.toString());
try {
// Cast voltages;
vsel1 = Integer.parseInt(value2.getText().toString());
vsel2 = Integer.parseInt(value4.getText().toString());
vsel3 = Integer.parseInt(value6.getText().toString());
vsel4 = Integer.parseInt(value8.getText().toString());
} catch (NumberFormatException e) {
// Go back to default, if wrong values;
vsel1 = 62;
vsel2 = 58;
vsel3 = 48;
vsel4 = 33;
Log.e("Aero", "These are wrong values, back to default.", e);
}
// Check if there are valid values;
if (a <= 1500000 && a > b && b > c && c > d
&& vsel1 < 80 && vsel1 > vsel2 && vsel2 > vsel3 && vsel3 > vsel4 && vsel4 >= 15) {
if (a > 300000 && b > 300000 && c > 300000 && d >= 300000) {
try {
// Set our max vsel after we changed the max freq
cpu_list.add("echo " + vsel1 + " > " + CPU_VSEL_MAX);
cpu_list.add("echo " + "4" + " " + a + "000" + " " + vsel1 + " > " + CPU_VSEL);
cpu_list.add("echo " + "3" + " " + b + "000" + " " + vsel2 + " > " + CPU_VSEL);
cpu_list.add("echo " + "2" + " " + c + "000" + " " + vsel3 + " > " + CPU_VSEL);
cpu_list.add("echo " + "1" + " " + d + "000" + " " + vsel4 + " > " + CPU_VSEL);
cpu_list.add("echo " + "0" + " " + a + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1" + " " + b + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "2" + " " + c + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "3" + " " + d + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + f + " > " + CPU_MAX_RATE);
cpu_list.add("echo " + i + " > " + CPU_BASE_PATH + 0 + CPU_MIN_FREQ);
String[] commands = cpu_list.toArray(new String[0]);
// Throw them all in!
AeroActivity.shell.setRootInfo(commands);
//** store preferences
//** note that this time we put to preferences commands instead of single values,
//** rebuild the commands in the bootService would have been a little expensive
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
preference.edit().putStringSet("cpu_commands", new HashSet<String>(Arrays.asList(commands))).commit();
} catch (Exception e) {
Log.e("Aero", "An Error occurred while setting values", e);
Toast.makeText(getActivity(), "An Error occurred, check logcat!", Toast.LENGTH_SHORT).show();
}
} else {
Log.e("Aero", "The frequencies you have set are to low!");
}
} else {
Log.e("Aero", "Cannot apply values, they are not in range.");
}
}
};
try {
Thread cpuUpdateThread = new Thread(runnable);
cpuUpdateThread.start();
} catch (Exception e) {
Log.e("Aero", "Something went completely wrong.", e);
}
// Start our background refresher Task;
try {
// Only start if not already alive
if (!mRefreshThread.isAlive()) {
mRefreshThread.start();
mRefreshThread.setPriority(Thread.MIN_PRIORITY);
}
} catch (NullPointerException e) {
Log.e("Aero", "Couldn't start Refresher Thread.", e);
}
}
})
.setNeutralButton(R.string.default_values, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
AeroActivity.shell.setOverclockAddress();
// Set our max vsel after we changed the max freq
cpu_list.add("echo " + "62" + " > " + CPU_VSEL_MAX);
cpu_list.add("echo " + "4" + " 1000000000" + " 62" + " > " + CPU_VSEL);
cpu_list.add("echo " + "3" + " 800000000" + " 58" + " > " + CPU_VSEL);
cpu_list.add("echo " + "2" + " 600000000" + " 48" + " > " + CPU_VSEL);
cpu_list.add("echo " + "1" + " 300000000" + " 33" + " > " + CPU_VSEL);
cpu_list.add("echo " + "0" + " 1000000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1" + " 800000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "2" + " 600000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "3" + " 300000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1000000" + " > " + CPU_MAX_RATE);
cpu_list.add("echo " + "300000" + " > " + CPU_MIN_FREQ);
String[] commands = cpu_list.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
try {
Thread.sleep(350);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
//** store preferences
//** note that this time we put to preferences commands instead of single values,
//** rebuild the commands in the bootService would have been a little expensive
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
preference.edit().putStringSet("cpu_commands", new HashSet<String>(Arrays.asList(commands))).commit();
} catch (Exception e) {
Log.e("Aero", "An Error occurred while setting values", e);
Toast.makeText(getActivity(), "An Error occurred, check logcat!", Toast.LENGTH_SHORT).show();
}
// Start our background refresher Task;
try {
// Only start if not already alive
if (!mRefreshThread.isAlive()) {
mRefreshThread.start();
mRefreshThread.setPriority(Thread.MIN_PRIORITY);
}
} catch (NullPointerException e) {
Log.e("Aero", "Couldn't start Refresher Thread.", e);
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setTitle(R.string.perf_live_oc_uc).show();
return false;
}
});
// Find our ListPreference (governor_settings);
listPref = (ListPreference) root.findPreference("set_governor");
// Just throw in our frequencies;
listPref.setEntries(AeroActivity.shell.getInfoArray(ALL_GOV_AVAILABLE, 0, 0));
listPref.setEntryValues(AeroActivity.shell.getInfoArray(ALL_GOV_AVAILABLE, 0, 0));
listPref.setValue(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
listPref.setSummary(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
listPref.setDialogIcon(R.drawable.cpu_dark);
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
//different listener for each element
listPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
/*
* I need to cast the object to a string first, but setRootInfo
* will take the object instead (its casted again there).
* The intention behind this is, is to solve the slow UI reaction
* and the slow file write process. Otherwise the UI would show the
* value _before_ the value actually was changed.
*/
String a = (String) o;
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
// Change governor for each available CPU;
setGovernor(a);
/*
* Probably the kernel takes a while to update the dictionaries
* and therefore we sleep for a short interval;
*/
try {
Thread.sleep(350);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
listPref.setSummary(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
// store preferences
preference.getEditor().commit();
return true;
}
;
});
max_frequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
/*
* Its pretty much the same like on the governor, except we only deal with numbers
* Also this should make no problems when the user is using different
* Clocks than default...
*/
String a = (String) o;
ArrayList<String> array = new ArrayList<String>();
if (Integer.parseInt(a) < Integer.parseInt(min_frequency.getValue()))
return false;
for (int k = 0; k < mNumCpus; k++) {
array.add("echo " + a + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ);
//** store preferences
preference.getEditor().commit();
}
max_frequency.setSummary(AeroActivity.shell.toMHz(a));
String[] commands = array.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
return true;
};
});
min_frequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
String a = (String) o;
ArrayList<String> array = new ArrayList<String>();
if (Integer.parseInt(a) > Integer.parseInt(max_frequency.getValue()))
return false;
for (int k = 0; k < mNumCpus; k++) {
array.add("echo " + a + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ);
//** store preferences
preference.getEditor().commit();
}
min_frequency.setSummary(AeroActivity.shell.toMHz(a));
String[] commands = array.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
return true;
};
});
}
| final public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// We have to load the xml layout first;
addPreferencesFromResource(R.layout.cpu_fragment);
root = this.getPreferenceScreen();
// Remove until back in Kernel;
PreferenceCategory cpuCategory = (PreferenceCategory) findPreference("cpu_settings");
// I don't like the following, can we simplify it?
// Find our ListPreference (max_frequency);
max_frequency = (ListPreference) root.findPreference("max_frequency");
updateMaxFreq();
max_frequency.setDialogIcon(R.drawable.lightning_dark);
// Find our ListPreference (min_frequency);
min_frequency = (ListPreference) root.findPreference("min_frequency");
updateMinFreq();
min_frequency.setDialogIcon(R.drawable.lightning_dark);
final Preference cpu_hotplug = root.findPreference("hotplug_control");
if (new File("/sys/kernel/hotplug_control").exists()) {
cpu_hotplug.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new CPUHotplugFragment())
.addToBackStack("Hotplug")
.commit();
return true;
}
});
} else {
cpuCategory.removePreference(cpu_hotplug);
}
final Preference voltage_control = root.findPreference("undervolt_control");
if (new File("/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table").exists()) {
voltage_control.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, new VoltageFragment())
.addToBackStack("Voltage")
.commit();
return true;
}
});
} else {
cpuCategory.removePreference(voltage_control);
}
final Preference cpu_oc_uc = (Preference) root.findPreference("cpu_oc_uc");
if (AeroActivity.shell.getInfo(CPU_VSEL).equals("Unavailable")) {
cpu_oc_uc.setEnabled(false);
cpuCategory.removePreference(cpu_oc_uc);
}
cpu_oc_uc.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
// Set up Alert Dialog and view;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.cpu_oc_uc, null);
builder.setIcon(R.drawable.lightbulb_dark);
String[] cpufreq = AeroActivity.shell.getInfoArray(CPU_AVAILABLE_FREQ, 0, 0);
// Our cpu values list;
final ArrayList<String> cpu_list = new ArrayList<String>();
final String overclockOutput = AeroActivity.shell.getRootInfo("cat", CPU_VSEL);
// Set up our EditText fields;
final EditText value1 = (EditText) layout.findViewById(R.id.value1);
final EditText value2 = (EditText) layout.findViewById(R.id.value2);
final EditText value3 = (EditText) layout.findViewById(R.id.value3);
final EditText value4 = (EditText) layout.findViewById(R.id.value4);
final EditText value5 = (EditText) layout.findViewById(R.id.value5);
final EditText value6 = (EditText) layout.findViewById(R.id.value6);
final EditText value7 = (EditText) layout.findViewById(R.id.value7);
final EditText value8 = (EditText) layout.findViewById(R.id.value8);
// Left side (cpu frequencies);
value1.setText(cpufreq[0]);
value3.setText(cpufreq[1]);
value5.setText(cpufreq[2]);
value7.setText(cpufreq[3]);
// Substring is not ideal, but it gets the job done;
value2.setText(overclockOutput.substring(42, 44));
// In case somebody uses very high frequencies;
if (Integer.parseInt(cpufreq[1]) >= 1000000) {
value4.setText(overclockOutput.substring(105, 107));
value6.setText(overclockOutput.substring(167, 169));
value8.setText(overclockOutput.substring(229, 231));
} else {
value4.setText(overclockOutput.substring(104, 106));
value6.setText(overclockOutput.substring(166, 168));
value8.setText(overclockOutput.substring(228, 230));
}
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(layout)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
AeroActivity.shell.setOverclockAddress();
// Objects;
final Object f = (value1.getText());
final Object g = (value3.getText());
final Object h = (value5.getText());
final Object i = (value7.getText());
Runnable runnable = new Runnable() {
int a, b, c, d;
int vsel1, vsel2, vsel3, vsel4;
@Override
public void run() {
// Cast objects to integer (frequencies;
a = Integer.parseInt(f.toString());
b = Integer.parseInt(g.toString());
c = Integer.parseInt(h.toString());
d = Integer.parseInt(i.toString());
try {
// Cast voltages;
vsel1 = Integer.parseInt(value2.getText().toString());
vsel2 = Integer.parseInt(value4.getText().toString());
vsel3 = Integer.parseInt(value6.getText().toString());
vsel4 = Integer.parseInt(value8.getText().toString());
} catch (NumberFormatException e) {
// Go back to default, if wrong values;
vsel1 = 62;
vsel2 = 58;
vsel3 = 48;
vsel4 = 33;
Log.e("Aero", "These are wrong values, back to default.", e);
}
// Check if there are valid values;
if (a <= 1500000 && a > b && b > c && c > d
&& vsel1 < 80 && vsel1 > vsel2 && vsel2 > vsel3 && vsel3 > vsel4 && vsel4 >= 15) {
if (a > 300000 && b > 300000 && c > 300000 && d >= 300000) {
try {
// Set our max vsel after we changed the max freq
cpu_list.add("echo " + vsel1 + " > " + CPU_VSEL_MAX);
cpu_list.add("echo " + "4" + " " + a + "000" + " " + vsel1 + " > " + CPU_VSEL);
cpu_list.add("echo " + "3" + " " + b + "000" + " " + vsel2 + " > " + CPU_VSEL);
cpu_list.add("echo " + "2" + " " + c + "000" + " " + vsel3 + " > " + CPU_VSEL);
cpu_list.add("echo " + "1" + " " + d + "000" + " " + vsel4 + " > " + CPU_VSEL);
cpu_list.add("echo " + "0" + " " + a + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1" + " " + b + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "2" + " " + c + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "3" + " " + d + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + f + " > " + CPU_MAX_RATE);
cpu_list.add("echo " + i + " > " + CPU_BASE_PATH + 0 + CPU_MIN_FREQ);
String[] commands = cpu_list.toArray(new String[0]);
// Throw them all in!
AeroActivity.shell.setRootInfo(commands);
//** store preferences
//** note that this time we put to preferences commands instead of single values,
//** rebuild the commands in the bootService would have been a little expensive
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
preference.edit().putStringSet("cpu_commands", new HashSet<String>(Arrays.asList(commands))).commit();
} catch (Exception e) {
Log.e("Aero", "An Error occurred while setting values", e);
Toast.makeText(getActivity(), "An Error occurred, check logcat!", Toast.LENGTH_SHORT).show();
}
} else {
Log.e("Aero", "The frequencies you have set are to low!");
}
} else {
Log.e("Aero", "Cannot apply values, they are not in range.");
}
}
};
try {
Thread cpuUpdateThread = new Thread(runnable);
cpuUpdateThread.start();
} catch (Exception e) {
Log.e("Aero", "Something went completely wrong.", e);
}
// Start our background refresher Task;
try {
// Only start if not already alive
if (!mRefreshThread.isAlive()) {
mRefreshThread.start();
mRefreshThread.setPriority(Thread.MIN_PRIORITY);
}
} catch (NullPointerException e) {
Log.e("Aero", "Couldn't start Refresher Thread.", e);
}
}
})
.setNeutralButton(R.string.default_values, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
AeroActivity.shell.setOverclockAddress();
// Set our max vsel after we changed the max freq
cpu_list.add("echo " + "62" + " > " + CPU_VSEL_MAX);
cpu_list.add("echo " + "4" + " 1000000000" + " 62" + " > " + CPU_VSEL);
cpu_list.add("echo " + "3" + " 800000000" + " 58" + " > " + CPU_VSEL);
cpu_list.add("echo " + "2" + " 600000000" + " 48" + " > " + CPU_VSEL);
cpu_list.add("echo " + "1" + " 300000000" + " 33" + " > " + CPU_VSEL);
cpu_list.add("echo " + "0" + " 1000000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1" + " 800000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "2" + " 600000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "3" + " 300000" + " > " + CPU_FREQ_TABLE);
cpu_list.add("echo " + "1000000" + " > " + CPU_MAX_RATE);
cpu_list.add("echo " + "300000" + " > " + CPU_MIN_FREQ);
String[] commands = cpu_list.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
try {
Thread.sleep(350);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
//** store preferences
//** note that this time we put to preferences commands instead of single values,
//** rebuild the commands in the bootService would have been a little expensive
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
preference.edit().putStringSet("cpu_commands", new HashSet<String>(Arrays.asList(commands))).commit();
} catch (Exception e) {
Log.e("Aero", "An Error occurred while setting values", e);
Toast.makeText(getActivity(), "An Error occurred, check logcat!", Toast.LENGTH_SHORT).show();
}
// Start our background refresher Task;
try {
// Only start if not already alive
if (!mRefreshThread.isAlive()) {
mRefreshThread.start();
mRefreshThread.setPriority(Thread.MIN_PRIORITY);
}
} catch (NullPointerException e) {
Log.e("Aero", "Couldn't start Refresher Thread.", e);
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setTitle(R.string.perf_live_oc_uc).show();
return false;
}
});
// Find our ListPreference (governor_settings);
listPref = (ListPreference) root.findPreference("set_governor");
// Just throw in our frequencies;
listPref.setEntries(AeroActivity.shell.getInfoArray(ALL_GOV_AVAILABLE, 0, 0));
listPref.setEntryValues(AeroActivity.shell.getInfoArray(ALL_GOV_AVAILABLE, 0, 0));
listPref.setValue(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
listPref.setSummary(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
listPref.setDialogIcon(R.drawable.cpu_dark);
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
//different listener for each element
listPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
/*
* I need to cast the object to a string first, but setRootInfo
* will take the object instead (its casted again there).
* The intention behind this is, is to solve the slow UI reaction
* and the slow file write process. Otherwise the UI would show the
* value _before_ the value actually was changed.
*/
String a = (String) o;
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
// Change governor for each available CPU;
setGovernor(a);
/*
* Probably the kernel takes a while to update the dictionaries
* and therefore we sleep for a short interval;
*/
try {
Thread.sleep(350);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
listPref.setSummary(AeroActivity.shell.getInfo(CPU_BASE_PATH + 0 + CURRENT_GOV_AVAILABLE));
// store preferences
preference.getEditor().commit();
return true;
}
;
});
max_frequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
/*
* Its pretty much the same like on the governor, except we only deal with numbers
* Also this should make no problems when the user is using different
* Clocks than default...
*/
String a = (String) o;
ArrayList<String> array = new ArrayList<String>();
try {
if (Integer.parseInt(a) < Integer.parseInt(min_frequency.getValue()))
return false;
} catch (NullPointerException e) {
return false;
}
for (int k = 0; k < mNumCpus; k++) {
array.add("echo " + a + " > " + CPU_BASE_PATH + k + CPU_MAX_FREQ);
//** store preferences
preference.getEditor().commit();
}
max_frequency.setSummary(AeroActivity.shell.toMHz(a));
String[] commands = array.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
return true;
};
});
min_frequency.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
String a = (String) o;
ArrayList<String> array = new ArrayList<String>();
try {
if (Integer.parseInt(a) > Integer.parseInt(max_frequency.getValue()))
return false;
} catch (NullPointerException e) {
return false;
}
for (int k = 0; k < mNumCpus; k++) {
array.add("echo " + a + " > " + CPU_BASE_PATH + k + CPU_MIN_FREQ);
//** store preferences
preference.getEditor().commit();
}
min_frequency.setSummary(AeroActivity.shell.toMHz(a));
String[] commands = array.toArray(new String[0]);
AeroActivity.shell.setRootInfo(commands);
return true;
};
});
}
|
diff --git a/com.mobilesorcery.sdk.builder.iphoneos/src/com/mobilesorcery/sdk/builder/iphoneos/IPhoneOSPackager.java b/com.mobilesorcery.sdk.builder.iphoneos/src/com/mobilesorcery/sdk/builder/iphoneos/IPhoneOSPackager.java
index a3384d03..a6711c7c 100644
--- a/com.mobilesorcery.sdk.builder.iphoneos/src/com/mobilesorcery/sdk/builder/iphoneos/IPhoneOSPackager.java
+++ b/com.mobilesorcery.sdk.builder.iphoneos/src/com/mobilesorcery/sdk/builder/iphoneos/IPhoneOSPackager.java
@@ -1,185 +1,185 @@
/* Copyright (C) 2009 Mobile Sorcery AB
This program is free software; you can redistribute it and/or modify it
under the terms of the Eclipse Public License v1.0.
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 Eclipse Public License v1.0 for
more details.
You should have received a copy of the Eclipse Public License v1.0 along
with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html
*/
package com.mobilesorcery.sdk.builder.iphoneos;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.CoreException;
import com.mobilesorcery.sdk.core.IBuildResult;
import com.mobilesorcery.sdk.core.IBuildVariant;
import com.mobilesorcery.sdk.core.IconManager;
import com.mobilesorcery.sdk.core.MoSyncProject;
import com.mobilesorcery.sdk.core.AbstractPackager;
import com.mobilesorcery.sdk.core.DefaultPackager;
import com.mobilesorcery.sdk.core.MoSyncTool;
import com.mobilesorcery.sdk.core.Util;
import com.mobilesorcery.sdk.core.Version;
/**
* Plugin entry point. Is responsible for creating xcode
* project for iphone os devices.
*
* @author Ali Mosavian
*/
public class IPhoneOSPackager
extends AbstractPackager
{
private String m_iphoneBuildLoc;
public IPhoneOSPackager ( )
{
MoSyncTool tool = MoSyncTool.getDefault( );
m_iphoneBuildLoc = tool.getBinary( "iphone-builder" ).toOSString( );
}
/**
* This method is called upon whenever a iphone os package
* is to be built.
*
* @param project
* @param targetProfile Profile information i presume.
* @param buildResult The build result is returned through this parameter.
*
* @throws CoreException Error occurred
*/
public void createPackage ( MoSyncProject project,
IBuildVariant variant,
IBuildResult buildResult )
throws CoreException
{
String appName;
String version;
String company;
IconManager icon;
DefaultPackager intern;
// Was used for printing to console
intern = new DefaultPackager( project,
variant );
//
// Custom parameters
//
appName = intern.getParameters( ).get( DefaultPackager.APP_NAME );
version = intern.getParameters( ).get( DefaultPackager.APP_VERSION );
company = intern.getParameters( ).get( DefaultPackager.APP_VENDOR_NAME );
try
{
String ver = new Version( version ).asCanonicalString( Version.MICRO );
File in = intern.resolveFile( "%runtime-dir%/template" );
File out = intern.resolveFile( "%package-output-dir%/xcode-proj" );
out.mkdirs( );
// Create XCode template
int res = intern.runCommandLineWithRes( m_iphoneBuildLoc,
"generate",
"-project-name",
appName,
"-version",
ver,
"-company-name",
company,
"-input",
in.getAbsolutePath( ),
"-output",
out.getAbsolutePath( ) );
// Did it run successfully?
if ( res != 0 )
return;
// Copy program files to xcode template
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/data_section.bin" ),
new File( out, "data_section.bin" ) );
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/rebuild.build.cpp" ),
new File( out, "Classes/rebuild.build.cpp" ) );
File resources = intern.resolveFile( "%compile-output-dir%/resources" );
if ( resources.exists( ) == true )
{
Util.copyFile( new NullProgressMonitor( ),
resources,
new File( out, "resources" ) );
}
else
{
Util.writeToFile( new File( out, "resources" ), "" );
}
//
// Set icons here
// Note: Always set a 48x48 png at the very least!
//
try
{
File f;
icon = new IconManager( intern,
project.getWrappedProject( )
.getLocation( ).toFile( ) );
// Set PNG icons
if ( icon.hasIcon( "png" ) == true )
{
int[] sizes = {57, 72};
for ( int s : sizes )
{
try
{
f = new File( out, "icon_"+s+"x"+s+".png" );
if ( f.exists( ) == true )
f.delete( );
icon.inject( f, s, s, "png" );
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
}
}
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
buildResult.setBuildResult( out );
}
catch ( Exception e )
{
// Return stack trace in case of error
throw new CoreException( new Status( IStatus.ERROR,
"com.mobilesorcery.builder.iphoneos",
- "Failed to build the xcode template" ));
+ "Failed to build the xcode template. NOTE: Building for iOS devices is only possible from Mac OS X at the moment." ));
}
}
}
| true | true | public void createPackage ( MoSyncProject project,
IBuildVariant variant,
IBuildResult buildResult )
throws CoreException
{
String appName;
String version;
String company;
IconManager icon;
DefaultPackager intern;
// Was used for printing to console
intern = new DefaultPackager( project,
variant );
//
// Custom parameters
//
appName = intern.getParameters( ).get( DefaultPackager.APP_NAME );
version = intern.getParameters( ).get( DefaultPackager.APP_VERSION );
company = intern.getParameters( ).get( DefaultPackager.APP_VENDOR_NAME );
try
{
String ver = new Version( version ).asCanonicalString( Version.MICRO );
File in = intern.resolveFile( "%runtime-dir%/template" );
File out = intern.resolveFile( "%package-output-dir%/xcode-proj" );
out.mkdirs( );
// Create XCode template
int res = intern.runCommandLineWithRes( m_iphoneBuildLoc,
"generate",
"-project-name",
appName,
"-version",
ver,
"-company-name",
company,
"-input",
in.getAbsolutePath( ),
"-output",
out.getAbsolutePath( ) );
// Did it run successfully?
if ( res != 0 )
return;
// Copy program files to xcode template
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/data_section.bin" ),
new File( out, "data_section.bin" ) );
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/rebuild.build.cpp" ),
new File( out, "Classes/rebuild.build.cpp" ) );
File resources = intern.resolveFile( "%compile-output-dir%/resources" );
if ( resources.exists( ) == true )
{
Util.copyFile( new NullProgressMonitor( ),
resources,
new File( out, "resources" ) );
}
else
{
Util.writeToFile( new File( out, "resources" ), "" );
}
//
// Set icons here
// Note: Always set a 48x48 png at the very least!
//
try
{
File f;
icon = new IconManager( intern,
project.getWrappedProject( )
.getLocation( ).toFile( ) );
// Set PNG icons
if ( icon.hasIcon( "png" ) == true )
{
int[] sizes = {57, 72};
for ( int s : sizes )
{
try
{
f = new File( out, "icon_"+s+"x"+s+".png" );
if ( f.exists( ) == true )
f.delete( );
icon.inject( f, s, s, "png" );
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
}
}
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
buildResult.setBuildResult( out );
}
catch ( Exception e )
{
// Return stack trace in case of error
throw new CoreException( new Status( IStatus.ERROR,
"com.mobilesorcery.builder.iphoneos",
"Failed to build the xcode template" ));
}
}
| public void createPackage ( MoSyncProject project,
IBuildVariant variant,
IBuildResult buildResult )
throws CoreException
{
String appName;
String version;
String company;
IconManager icon;
DefaultPackager intern;
// Was used for printing to console
intern = new DefaultPackager( project,
variant );
//
// Custom parameters
//
appName = intern.getParameters( ).get( DefaultPackager.APP_NAME );
version = intern.getParameters( ).get( DefaultPackager.APP_VERSION );
company = intern.getParameters( ).get( DefaultPackager.APP_VENDOR_NAME );
try
{
String ver = new Version( version ).asCanonicalString( Version.MICRO );
File in = intern.resolveFile( "%runtime-dir%/template" );
File out = intern.resolveFile( "%package-output-dir%/xcode-proj" );
out.mkdirs( );
// Create XCode template
int res = intern.runCommandLineWithRes( m_iphoneBuildLoc,
"generate",
"-project-name",
appName,
"-version",
ver,
"-company-name",
company,
"-input",
in.getAbsolutePath( ),
"-output",
out.getAbsolutePath( ) );
// Did it run successfully?
if ( res != 0 )
return;
// Copy program files to xcode template
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/data_section.bin" ),
new File( out, "data_section.bin" ) );
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/rebuild.build.cpp" ),
new File( out, "Classes/rebuild.build.cpp" ) );
File resources = intern.resolveFile( "%compile-output-dir%/resources" );
if ( resources.exists( ) == true )
{
Util.copyFile( new NullProgressMonitor( ),
resources,
new File( out, "resources" ) );
}
else
{
Util.writeToFile( new File( out, "resources" ), "" );
}
//
// Set icons here
// Note: Always set a 48x48 png at the very least!
//
try
{
File f;
icon = new IconManager( intern,
project.getWrappedProject( )
.getLocation( ).toFile( ) );
// Set PNG icons
if ( icon.hasIcon( "png" ) == true )
{
int[] sizes = {57, 72};
for ( int s : sizes )
{
try
{
f = new File( out, "icon_"+s+"x"+s+".png" );
if ( f.exists( ) == true )
f.delete( );
icon.inject( f, s, s, "png" );
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
}
}
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
buildResult.setBuildResult( out );
}
catch ( Exception e )
{
// Return stack trace in case of error
throw new CoreException( new Status( IStatus.ERROR,
"com.mobilesorcery.builder.iphoneos",
"Failed to build the xcode template. NOTE: Building for iOS devices is only possible from Mac OS X at the moment." ));
}
}
|
diff --git a/src/Client/Roster.java b/src/Client/Roster.java
index 4628ca9e..75794bec 100644
--- a/src/Client/Roster.java
+++ b/src/Client/Roster.java
@@ -1,3134 +1,3136 @@
/*
* Roster.java
*
* Created on 6.01.2005, 19:16
* Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.org
*
* 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.
*
* You can also redistribute and/or modify this program under the
* terms of the Psi License, specified in the accompanied COPYING
* file, as published by the Psi Project; either dated January 1st,
* 2005, 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package Client;
import Account.Account;
import Account.AccountSelect;
import Alerts.AlertCustomize;
import Alerts.AlertProfile;
//#ifndef WMUC
import Conference.BookmarkQuery;
import Conference.Bookmarks;
import Conference.ConferenceGroup;
import Conference.MucContact;
import Conference.affiliation.ConferenceQuickPrivelegeModify;
import Conference.ConferenceForm;
//#endif
//#ifdef STATS
//# import Statistic.Stats;
//#endif
import images.MenuIcons;
//#ifdef ARCHIVE
import Archive.ArchiveList;
//#endif
import Menu.RosterItemActions;
import Menu.RosterToolsMenu;
import Menu.SieNatMenu;
//#ifdef CLIENTS_ICONS
import images.ClientsIconsData;
//#endif
import images.RosterIcons;
import Menu.MenuCommand;
import Menu.MyMenu;
//#if FILE_TRANSFER
import PrivacyLists.QuickPrivacy;
import io.file.transfer.TransferDispatcher;
//#endif
import javax.microedition.lcdui.Displayable;
import locale.SR;
import login.LoginListener;
//#ifdef NON_SASL_AUTH
//# import login.NonSASLAuth;
//#endif
//#if SASL_XGOOGLETOKEN
//# import login.GoogleTokenAuth;
//#endif
import login.SASLAuth;
import midlet.BombusMod;
import ui.controls.AlertBox;
import util.StringUtils;
import VCard.VCard;
import VCard.VCardEdit;
import VCard.VCardView;
import com.alsutton.jabber.*;
import com.alsutton.jabber.datablocks.*;
import java.util.*;
import ui.*;
//#ifdef POPUPS
import ui.controls.PopUp;
//#endif
import ui.controls.form.DefForm;
import xmpp.EntityCaps;
import xmpp.XmppError;
//#ifdef CAPTCHA
//# import xmpp.extensions.Captcha;
//#endif
import xmpp.extensions.IqQueryRoster;
//#if SASL_XGOOGLETOKEN
//# import xmpp.extensions.IqGmail;
//#endif
import xmpp.extensions.IqLast;
import xmpp.extensions.IqPing;
import xmpp.extensions.IqVersionReply;
import xmpp.extensions.IqTimeReply;
//#ifdef ADHOC
//# import xmpp.extensions.IQCommands;
//#endif
//#ifdef PEP
//# import xmpp.extensions.PepListener;
//#endif
import xmpp.extensions.RosterXListener;
//#ifdef LIGHT_CONFIG
//# import LightControl.CustomLight;
//#endif
public class Roster
extends DefForm
implements
JabberListener,
Runnable,
LoginListener
{
private MenuCommand cmdActions;//=new MenuCommand(SR.MS_ITEM_ACTIONS, MenuCommand.SCREEN, 1);
private MenuCommand cmdStatus;
private MenuCommand cmdActiveContacts;
private MenuCommand cmdAlert;
//#ifndef WMUC
private MenuCommand cmdConference;
//#endif
//#ifdef ARCHIVE
private MenuCommand cmdArchive;
//#endif
private MenuCommand cmdAdd;
private MenuCommand cmdTools;
private MenuCommand cmdAccount;
private MenuCommand cmdCleanAllMessages;
private MenuCommand cmdInfo;
private MenuCommand cmdMinimize;
private MenuCommand cmdQuit;
public Contact activeContact = null;
public Jid myJid;
public JabberStream theStream;
public int messageCount;
int highliteMessageCount;
public Object transferIcon;
public Vector hContacts;
private Vector vContacts;
public Groups groups;
public Vector bookmarks;
public static MessageEdit me = null;
private StatusList sl;
public int myStatus=cf.loginstatus;
private static String myMessage;
public static int oldStatus=0;
private static int lastOnlineStatus;
public int currentReconnect=0;
public boolean doReconnect=false;
public boolean querysign=false;
//#ifdef AUTOSTATUS
//# private AutoStatusTask autostatus;
//# public static boolean autoAway=false;
//# public static boolean autoXa=false;
//#endif
//#if SASL_XGOOGLETOKEN
//# private String token;
//#endif
//#ifdef JUICK
//# public Vector juickContacts = new Vector();
//# public int indexMainJuickContact = -1; // Т.е. считаем, что жуйкоконтактов нет вообще.
//#endif
public long lastMessageTime=Time.utcTimeMillis();
public static String startTime=Time.dispLocalTime();
private static long notifyReadyTime=System.currentTimeMillis();
private static int blockNotifyEvent=-111;
private int blState=Integer.MAX_VALUE;
private final static int SOUND_FOR_ME=500;
private final static int SOUND_FOR_CONFERENCE=800;
private final static int SOUND_MESSAGE=1000;
private final static int SOUND_CONNECTED=777;
private final static int SOUND_FOR_VIP=100;
private final static int SOUND_COMPOSING=888;
private final static int SOUND_OUTGOING=999;
public Roster() {
super(null, false);
//splash = SplashScreen.getInstance();
sl=StatusList.getInstance();
// setLight(cf.lightState);
MainBar mb=new MainBar(4, null, null, false);
setMainBarItem(mb);
mb.addRAlign();
mb.addElement(null);
mb.addElement(null);
mb.addElement(null); //ft
hContacts=null;
hContacts=new Vector();
groups=null;
groups=new Groups();
vContacts=null;
vContacts=new Vector(); // just for displaying
updateMainBar();
SplashScreen.getInstance().setExit(this);
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
ClientsIconsData.getInstance();
//#endif
enableListWrapping(true);
}
public final void commandState() {
menuCommands.removeAllElements();
int activeType = MenuCommand.SCREEN;
if (phoneManufacturer == Config.NOKIA) {
activeType = MenuCommand.BACK;
}
if (phoneManufacturer == Config.INTENT) {
activeType = MenuCommand.BACK;
}
if (phoneManufacturer == Config.J2ME) {
activeType = MenuCommand.BACK;
}
cmdActions = new MenuCommand(SR.MS_ITEM_ACTIONS, activeType, 2);
cmdStatus = new MenuCommand(SR.MS_STATUS_MENU, MenuCommand.SCREEN, 4);
cmdActiveContacts = new MenuCommand(SR.MS_ACTIVE_CONTACTS, MenuCommand.SCREEN, 3);
cmdAlert = new MenuCommand(SR.MS_ALERT_PROFILE_CMD, MenuCommand.SCREEN, 8);
//#ifndef WMUC
cmdConference = new MenuCommand(SR.MS_CONFERENCE, MenuCommand.SCREEN, 10);
//#endif
//#ifdef ARCHIVE
cmdArchive = new MenuCommand(SR.MS_ARCHIVE, MenuCommand.SCREEN, 10);
//#endif
cmdAdd = new MenuCommand(SR.MS_ADD_CONTACT, MenuCommand.SCREEN, 12);
cmdTools = new MenuCommand(SR.MS_TOOLS, MenuCommand.SCREEN, 14);
cmdAccount = new MenuCommand(SR.MS_ACCOUNT_, MenuCommand.SCREEN, 15);
cmdCleanAllMessages = new MenuCommand(SR.MS_CLEAN_ALL_MESSAGES, MenuCommand.SCREEN, 50);
cmdInfo = new MenuCommand(SR.MS_ABOUT, MenuCommand.SCREEN, 80);
cmdMinimize = new MenuCommand(SR.MS_APP_MINIMIZE, MenuCommand.SCREEN, 90);
cmdQuit = new MenuCommand(SR.MS_APP_QUIT, MenuCommand.SCREEN, 99);
addMenuCommand(cmdStatus);
addMenuCommand(cmdActiveContacts);
//#ifndef WMUC
if (isLoggedIn()) {
addMenuCommand(cmdConference);
}
//#endif
addMenuCommand(cmdAlert);
//#ifdef ARCHIVE
//#ifdef PLUGINS
//# if (sd.Archive)
//#endif
addMenuCommand(cmdArchive);
//#endif
if (isLoggedIn()) {
addMenuCommand(cmdAdd);
}
addMenuCommand(cmdAccount);
addMenuCommand(cmdTools);
addMenuCommand(cmdInfo);
if (cf.allowMinimize) {
addMenuCommand(cmdMinimize);
}
addMenuCommand(cmdCleanAllMessages);
if (phoneManufacturer != Config.NOKIA_9XXX) {
addMenuCommand(cmdQuit);
}
cmdActions.setImg(MenuIcons.ICON_ITEM_ACTIONS);
cmdStatus.setImg(MenuIcons.ICON_STATUS);
cmdActiveContacts.setImg(MenuIcons.ICON_CONFERENCE);
cmdAlert.setImg(MenuIcons.ICON_NOTIFY);
//#ifndef WMUC
cmdConference.setImg(MenuIcons.ICON_CONFERENCE);
//#endif
//#ifdef ARCHIVE
cmdArchive.setImg(MenuIcons.ICON_ARCHIVE);
//#endif
cmdAdd.setImg(MenuIcons.ICON_ADD_CONTACT);
cmdTools.setImg(MenuIcons.ICON_SETTINGS);
cmdAccount.setImg(MenuIcons.ICON_VCARD);
cmdInfo.setImg(MenuIcons.ICON_CHECK_UPD);
if (cf.allowMinimize) {
cmdMinimize.setImg(MenuIcons.ICON_FILEMAN);
}
cmdCleanAllMessages.setImg(MenuIcons.ICON_CLEAN_MESSAGES);
cmdQuit.setImg(MenuIcons.ICON_BUILD_NEW);
}
public void setProgress(String pgs,int percent){
SplashScreen.getInstance().setProgress(pgs, percent);
setRosterMainBar(pgs);
redraw();
}
public void setProgress(int percent){
SplashScreen.getInstance().setProgress(percent);
}
private void setRosterMainBar(String s){
getMainBarItem().setElementAt(s, 3);
}
private int rscaler;
private int rpercent;
public void rosterItemNotify(){
rscaler++;
if (rscaler<4) return;
rscaler=0;
if (rpercent<100) rpercent++;
SplashScreen.getInstance().setProgress(rpercent);
}
// establishing connection process
public void run(){
//#ifdef POPUPS
//if (cf.firstRun) setWobbler(1, (Contact) null, SR.MS_ENTER_SETTINGS);
//#endif
setQuerySign(true);
if (!doReconnect) {
setProgress(25);
resetRoster();
}
try {
Account a=sd.account;
//#if SASL_XGOOGLETOKEN
//# if (a.useGoogleToken()) {
//# setProgress(SR.MS_TOKEN, 30);
//# token=new GoogleTokenAuth(a).responseXGoogleToken();
//# if (token==null) throw new SecurityException("Can't get Google token");
//# }
//#endif
setProgress(SR.MS_CONNECT_TO_+a.getServer(), 30);
theStream= a.openJabberStream();
new Thread(theStream).start();
new Thread( theStream.dispatcher).start();
setProgress(SR.MS_OPENING_STREAM, 40);
theStream.setJabberListener( this );
theStream.initiateStream();
} catch( Exception e ) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
//SplashScreen.getInstance().close();
setProgress(SR.MS_FAILED, 100);
doReconnect=false;
myStatus=Presence.PRESENCE_OFFLINE;
setQuerySign(false);
redraw();
askReconnect(e);
}
}
public void resetRoster() {
synchronized (hContacts) {
hContacts=null;
hContacts=new Vector();
//#ifdef JUICK
//# juickContacts = null;
//# juickContacts = new Vector();
//# indexMainJuickContact = -1;
//#endif
groups=null;
groups=new Groups();
vContacts=null;
vContacts=new Vector(); // just for displaying
bookmarks=null;
}
myJid = new Jid(sd.account.getJid());
updateContact(sd.account.getNick(), myJid.getBareJid(), SR.MS_SELF_CONTACT, "self", false);
}
public void systemGC() {
if (Config.getInstance().widthSystemgc) {
System.gc();
try { Thread.sleep(50); } catch (InterruptedException e){}
}
}
public void errorLog(String s){
if (s==null) return;
Msg m=new Msg(Msg.MESSAGE_TYPE_OUT, "local", "Error", s);
messageStore(selfContact(), m);
}
public void beginPaint() {
itemsList = vContacts;
}
public void setEventIcon(Object icon){
transferIcon=icon;
getMainBarItem().setElementAt(icon, 7);
redraw();
}
public Object getEventIcon() {
if (transferIcon!=null) return transferIcon;
return null;
}
private void updateMainBar(){
int s=querysign?RosterIcons.ICON_PROGRESS_INDEX:myStatus;
int profile=cf.profile;
Object en=(profile>0)? new Integer(profile+RosterIcons.ICON_PROFILE_INDEX+1):null;
MainBar mb=(MainBar) getMainBarItem();
mb.setElementAt((messageCount==0)?null:new Integer(RosterIcons.ICON_MESSAGE_INDEX), 0);
mb.setElementAt((messageCount==0)?null:getHeaderString(),1);
mb.setElementAt(new Integer(s), 2);
mb.setElementAt(en, 5);
if (phoneManufacturer==Config.WINDOWS) {
if (messageCount==0) {
setTitle("BombusMod");
} else {
setTitle("BombusMod "+getHeaderString());
}
}
}
public String getHeaderString() {
return ((highliteMessageCount==0)?" ":" "+highliteMessageCount+"/")+messageCount+" ";
}
boolean countNewMsgs() {
int m=0;
int h=0;
if (hContacts == null)
return false;
synchronized (hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++){
Contact c=(Contact)hContacts.elementAt(i);
m+=c.getNewMsgsCount();
h+=c.getNewHighliteMsgsCount();
}
}
highliteMessageCount=h;
messageCount=m;
updateMainBar();
return (m>0);
}
public void cleanupSearch(){
int index=0;
synchronized (hContacts) {
int j=hContacts.size();
while (index<j) {
if ( ((Contact) hContacts.elementAt(index)).getGroupType()==Groups.TYPE_SEARCH_RESULT ) {
hContacts.removeElementAt(index);
j--;
}
else index++;
}
}
reEnumRoster();
}
public void cmdCleanAllMessages(){
if (messageCount>0) {
new AlertBox(SR.MS_UNREAD_MESSAGES+": "+messageCount, SR.MS_SURE_DELETE) {
public void yes() { cleanAllMessages(); }
public void no() { }
};
} else {
cleanAllMessages();
cleanAllGroups();
}
}
public void cleanAllMessages(){
synchronized (hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++) {
Contact c=(Contact)hContacts.elementAt(i);
try {
c.purge();
} catch (Exception ex) { }
}
}
highliteMessageCount=0;
messageCount=0;
cleanAllGroups();
//reEnumRoster();
redraw();
}
public void cleanAllGroups() {
for (Enumeration e = groups.elements(); e.hasMoreElements();) {
Group group = (Group)e.nextElement();
cleanupGroup(group);
}
reEnumRoster();
}
public void cleanupGroup(Group g){
/*Group g=(Group)getFocusedObject();*/
if (g==null) return;
if (!g.collapsed && !Config.getInstance().autoClean) return;
String groupSelfContact = "";
//#ifndef WMUC
if (g instanceof ConferenceGroup) {
ConferenceGroup cg= (ConferenceGroup) g;
groupSelfContact = cg.selfContact.bareJid;
if (!cg.inRoom) {
int index=0;
boolean removeGroup=true;
synchronized (hContacts) {
int j=hContacts.size();
while (index<j) {
Contact contact=(Contact)hContacts.elementAt(index);
if (contact.group==g) {
if (contact.getNewMsgsCount() == 0) {
contact.msgs=null;
contact=null;
hContacts.removeElementAt(index);
j--;
} else {
removeGroup=false;
index++;
}
} else index++;
}
if (removeGroup) {
groups.removeGroup(g);
} else {
return;
}
}
}// else return;
}
//#endif
int index=0;
synchronized (hContacts) {
int j=hContacts.size();
while (index<j) {
Contact contact=(Contact)hContacts.elementAt(index);
if (contact.group==g) {
if ( contact.origin>Contact.ORIGIN_ROSTERRES
&& contact.status>=Presence.PRESENCE_OFFLINE
&& !contact.haveChatMessages()
&& !contact.bareJid.equals(groupSelfContact)
&& contact.origin!=Contact.ORIGIN_GROUPCHAT) {
contact.msgs=null;
contact=null;
hContacts.removeElementAt(index);
j--;
} else {
index++;
}
}
else index++;
}
//#ifndef WMUC
if (g.getOnlines()==0 && !(g instanceof ConferenceGroup)) {
if (g.type==Groups.TYPE_MUC) groups.removeGroup(g);
}
//#endif
}
}
ReEnumerator reEnumerator=null;
public void reEnumRoster(){
if (reEnumerator==null) reEnumerator=new ReEnumerator();
reEnumerator.queueEnum();
}
public Vector getHContacts() {return hContacts;}
public void updateContact(String nick, String jid, String grpName, String subscr, boolean ask) {
// called only on roster read
int status=Presence.PRESENCE_OFFLINE;
if (subscr.equals("none")) status=Presence.PRESENCE_UNKNOWN;
if (ask) status=Presence.PRESENCE_ASK;
if (subscr.equals("remove")) status=-1;
Jid J=new Jid(jid);
Contact c=findContact(J,false); // search by bare jid
if (c==null) {
c=new Contact(nick, jid, Presence.PRESENCE_OFFLINE, null);
addContact(c);
//#ifdef JUICK
//# addJuickContact(c);
//#endif
}
boolean firstInstance=true; //FS#712 workaround
int index=0;
synchronized (getHContacts()) {
int j=hContacts.size();
for (int i=0; i<j; i++) {
c=(Contact)hContacts.elementAt(i);
if (c.jid.equals(J,false)) {
Group group= (c.jid.isTransport())?
groups.getGroup(Groups.TYPE_TRANSP) :
groups.getGroup(grpName);
if (group==null) {
group=groups.addGroup(grpName, Groups.TYPE_COMMON);
}
if (status<0) {
hContacts.removeElementAt(index);
j--;
//#ifdef JUICK
//# deleteJuickContact(c);
//#endif
continue;
}
c.nick=nick;
c.group=group;
c.subscr=subscr;
c.offline_type=status;
c.ask_subscribe=ask;
if (c.origin==Contact.ORIGIN_PRESENCE) {
if (firstInstance) c.origin=Contact.ORIGIN_ROSTERRES;
else c.origin=Contact.ORIGIN_CLONE;
}
firstInstance=false;
if (querysign==true) {
if (cf.collapsedGroups) {
Group g=c.group;
g.collapsed=true;
}
}
c.setSortKey((nick==null)? jid:nick);
}
index++;
}
}
//if (status<0) removeTrash();
}
private void removeTrash(){
int index=0;
synchronized (getHContacts()) {
int j=hContacts.size();
while (index<j) {
Contact c=(Contact)hContacts.elementAt(index);
if (c.offline_type<0) {
hContacts.removeElementAt(index);
j--;
} else index++;
}
countNewMsgs();
}
}
//#ifndef WMUC
public MucContact findMucContact(Jid jid) {
Contact contact = findContact(jid, true);
if (contact instanceof MucContact) {
return (MucContact) contact;
} else {
if (contact != null) {
// drop buggy bookmark in roster
synchronized (getHContacts()) {
hContacts.removeElement(contact);
}
}
return null;
}
}
public final ConferenceGroup initMuc(String from, String joinPassword){
//#ifdef AUTOSTATUS
//# if (autoAway) {
//# ExtendedStatus es=sl.getStatus(oldStatus);
//# String ms=es.getMessage();
//# sendPresence(oldStatus, ms);
//# autoAway=false;
//# autoXa=false;
//# myStatus=oldStatus;
//#
//# messageActivity();
//# }
//#endif
// muc message
int ri=from.indexOf('@');
int rp=from.indexOf('/');
String room=from.substring(0,ri);
String roomJid=from.substring(0,rp).toLowerCase();
ConferenceGroup grp = groups.getConfGroup(new Jid(roomJid));
// creating room
if (grp==null) // we hasn't joined this room yet
groups.addGroup(grp = new ConferenceGroup(room, new Jid(roomJid)) );
grp.password=joinPassword;
MucContact c = findMucContact( new Jid(roomJid) );
if (c == null) {
c = new MucContact(room, roomJid);
addContact(c);
}
// change nick if already in room
if (c.status==Presence.PRESENCE_ONLINE) return grp;
c.setStatus(Presence.PRESENCE_ONLINE);
c.transport=RosterIcons.ICON_GROUPCHAT_INDEX; //FIXME: убрать хардкод
c.bareJid=from;
c.origin=Contact.ORIGIN_GROUPCHAT;
c.commonPresence=true;
grp.conferenceJoinTime=Time.utcTimeMillis();
grp.confContact=c;
c.group=grp;
String nick=from.substring(rp+1);
// old self-contact
c=grp.selfContact;
// check for existing entry - it may be our old self-contact
// or another contact whose nick we pretend
MucContact foundInRoom = findMucContact( new Jid(from) );
if (foundInRoom!=null) {
c=foundInRoom; //choose found contact instead of old self-contact
}
// if exists (and online - rudimentary check due to line 500)
// rename contact
if (c!=null) if (c.status>=Presence.PRESENCE_OFFLINE) {
c.nick=nick;
c.jid.setJid(from);
c.bareJid=from;
}
// create self-contact if no any candidates found
if (c==null) {
c=new MucContact(nick, from);
addContact(c);
}
grp.selfContact=c;
c.group=grp;
c.origin=Contact.ORIGIN_GC_MYSELF;
grp.collapsed = cf.collapsedGroups;
sort(hContacts);
return grp;
}
public final MucContact mucContact(String from){
// muc message
int ri=from.indexOf('@');
int rp=from.indexOf('/');
String room = from.substring(0,ri);
String roomJid = from.substring(0,rp).toLowerCase();
ConferenceGroup grp = groups.getConfGroup(new Jid(roomJid));
if (grp==null) return null; // we are not joined this room
MucContact c=findMucContact( new Jid(from) );
if (c==null) {
c=new MucContact(from.substring(rp+1), from);
addContact(c);
c.origin=Contact.ORIGIN_GC_MEMBER;
}
c.group=grp;
sort(hContacts);
return c;
}
//#endif
public final Contact getContact(final String jid, boolean createInNIL) {
Jid J=new Jid(jid);
Contact c=findContact(J, true);
if (c!=null)
return c;
c=findContact(J, false);
if (c==null) {
if (!createInNIL) return null;
c=new Contact(null, jid, Presence.PRESENCE_OFFLINE, "none" ); /*"not-in-list"*/
c.bareJid=J.getBareJid();
c.origin=Contact.ORIGIN_PRESENCE;
c.group=groups.getGroup(Groups.TYPE_NOT_IN_LIST);
addContact(c);
} else {
if (c.origin==Contact.ORIGIN_ROSTER) {
c.origin=Contact.ORIGIN_ROSTERRES;
c.setStatus(Presence.PRESENCE_OFFLINE);
c.jid=J;
//System.out.println("add resource");
} else {
c=c.clone(J, Presence.PRESENCE_OFFLINE);
addContact(c);
//System.out.println("cloned");
}
}
sort(hContacts);
return c;
}
//#ifdef POPUPS
public void showContactMessageList(String jid) {
new ContactMessageList(sd.roster.getContact(jid, false));
}
//#endif
public void addContact(Contact c) {
synchronized (getHContacts()) { hContacts.addElement(c); }
}
public final Contact findContact(final Jid j, final boolean compareResources) {
synchronized (getHContacts()) {
int j2=hContacts.size();
for (int i=0; i<j2; i++){
Contact c=(Contact)hContacts.elementAt(i);
if (c.jid.equals(j,compareResources)) return c;
}
}
return null;
}
//#ifdef JUICK
//# /* public Vector getJuickContacts(boolean str) {
//# Vector juickContacts = new Vector();
//# synchronized (hContacts) {
//# for (Enumeration e = hContacts.elements(); e.hasMoreElements();) {
//# Contact c = (Contact) e.nextElement();
//# if (isJuickContact(c))
//# if (str)
//# juickContacts.addElement(c.bareJid);
//# else juickContacts.addElement(c);
//# }
//# }
//# return juickContacts;
//# }*/
//#
//# public Contact getMainJuickContact() {
//# if (indexMainJuickContact > -1)
//# return (Contact) juickContacts.elementAt(indexMainJuickContact);
//# else return null;
//# }
//#
//# /* public void updateMainJuickContact() {
//# System.out.println("1. juickJID: "+cf.juickJID);
//# mainJuickContact = null;
//# int index = -1;
//# if (!cf.juickJID.equals("")) {
//# index = hContacts.indexOf(new Contact("Juick", cf.juickJID, Presence.PRESENCE_OFFLINE, null));
//# System.out.println("index: "+index);
//# if (index < 0) { // Если не нашли, то считаем, что не указан.
//# cf.juickJID = "";
//# }
//# }
//# if (index > -1) {
//# mainJuickContact = (Contact) hContacts.elementAt(index);
//# } else {
//# Vector juickContacts = getJuickContacts(false);
//# if (juickContacts.size() > 0) {
//# mainJuickContact = (Contact) juickContacts.elementAt(0);
//# }
//# }
//# System.out.println("2. juickJID: "+cf.juickJID);
//# }*/
//#
//# public boolean isJuickContact(Contact c) {
//# return c.jid.equalsViaJ2J("[email protected]");
//# }
//#
//# public void addJuickContact(Contact c) {
//# if (isJuickContact(c)) {
//# juickContacts.addElement(c);
//# // Далее урезаный аналог updateMainJuickContact(). Побыстрее него, работает *только* при добавлении контакта.
//# if (isMainJuickContact(c)) {
//# indexMainJuickContact = juickContacts.size() - 1;
//# } else if (indexMainJuickContact < 0) {
//# indexMainJuickContact = 0;
//# }
//# }
//# }
//#
//# public void deleteJuickContact(Contact c) {
//# if (juickContacts.removeElement(c)) {
//# updateMainJuickContact();
//# }
//# }
//#
//# public boolean isMainJuickContact(Contact c) {
//# return c.bareJid.equals(JuickConfig.getJuickJID());
//# }
//#
//# public void updateMainJuickContact() {
//# int size = juickContacts.size();
//# if (size < 1) {
//# indexMainJuickContact = -1;
//# } else if ((size == 1) || (JuickConfig.getJuickJID().equals(""))) {
//# indexMainJuickContact = 0;
//# } else {
//# //indexMainJuickContact = juickContacts.indexOf(new Contact("Juick", juickConfig.getJuickJID(), Presence.PRESENCE_OFFLINE, null));
//# for (int i = 0; i < juickContacts.size(); i++) {
//# if (((Contact) juickContacts.elementAt(i)).bareJid.equals(JuickConfig.getJuickJID()))
//# indexMainJuickContact = i;
//# }
//# if (indexMainJuickContact < 0) {
//# JuickConfig.setJuickJID("", false);
//# indexMainJuickContact = 0; // Можно сделать это присваивание через рекурсию, но вроде пока не надо.
//# }
//# }
//# }
//#endif
public void sendPresence(int newStatus, String message) {
if (newStatus!=Presence.PRESENCE_SAME)
myStatus=newStatus;
//#ifdef AUTOSTATUS
//# messageActivity();
//#endif
if (message!=null)
myMessage=message;
setQuerySign(false);
if (myStatus!=Presence.PRESENCE_OFFLINE) {
lastOnlineStatus=myStatus;
}
// reconnect if disconnected
if (myStatus!=Presence.PRESENCE_OFFLINE && theStream==null ) {
synchronized (getHContacts()) {
doReconnect=(hContacts.size()>1);
}
redraw();
new Thread(this).start();
return;
}
blockNotify(-111,13000);
if (isLoggedIn()) {
if (myStatus==Presence.PRESENCE_OFFLINE && !cf.collapsedGroups)
groups.queryGroupState(false);
// send presence
ExtendedStatus es= sl.getStatus(myStatus);
if (message==null)
myMessage=StringUtils.toExtendedString(es.getMessage());
myMessage=StringUtils.toExtendedString(myMessage);
int myPriority=es.getPriority();
Presence presence = new Presence(myStatus, myPriority, myMessage, sd.account.getNick());
if (!sd.account.isMucOnly() )
theStream.send( presence );
//#ifndef WMUC
reEnumerator = null;
multicastConferencePresence(myStatus, myMessage, myPriority);
//#endif
}
// disconnect
if (myStatus==Presence.PRESENCE_OFFLINE) {
try {
theStream.close(); // sends </stream:stream> and closes socket
} catch (Exception e) { /*e.printStackTrace();*/ }
synchronized(hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++){
((Contact)hContacts.elementAt(i)).setStatus(Presence.PRESENCE_OFFLINE); // keep error & unknown
}
}
theStream=null;
//#ifdef AUTOSTATUS
//# autoAway=false;
//# autoXa=false;
//#endif
systemGC();
}
Contact c=selfContact();
c.setStatus(myStatus);
sort(hContacts);
reEnumRoster();
}
public void sendDirectPresence(int status, String to, JabberDataBlock x) {
if (to==null) {
sendPresence(status, null);
return;
}
ExtendedStatus es= sl.getStatus(status);
myMessage=es.getMessage();
myMessage=StringUtils.toExtendedString(myMessage);
Presence presence = new Presence(status, es.getPriority(), myMessage, sd.account.getNick());
presence.setTo(to);
if (x!=null) presence.addChild(x);
if (theStream!=null) {
theStream.send( presence );
}
}
public void sendDirectPresence(int status, Contact to, JabberDataBlock x) {
sendDirectPresence(status, (to==null)? null: to.getJid(), x);
if (to.jid.isTransport()) blockNotify(-111,10000);
//#ifndef WMUC
if (to instanceof MucContact) ((MucContact)to).commonPresence=false;
//#endif
}
public boolean isLoggedIn() {
if (theStream==null) return false;
return theStream.loggedIn;
}
public Contact selfContact() {
return getContact(myJid.getJid(), false);
}
//#ifndef WMUC
public void multicastConferencePresence(int myStatus, String myMessage, int myPriority) {
//if (!cf.autoJoinConferences) return; //requested to disable
if (myStatus==Presence.PRESENCE_INVISIBLE) return; //block multicasting presence invisible
synchronized (hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++) {
Contact c=(Contact) hContacts.elementAt(i);
if (c.origin!=Contact.ORIGIN_GROUPCHAT) continue;
if (!((MucContact)c).commonPresence) continue; // stop if room left manually
ConferenceGroup confGroup=(ConferenceGroup)c.group;
if (!confGroup.inRoom) continue; // don`t reenter to leaved rooms
Contact myself=confGroup.selfContact;
if (c.status==Presence.PRESENCE_OFFLINE){
ConferenceForm.join(confGroup.name, myself.getJid(), confGroup.password, 20);
continue;
}
Presence presence = new Presence(myStatus, myPriority, myMessage, null);
presence.setTo(myself.bareJid);
theStream.send(presence);
}
}
}
//#endif
public void sendPresence(String to, String type, JabberDataBlock child, boolean conference) { //voffk: todo: check it!
JabberDataBlock presence=new Presence(to, type);
if (child!=null) {
presence.addChild(child);
ExtendedStatus es= sl.getStatus(myStatus);
switch (myStatus){
case Presence.PRESENCE_CHAT: presence.addChild("show", Presence.PRS_CHAT);break;
case Presence.PRESENCE_AWAY: presence.addChild("show", Presence.PRS_AWAY);break;
case Presence.PRESENCE_XA: presence.addChild("show", Presence.PRS_XA);break;
case Presence.PRESENCE_DND: presence.addChild("show", Presence.PRS_DND);break;
}
if (es.getPriority()!=0)
presence.addChild("priority",Integer.toString(es.getPriority()));
if (es.getMessage()!=null)
presence.addChild("status", StringUtils.toExtendedString(es.getMessage()));
} else if (conference) {
ExtendedStatus es= sl.getStatus(Presence.PRESENCE_OFFLINE);
if (es.getMessage()!=null)
presence.addChild("status", StringUtils.toExtendedString(es.getMessage()));
}
theStream.send(presence);
}
public void doSubscribe(Contact c) {
if (c.subscr==null) return;
boolean subscribe =
c.subscr.startsWith("none") ||
c.subscr.startsWith("from");
if (c.ask_subscribe) subscribe=false;
boolean subscribed =
c.subscr.startsWith("none") ||
c.subscr.startsWith("to");
//getMessage(cursor).messageType==Msg.MESSAGE_TYPE_AUTH;
String to=(c.jid.isTransport())?c.getJid():c.bareJid;
if (subscribed) sendPresence(to,"subscribed", null, false);
if (subscribe) sendPresence(to,"subscribe", null, false);
}
public void sendMessage(Contact to, String id, final String body, final String subject , String composingState) {
try {
//#ifndef WMUC
boolean groupchat=to.origin==Contact.ORIGIN_GROUPCHAT;
//#else
//# boolean groupchat=false;
//#endif
//#ifdef AUTOSTATUS
//# if (autoAway) {
//# ExtendedStatus es=sl.getStatus(oldStatus);
//# String ms=es.getMessage();
//# sendPresence(oldStatus, ms);
//# autoAway=false;
//# autoXa=false;
//# myStatus=oldStatus;
//# }
//#endif
Message message = new Message(
to.getJid(),
body,
subject,
groupchat
);
message.setAttribute("id", id);
if (groupchat && body==null && subject==null) return;
if (composingState!=null)
message.addChildNs(composingState, "http://jabber.org/protocol/chatstates");
if (!groupchat)
if (body!=null) if (cf.eventDelivery)
message.addChildNs("request", "urn:xmpp:receipts");
theStream.send( message );
lastMessageTime=Time.utcTimeMillis();
playNotify(SOUND_OUTGOING);
} catch (Exception e) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
}
//#ifdef AUTOSTATUS
//# messageActivity();
//#endif
}
private void sendDeliveryMessage(Contact c, String id) {
if (!cf.eventDelivery) return;
if (myStatus==Presence.PRESENCE_INVISIBLE) return;
Message message=new Message(c.jid.getJid());
// FIXME: no need to send <received /> to forwarded messages
//xep-0184
message.setAttribute("id", id);
message.addChildNs("received", "urn:xmpp:receipts");
theStream.send( message );
}
private Vector vCardQueue;
public void resolveNicknames(String transport){
vCardQueue=null;
vCardQueue=new Vector();
synchronized (hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++){
Contact k=(Contact) hContacts.elementAt(i);
if (k.jid.isTransport())
continue;
int grpType=k.getGroupType();
if (k.jid.getServer().equals(transport) && k.nick==null && (grpType==Groups.TYPE_COMMON || grpType==Groups.TYPE_NO_GROUP))
vCardQueue.addElement(VCard.getQueryVCard(k.getJid(), "nickvc"+k.bareJid));
}
}
setQuerySign(true);
sendVCardReq();
}
private void sendVCardReq(){
querysign=false;
if (vCardQueue!=null) {
if (!vCardQueue.isEmpty()) {
JabberDataBlock req=(JabberDataBlock) vCardQueue.lastElement();
vCardQueue.removeElement(req);
//System.out.println(k.nick);
theStream.send(req);
querysign=true;
}
}
updateMainBar();
}
//#if CHANGE_TRANSPORT
//# public void contactChangeTransport(String srcTransport, String dstTransport){ //voffk
//# setQuerySign(true);
//# int j=hContacts.size();
//# for (int i=0; i<j; i++) {
//# Contact k=(Contact) hContacts.elementAt(i);
//# if (k.jid.isTransport()) continue;
//# int grpType=k.getGroupType();
//# if (k.jid.getServer().equals(srcTransport) &&
//# (grpType==Groups.TYPE_COMMON || grpType==Groups.TYPE_NO_GROUP ||
//# grpType==Groups.TYPE_VISIBLE || grpType==Groups.TYPE_VIP ||
//# grpType==Groups.TYPE_IGNORE)) {
//# String jid=k.getJid();
//# jid=StringUtils.stringReplace(jid, srcTransport, dstTransport);
//# storeContact(jid, k.nick, (!k.group.getName().equals(SR.MS_GENERAL))?(k.group.getName()):"", true); //new contact addition
//# try {
//# Thread.sleep(300);
//# } catch (Exception ex) { }
//# deleteContact(k); //old contact deletion
//# }
//# }
//# setQuerySign(false);
//# }
//#endif
public void loginFailed(String error){
myStatus=Presence.PRESENCE_OFFLINE;
setProgress(SR.MS_LOGIN_FAILED, 100);
errorLog(error);
try {
theStream.close();
} catch (Exception e) {
//e.printStackTrace();
}
theStream=null;
systemGC();
doReconnect=false;
setQuerySign(false);
redraw();
}
public void loginSuccess() {
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType==Config.AWAY_IDLE || cf.autoAwayType==Config.AWAY_MESSAGE) {
//# autostatus=new AutoStatusTask();
//# new Thread(autostatus).start();
//# }
//#
//# if (myStatus<2)
//# messageActivity();
//#endif
theStream.addBlockListener(new EntityCaps());
theStream.addBlockListener(new IqPing());
theStream.addBlockListener(new IqVersionReply());
theStream.startKeepAliveTask(); //enable keep-alive packets
theStream.loggedIn=true;
currentReconnect=0;
theStream.addBlockListener(new IqLast());
theStream.addBlockListener(new IqTimeReply());
theStream.addBlockListener(new RosterXListener());
//#ifdef ADHOC
//# if (cf.adhoc)
//#ifdef PLUGINS
//# if (sd.Adhoc)
//#endif
//# IQCommands.getInstance().addBlockListener();
//#endif
//#ifdef PEP
//# if (cf.sndrcvmood)
//#ifdef PLUGINS
//# if (sd.PEP)
//#endif
//# PepListener.getInstance().addBlockListener();
//#endif
//#if SASL_XGOOGLETOKEN
//# if (StaticData.getInstance().account.isGmail())
//# theStream.addBlockListener(new IqGmail());
//#endif
//#if FILE_TRANSFER
if (cf.fileTransfer) // enable File transfers
//#ifdef PLUGINS
//# if (sd.FileTransfer)
//#endif
TransferDispatcher.getInstance().addBlockListener();
//#endif
//#ifdef CAPTCHA
//# theStream.addBlockListener(new Captcha());
//#endif
playNotify(SOUND_CONNECTED);
if (doReconnect) {
querysign=doReconnect=false;
sendPresence(myStatus, null);
return;
}
//
//theStream.enableRosterNotify(true); //voffk
rpercent=50;
if (sd.account.isMucOnly()) {
setProgress(SR.MS_CONNECTED,100);
show();
try {
reEnumRoster();
} catch (Exception e) { }
setQuerySign(false);
doReconnect=false;
show();
//#ifndef WMUC
//query bookmarks
theStream.addBlockListener(new BookmarkQuery(BookmarkQuery.LOAD));
//#endif
} else {
JabberDataBlock qr=new IqQueryRoster();
setProgress(SR.MS_ROSTER_REQUEST, 49);
theStream.send( qr );
}
//#ifndef WMUC
//query bookmarks
if (bookmarks==null)
theStream.addBlockListener(new BookmarkQuery(BookmarkQuery.LOAD));
//#endif
}
public void bindResource(String myJid) {
Contact self=selfContact();
self.jid=this.myJid=new Jid(myJid);
}
public int blockArrived( JabberDataBlock data ) {
try {
if( data instanceof Iq ) {
String from = data.getAttribute("from");
String type = data.getTypeAttribute();
String id = data.getAttribute("id");
if (id!=null) {
if (id.startsWith("nickvc")) {
if (type.equals("get") || type.equals("set")) return JabberBlockListener.BLOCK_REJECTED;
VCard vc=new VCard(data);//.getNickName();
String nick=vc.getNickName();
Contact c=findContact(new Jid(from), false);
String group=(c.getGroupType()==Groups.TYPE_NO_GROUP)? null: c.group.name;
if (nick!=null) storeContact(from,nick,group, false);
//updateContact( nick, c.rosterJid, group, c.subscr, c.ask_subscribe);
sendVCardReq();
return JabberBlockListener.BLOCK_PROCESSED;
}
if (id.startsWith("getvc")) {
if (type.equals("error")) {
setQuerySign(false);
AlertBox alertBox = new AlertBox(SR.MS_ERROR, XmppError.findInStanza(data).toString()) {
public void yes() {
destroyView();
}
public void no() {
destroyView();
}
};
return JabberBlockListener.BLOCK_PROCESSED;
}
if (type.equals("get") || type.equals("set") ) return JabberBlockListener.BLOCK_REJECTED;
setQuerySign(false);
VCard vcard=new VCard(data);
String jid=id.substring(5);
Contact c=getContact(jid, false); // drop unwanted vcards
if (c!=null) {
c.vcard=vcard;
if (midlet.BombusMod.getInstance().getCurrentDisplayable() instanceof VirtualList) {
// if (c.getGroupType()==Groups.TYPE_SELF) { // Not able to edit VCard if self contact in roster
if (c.getJid().equals(myJid.getJid())) {
new VCardEdit(vcard);
} else {
new VCardView(c);
}
}
} else {
new VCardView(c);
}
return JabberBlockListener.BLOCK_PROCESSED;
}
} // id!=null
if ( type.equals( "result" ) ) {
if (id.equals("getros")) {
//theStream.enableRosterNotify(false); //voffk
processRoster(data);
if(!cf.collapsedGroups)
groups.queryGroupState(true);
setProgress(SR.MS_CONNECTED,100);
reEnumRoster();
querysign=doReconnect=false;
if (cf.loginstatus==5) {
sendPresence(Presence.PRESENCE_INVISIBLE, null);
} else {
sendPresence(cf.loginstatus, null);
}
SplashScreen.getInstance().close();
return JabberBlockListener.BLOCK_PROCESSED;
}
} else if (type.equals("set")) {
if (processRoster(data)) {
theStream.send(new Iq(from, Iq.TYPE_RESULT, id));
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
}
}
} else if( data instanceof Message ) { // If we've received a message
//System.out.println(data.toString());
querysign=false;
Message message = (Message) data;
String from=message.getFrom();
if (myJid.equals(new Jid(from), false)) //Enable forwarding only from self-jids
from=message.getXFrom();
String type=message.getTypeAttribute();
boolean groupchat=false;
int start_me=-1;
String name=null;
if (type!=null)
if (type.equals("groupchat"))
groupchat=true;
if (groupchat) {
start_me=0;
int rp=from.indexOf('/');
name=from.substring(rp+1);
if (rp>0) from=from.substring(0, rp);
}
Contact c=getContact(from, (cf.notInListDropLevel != NotInListFilter.DROP_MESSAGES_PRESENCES || groupchat));
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //not-in-list message dropped
boolean highlite=false;
String body=message.getBody().trim();
String oob=message.getOOB();
if (oob!=null) body+=oob;
if (body.length()==0)
body=null;
String subj=message.getSubject().trim();
if (subj.length()==0)
subj=null;
long tStamp=message.getMessageTime();
int mType=Msg.MESSAGE_TYPE_IN;
if (groupchat) {
if (subj!=null) { // subject
if (body==null)
body=name+" "+SR.MS_HAS_SET_TOPIC_TO+": "+subj;
if (!subj.equals(c.statusString)) {
c.statusString=subj; // adding secondLine to conference
} else {
return JabberBlockListener.BLOCK_PROCESSED;
}
subj=null;
start_me=-1;
highlite=true;
mType=Msg.MESSAGE_TYPE_SUBJ;
}
} else if (type!=null){
if (type.equals("error")) {
body=SR.MS_ERROR_ + XmppError.findInStanza(message).toString();
} else if (type.equals("headline")) {
mType=Msg.MESSAGE_TYPE_HEADLINE;
}
} else {
type="chat";
}
//#ifndef WMUC
try {
JabberDataBlock xmlns=message.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmlns!=null) {
JabberDataBlock invite=xmlns.getChildBlock("invite");
if (invite!=null) {
if (message.getTypeAttribute().equals("error")) {
ConferenceGroup invConf=(ConferenceGroup)groups.getGroup(from);
body=XmppError.decodeStanzaError(message).toString(); /*"error: invites are forbidden"*/
} else {
String inviteReason=invite.getChildBlockText("reason");
String room=from+'/'+sd.account.getNickName();
ConferenceGroup invConf=initMuc(room, xmlns.getChildBlockText("password"));
invConf.confContact.commonPresence=false; //FS#761
if (invConf.selfContact.status==Presence.PRESENCE_OFFLINE)
invConf.confContact.status=Presence.PRESENCE_OFFLINE;
if (inviteReason!=null)
inviteReason=(inviteReason.length()>0)?" ("+inviteReason+")":"";
body=invite.getAttribute("from")+SR.MS_IS_INVITING_YOU+from+inviteReason;
reEnumRoster();
}
}
}
} catch (Exception e) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
}
//#endif
if (name==null) name=c.getName();
// /me
if (body!=null) {
//forme=false;
if (body.startsWith("/me ")) start_me=3;
if (start_me>=0) {
StringBuffer b=new StringBuffer();
//#if NICK_COLORS
b.append("\01");
//#endif
b.append(name);
//#if NICK_COLORS
b.append("\02");
//#endif
if (start_me==0) {
if (!cf.showBalloons) b.insert(0,"<");
b.append("> ");
}
else
b.insert(0,'*');
b.append(body.substring(start_me));
body=b.toString();
b=null;
}
//#ifdef LIGHT_CONFIG
//#ifdef PLUGINS
//# if (StaticData.getInstance().lightConfig)
//#endif
//# if (type.equals("chat")) CustomLight.message();
//#endif
}
//boolean compose=false;
if (type.equals("chat") && myStatus!=Presence.PRESENCE_INVISIBLE) {
if (message.findNamespace("request", "urn:xmpp:receipts")!=null) {
sendDeliveryMessage(c, data.getAttribute("id"));
}
if (message.findNamespace("received", "urn:xmpp:receipts")!=null) {
c.markDelivered(data.getAttribute("id"));
}
if (message.findNamespace("active", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("paused", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("composing", "http://jabber.org/protocol/chatstates")!=null) {
playNotify(SOUND_COMPOSING);
c.acceptComposing=true;
c.showComposing=true;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, SR.MS_COMPOSING_NOTIFY);
//#endif
}
}
redraw();
if (body==null)
return JabberBlockListener.BLOCK_REJECTED;
Msg m=new Msg(mType, from, subj, body);
if (tStamp!=0)
m.dateGmt=tStamp;
//#ifndef WMUC
if (m.body.indexOf(SR.MS_IS_INVITING_YOU)>-1) m.dateGmt=0;
if (groupchat) {
ConferenceGroup mucGrp=(ConferenceGroup)c.group;
if (mucGrp.selfContact.getJid().equals(message.getFrom())) {
m.messageType=Msg.MESSAGE_TYPE_OUT;
m.unread=false;
} else {
//#ifdef LIGHT_CONFIG
//#ifdef PLUGINS
//# if (StaticData.getInstance().lightConfig)
//#endif
//# CustomLight.message();
//#endif
if (m.dateGmt<= ((ConferenceGroup)c.group).conferenceJoinTime)
m.messageType=Msg.MESSAGE_TYPE_HISTORY;
// highliting messages with myNick substring
String myNick=mucGrp.selfContact.getName();
String myNick_=myNick+" ";
String _myNick=" "+myNick;
if (body.indexOf(myNick)>-1) {
if (body.indexOf("> "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+",")>-1)
highlite=true;
else if (body.indexOf(": "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+" ")>-1)
highlite=true;
else if (body.indexOf(", "+myNick)>-1)
highlite=true;
else if (body.endsWith(_myNick))
highlite=true;
else if (body.indexOf(_myNick+"?")>-1)
highlite=true;
else if (body.indexOf(_myNick+"!")>-1)
highlite=true;
else if (body.indexOf(_myNick+".")>-1)
highlite=true;
}
myNick=null; myNick_=null; _myNick=null;
//TODO: custom highliting dictionary
}
m.from=name;
}
//#endif
m.highlite=highlite;
messageStore(c, m);
return JabberBlockListener.BLOCK_PROCESSED;
} else if( data instanceof Presence ) { // If we've received a presence
//System.out.println("presence");
if (myStatus==Presence.PRESENCE_OFFLINE)
return JabberBlockListener.BLOCK_REJECTED;
Presence pr = (Presence) data;
String from=pr.getFrom();
pr.dispathch();
int ti=pr.getTypeIndex();
//PresenceContact(from, ti);
Msg m=new Msg( (ti==Presence.PRESENCE_AUTH || ti==Presence.PRESENCE_AUTH_ASK)?Msg.MESSAGE_TYPE_AUTH:Msg.MESSAGE_TYPE_PRESENCE, from, null, pr.getPresenceTxt());
//#ifndef WMUC
JabberDataBlock xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmuc==null) xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc"); //join errors
if (xmuc!=null) {
try {
MucContact c = mucContact(from);
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) {
if (pr.hasEntityCaps()) {
getClientIcon(c, pr.getEntityNode());
- c.version = pr.getEntityVer();
+ String presenceVer = pr.getEntityVer();
+ if (presenceVer != null)
+ c.version = presenceVer;
}
}
//#endif
String lang=pr.getAttribute("xml:lang");
if (lang!=null) c.lang=lang;
lang=null;
c.statusString=pr.getStatus();
String chatPres=c.processPresence(xmuc, pr);
if (cf.storeConfPresence
|| chatPres.indexOf(SR.MS_WAS_BANNED)>-1
|| chatPres.indexOf(SR.MS_WAS_KICKED)>-1
|| data.getTypeAttribute().equals("error")) {
int rp=from.indexOf('/');
String name=from.substring(rp+1);
Msg chatPresence=new Msg(Msg.MESSAGE_TYPE_PRESENCE, name, null, chatPres );
chatPresence.color=c.getMainColor();
messageStore(getContact(from.substring(0, rp), false), chatPresence);
name=null;
}
chatPres=null;
messageStore(c,m);
c.priority=pr.getPriority();
//System.gc();
//Thread.sleep(20);
} catch (Exception e) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
}
} else {
//#endif
Contact c=null;
if (ti==Presence.PRESENCE_AUTH_ASK) {
//processing subscriptions
if (cf.autoSubscribe==Config.SUBSCR_DROP)
return JabberBlockListener.BLOCK_REJECTED;
if (cf.autoSubscribe==Config.SUBSCR_REJECT) {
//#ifdef DEBUG
//# System.out.print(from);
//# System.out.println(": decline subscription");
//#endif
sendPresence(from, "unsubscribed", null, false);
return JabberBlockListener.BLOCK_PROCESSED;
}
c=getContact(from, true);
messageStore(c, m);
if (cf.autoSubscribe==Config.SUBSCR_AUTO) {
doSubscribe(c);
messageStore(c, new Msg(Msg.MESSAGE_TYPE_AUTH, from, null, SR.MS_AUTH_AUTO));
}
} else {
// processing presences
boolean enNIL = cf.notInListDropLevel > NotInListFilter.DROP_PRESENCES;
c=getContact(from, enNIL);
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //drop not-in-list presence
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
if (pr.getTypeIndex()!=Presence.PRESENCE_ERROR) {
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) if (ti<Presence.PRESENCE_OFFLINE)
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null) {
ClientsIconsData.processData(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
} else if (c.jid.hasResource()) {
ClientsIconsData.processData(c, c.getResource().substring(1));
}
//#endif
JabberDataBlock j2j=pr.findNamespace("x", "j2j:history");
if (j2j!=null) {
if (j2j.getChildBlock("jid")!=null)
c.j2j=j2j.getChildBlock("jid").getAttribute("gateway");
}
j2j=null;
String lang=pr.getAttribute("xml:lang");
//#if DEBUG
//# //System.out.println("xml:lang="+lang); // Very much output!
//#endif
c.lang=lang; lang=null;
c.statusString=pr.getStatus();
}
messageStore(c, m);
}
c.priority=pr.getPriority();
if (ti>=0)
c.setStatus(ti);
if (c.nick==null && c.status<=Presence.PRESENCE_DND) {
JabberDataBlock nick = pr.findNamespace("nick", "http://jabber.org/protocol/nick");
if (nick!=null) c.nick=nick.getText();
}
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT) && notifyReady(-111)) {
//#if USE_ROTATOR
if (cf.notifyBlink)
c.setNewContact();
//#endif
if (cf.notifyPicture) {
if (c.getGroupType()!=Groups.TYPE_TRANSP)
c.setIncoming(Contact.INC_APPEARING);
}
}
if (ti==Presence.PRESENCE_OFFLINE) {
c.setIncoming(Contact.INC_NONE);
c.showComposing=false;
}
if (ti>=0) {
//#ifdef RUNNING_MESSAGE
//# if (ti==Presence.PRESENCE_OFFLINE)
//# setTicker(c, SR.MS_OFFLINE);
//# else if (ti==Presence.PRESENCE_ONLINE)
//# setTicker(c, SR.MS_ONLINE);
//#endif
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT || ti==Presence.PRESENCE_OFFLINE) && (c.getGroupType()!=Groups.TYPE_TRANSP) && (c.getGroupType()!=Groups.TYPE_IGNORE))
playNotify(ti);
}
//#ifndef WMUC
}
//#endif
if (cf.autoClean) {
cleanAllGroups();
sort(hContacts);
}
else {
sort(hContacts);
reEnumRoster();
}
return JabberBlockListener.BLOCK_PROCESSED;
} // if presence
} catch(OutOfMemoryError eom){
System.out.println("error bombusmod\\src\\Client\\Roster.java:12");
} catch( Exception e ) {
//#if DEBUG
//# e.printStackTrace();
//#endif
}
return JabberBlockListener.BLOCK_REJECTED;
}
//#ifdef CLIENTS_ICONS
private void getClientIcon(Contact c, String data) {
ClientsIconsData.processData(c, data);
}
//#endif
boolean processRoster(JabberDataBlock data) {
JabberDataBlock q=data.findNamespace("query", "jabber:iq:roster");
if (q==null) return false;
int type=0;
//verifying from attribute as in RFC3921/7.2
String from=data.getAttribute("from");
if (from!=null) {
Jid fromJid=new Jid(from);
if (fromJid.hasResource())
if (!myJid.equals(fromJid, true)) return false;
}
Vector cont=(q!=null)?q.getChildBlocks():null;
q = null;
if (cont!=null)
{
int j=cont.size();
for (int ii=0; ii<j; ii++){
JabberDataBlock i=(JabberDataBlock)cont.elementAt(ii);
if (i.getTagName().equals("item")) {
String name=i.getAttribute("name");
String jid=i.getAttribute("jid");
String subscr=i.getAttribute("subscription");
boolean ask= (i.getAttribute("ask")!=null);
String group=i.getChildBlockText("group");
if (group.length()==0) group=Groups.COMMON_GROUP;
updateContact(name,jid,group, subscr, ask);
//sort(hContacts);
}
}
}
sort(hContacts);
return true;
}
//#ifdef POPUPS
boolean showWobbler(Contact c) {
if (!cf.popUps)
return false;
if (activeContact==null)
return true;
return(!c.equals(activeContact));
}
//#endif
//#ifdef FILE_TRANSFER
public void addFileQuery(String from, String message) {
Contact c=getContact(from, true);
c.fileQuery=true;
messageStore(c, new Msg(Msg.MESSAGE_TYPE_FILE_REQ, from, SR.MS_FILE, message));
}
//#endif
public void messageStore(Contact c, Msg message) {
if (c==null) return;
c.addMessage(message);
boolean autorespond = false;
//#ifdef RUNNING_MESSAGE
//# if (message.messageType==Msg.MESSAGE_TYPE_IN)
//# setTicker(c, message.body);
//#endif
if (Config.getInstance().widthSystemgc) {
if (cf.ghostMotor) {
systemGC();
}
}
if (countNewMsgs())
reEnumRoster();
if (!message.unread) return;
//TODO: clear unread flag if not-in-list IS HIDDEN
if (c.getGroupType()==Groups.TYPE_IGNORE)
return; // no signalling/focus on ignore
//#ifdef POPUPS
if (cf.popUps)
if (message.messageType==Msg.MESSAGE_TYPE_AUTH && showWobbler(c))
setWobbler(2, c, message.from+"\n"+message.body);
//#endif
if (cf.popupFromMinimized)
BombusMod.getInstance().hideApp(false);
if (cf.autoFocus)
focusToContact(c, false);
if (message.highlite) {
playNotify(SOUND_FOR_ME);
//#ifdef POPUPS
if (showWobbler(c))
setWobbler(2, c, message.body);
//#endif
autorespond = true;
} else if (message.messageType==Msg.MESSAGE_TYPE_IN || message.messageType==Msg.MESSAGE_TYPE_HEADLINE) {
if (c.origin<Contact.ORIGIN_GROUPCHAT) {
//#ifndef WMUC
if (!(c instanceof MucContact))
//#endif
//#ifdef POPUPS
if (showWobbler(c)) {
setWobbler(2, c, c.toString()+": "+message.body);
autorespond = true;
}
//#endif
if (c.group.type==Groups.TYPE_VIP) {
playNotify(SOUND_FOR_VIP);
autorespond = true;
} else {
playNotify(SOUND_MESSAGE);
autorespond = true;
}
}
//#ifndef WMUC
else {
if (c.origin!=Contact.ORIGIN_GROUPCHAT && c instanceof MucContact) {
playNotify(SOUND_MESSAGE); //private message
autorespond = true;
} else {
playNotify(SOUND_FOR_CONFERENCE);
}
}
//#endif
}
if (c.origin==Contact.ORIGIN_GROUPCHAT || c.jid.isTransport() || c.getGroupType()==Groups.TYPE_TRANSP || c.getGroupType()==Groups.TYPE_SEARCH_RESULT || c.getGroupType()==Groups.TYPE_SELF)
autorespond=false;
if (message.messageType!=Msg.MESSAGE_TYPE_IN)
autorespond=false;
if (!c.autoresponded && autorespond) {
ExtendedStatus es=sl.getStatus(myStatus);
if (es.getAutoRespond()) {
//#if DEBUG
//# System.out.println(SR.MS_AUTORESPOND+" "+c.getJid());
//#endif
Message autoMessage = new Message(
c.getJid(),
es.getAutoRespondMessage(),
SR.MS_AUTORESPOND,
false
);
theStream.send( autoMessage );
c.autoresponded=true;
c.addMessage(new Msg(Msg.MESSAGE_TYPE_SYSTEM, "local", SR.MS_AUTORESPOND, ""));
}
}
}
public void blockNotify(int event, long ms) {
if (!notifyReady(-111)) return;
blockNotifyEvent=event;
notifyReadyTime=System.currentTimeMillis()+ms;
}
public boolean notifyReady(int event) {
if ((blockNotifyEvent==event ||
(blockNotifyEvent==-111 && event<=7)) &&
System.currentTimeMillis()<notifyReadyTime) return false;
else return true;
}
public void playNotify(int event) {
if (!notifyReady(event)) return;
//#if DEBUG
//# System.out.println("event: "+event);
//#endif
AlertCustomize ac=AlertCustomize.getInstance();
int volume=ac.soundVol;
int vibraLen=cf.vibraLen;
String type, message;
//boolean flashBackLight=ac.flashBackLight;
switch (event) {
case 0: //online
case 1: //chat
if (cf.notifySound) {
message=ac.soundOnline;
type=ac.soundOnlineType;
} else {
message=null; type=null;
}
vibraLen=0;
//flashBackLight=false;
break;
case 5: //offline
message=ac.soundOffline;
type=ac.soundOfflineType;
vibraLen=0;
//flashBackLight=false;
break;
case SOUND_FOR_VIP: //VIP
message=ac.soundVIP;
type=ac.soundVIPType;
break;
case SOUND_MESSAGE: //message
message=ac.messagesnd;
type=ac.messageSndType;
break;
case SOUND_FOR_CONFERENCE: //conference
message=ac.soundConference;
type=ac.soundConferenceType;
if (ac.vibrateOnlyHighlited)
vibraLen=0;
break;
case SOUND_FOR_ME: //message for you
message=ac.soundForYou;
type=ac.soundForYouType;
break;
case SOUND_CONNECTED: //startup
message=ac.soundStartUp;
type=ac.soundStartUpType;
vibraLen=0;
//flashBackLight=false;
break;
case SOUND_COMPOSING: //composing
message=ac.soundComposing;
type=ac.soundComposingType;
vibraLen=0;
//flashBackLight=false;
break;
case SOUND_OUTGOING: //Outgoing
message=ac.soundOutgoing;
type=ac.soundOutgoingType;
vibraLen=0;
//flashBackLight=false;
break;
default:
message="";
type="none";
vibraLen=0;
//flashBackLight=false;
break;
}
int profile=cf.profile;
EventNotify notify=null;
switch (profile) {
//display fileType soundName volume vibrate
case AlertProfile.ALL: notify=new EventNotify( type, message, volume, vibraLen); break;
case AlertProfile.NONE: notify=new EventNotify( null, null, volume, 0); break;
case AlertProfile.VIBRA: notify=new EventNotify( null, null, volume, vibraLen); break;
case AlertProfile.SOUND: notify=new EventNotify( type, message, volume, 0); break;
}
if (notify!=null) notify.startNotify();
blockNotify(event, 2000);
}
public void focusToContact(final Contact c, boolean force) {
Group g = c.group;
if (g.collapsed) {
g.collapsed = false;
reEnumerator.queueEnum(c, force);
}
int index = vContacts.indexOf(c);
if (index >= 0) {
moveCursorTo(index);
}
}
public void beginConversation() { //todo: verify xmpp version
if (theStream.isXmppV1())
new SASLAuth(sd.account, this, theStream)
//#if SASL_XGOOGLETOKEN
//# .setToken(token)
//#endif
;
//#if NON_SASL_AUTH
//# else new NonSASLAuth(sd.account, this, theStream);
//#endif
}
public void connectionTerminated( Exception e ) {
if( e!=null ) {
askReconnect(e);
} else {
setProgress(SR.MS_DISCONNECTED, 0);
try {
sendPresence(Presence.PRESENCE_OFFLINE, null);
} catch (Exception e2) {
//#if DEBUG
//# e2.printStackTrace();
//#endif
}
}
redraw();
}
private void askReconnect(final Exception e) {
StringBuffer error=new StringBuffer();
if (e.getClass().getName().indexOf("java.lang.Exception")<0) {
error.append(e.getClass().getName());
error.append('\n');
}
if (e.getMessage()!=null)
error.append(e.getMessage());
if (e instanceof SecurityException) {
String errSSL=io.SSLExceptionDecoder.decode(e);
errorLog(errSSL);
return;
}
if (currentReconnect>=cf.reconnectCount) { errorLog(error.toString()); return; }
currentReconnect++;
String topBar="("+currentReconnect+"/"+cf.reconnectCount+") Reconnecting";
errorLog(topBar+"\n"+error.toString());
setRotator();
reconnectWindow.getInstance().startReconnect();
}
public void doReconnect() {
setProgress(SR.MS_DISCONNECTED, 0);
logoff(null);
try {
sendPresence(lastOnlineStatus, null);
} catch (Exception e2) { }
}
public void eventOk(){
super.eventOk();
if (createMsgList()==null) {
cleanupGroup((Group)getFocusedObject());
reEnumRoster();
}
}
public void eventLongOk(){
super.eventLongOk();
//#ifndef WMUC
//#ifdef POPUPS
showInfo();
//#endif
//#endif
}
private Displayable createMsgList(){
Object e=getFocusedObject();
if (e instanceof Contact) {
return new ContactMessageList((Contact)e);
}
return null;
}
protected void keyGreen(){
if (!isLoggedIn()) return;
Displayable pview=createMsgList();
if (pview!=null) {
Contact c=(Contact)getFocusedObject();
me = null; me = new MessageEdit(c, c.msgSuspended);
me.show(this);
c.msgSuspended=null;
}
}
protected void keyClear() {
Object focusedObject = getFocusedObject();
if (isLoggedIn() && (focusedObject instanceof Contact)) {
final Contact c = (Contact) getFocusedObject();
try {
//#ifndef WMUC
boolean isMucContact = (focusedObject instanceof MucContact);
//#else
//# boolean isMucContact = false;
//#endif
focusedObject = null;
if (!isMucContact) {
new AlertBox(SR.MS_DELETE_ASK, c.getNickJid()) {
public void yes() {
deleteContact(c);
}
public void no() {}
};
}
//#ifndef WMUC
else if (isMucContact && c.origin!=Contact.ORIGIN_GROUPCHAT) {
ConferenceGroup mucGrp=(ConferenceGroup)c.group;
if (mucGrp.selfContact.roleCode==MucContact.ROLE_MODERATOR) {
String myNick=mucGrp.selfContact.getName();
MucContact mc=(MucContact) c;
new ConferenceQuickPrivelegeModify(mc, ConferenceQuickPrivelegeModify.KICK,myNick);
}
}
//#endif
} catch (Exception e) { /* NullPointerException */ }
}
}
public void keyPressed(int keyCode){
super.keyPressed(keyCode);
switch (keyCode) {
//#ifdef POPUPS
case KEY_POUND:
if (getItemCount()==0)
return;
showInfo();
return;
//#endif
case KEY_NUM1:
if (cf.collapsedGroups) { //collapse all groups
for (Enumeration e=groups.elements(); e.hasMoreElements();) {
Group grp=(Group)e.nextElement();
grp.collapsed=true;
}
reEnumRoster();
}
break;
case KEY_NUM4:
super.pageLeft();
return;
case KEY_NUM6:
super.pageRight();
return;
//#ifdef AUTOSTATUS
//# case SE_FLIPCLOSE_JP6:
//# if (phoneManufacturer==Config.SONYE) { //workaround for SE JP6 - enabling vibra in closed state
//# midlet.BombusMod.getInstance().setDisplayable(null);
//# try {
//# Thread.sleep(300);
//# } catch (Exception ex) {}
//# midlet.BombusMod.getInstance().setDisplayable(this);
//# keyLock();
//# }
//# break;
//# case SIEMENS_FLIPCLOSE:
//# if (cf.phoneManufacturer == Config.SIEMENS) // verify platform because SIEMENS_FLIPCLOSE maybe MOTOROLA_FLIP
//# keyLock();
//# break;
//# case MOTOROLA_FLIP:
//# if (cf.phoneManufacturer == Config.MOTO)
//# keyLock();
//# break;
//#endif
case KEY_NUM0:
if (getItemCount()==0)
return;
synchronized(hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++){
Contact c=(Contact)hContacts.elementAt(i);
c.setIncoming(Contact.INC_NONE);
c=null;
}
}
redraw();
systemGC();
if (messageCount==0) return;
Object atcursor=getFocusedObject();
Contact c=(atcursor instanceof Contact)?(Contact)atcursor:(Contact)hContacts.firstElement();
Enumeration i=hContacts.elements();
int pass=0; //
while (pass<2) {
if (!i.hasMoreElements()) i=hContacts.elements();
Contact p=(Contact)i.nextElement();
if (pass==1) if (p.getNewMsgsCount()>0) {
focusToContact(p, true);
setRotator();
break;
}
if (p==c) pass++;
}
break;
case KEY_NUM3:
if (getItemCount()==0)
return;
int newpos=searchGroup(-1);
if (newpos>-1) {
moveCursorTo(newpos);
setRotator();
}
break;
case KEY_NUM9:
if (getItemCount()==0)
return;
int newpos2=searchGroup(1);
if (newpos2>-1) {
moveCursorTo(newpos2);
setRotator();
}
break;
case KEY_STAR:
if (cf.ghostMotor) {
// backlight management
blState=(blState==1)? Integer.MAX_VALUE : 1;
midlet.BombusMod.getInstance().getDisplay().flashBacklight(blState);
}
break;
}
//#ifdef LIGHT_CONFIG
//#ifdef PLUGINS
//# if (StaticData.getInstance().lightConfig)
//#endif
//# CustomLight.keyPressed();
//#endif
//#ifdef AUTOSTATUS
//# userActivity();
//#endif
}
//#ifdef AUTOSTATUS
//# private void keyLock() {
//# if (cf.autoAwayType==Config.AWAY_LOCK)
//# if (!autoAway)
//# autostatus.setTimeEvent(cf.autoAwayDelay* 60*1000);
//# }
//#endif
protected void keyRepeated(int keyCode) {
super.keyRepeated(keyCode);
if (kHold==keyCode) return;
kHold=keyCode;
if (keyCode==cf.keyLock) {
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType==Config.AWAY_LOCK) {
//# if (!autoAway) {
//# autoAway=true;
//# if (cf.useMyStatusMessages) {
//# sendPresence(Presence.PRESENCE_AWAY, null);
//# } else {
//# sendPresence(Presence.PRESENCE_AWAY, "Auto Status on KeyLock since %t");
//# }
//# }
//# }
//#endif
new SplashScreen( getMainBarItem(), cf.keyLock);
return;
} else if (keyCode==cf.keyVibra || keyCode==MOTOE680_FMRADIO /* TODO: redefine keyVibra*/) {
// swap profiles
int profile=cf.profile;
cf.profile=(profile==AlertProfile.VIBRA)?cf.lastProfile : AlertProfile.VIBRA;
cf.lastProfile=profile;
updateMainBar();
redraw();
return;
} else if (keyCode==KEY_NUM0) {
cf.showOfflineContacts=!cf.showOfflineContacts;
reEnumRoster();
return;
}
//#ifndef WMUC
else if ((keyCode==KEY_NUM1)&& isLoggedIn()) new Bookmarks(null);
//#endif
else if (keyCode==KEY_NUM3) new ActiveContacts(null);
else if (keyCode==KEY_NUM4) new ConfigForm();
else if (keyCode==KEY_NUM6) {
Config.fullscreen=!Config.fullscreen;
cf.saveToStorage();
VirtualList.fullscreen=Config.fullscreen;
VirtualCanvas.getInstance().setFullScreenMode(Config.fullscreen);
}
else if (keyCode==KEY_NUM7)
new RosterToolsMenu();
else if (keyCode==KEY_NUM9) {
if (cf.allowMinimize)
BombusMod.getInstance().hideApp(true);
else if (phoneManufacturer==Config.SIEMENS2)
new SieNatMenu( this); /*
try {
//SIEMENS: MYMENU call. Possible Main Menu for capable phones
BombusMod.getInstance().platformRequest("native:ELSE_STR_MYMENU");
} catch (Exception e) { } */
else if (phoneManufacturer==Config.SIEMENS)//SIEMENS-NSG: MYMENU call. Possible Native Menu for capable phones
try {
BombusMod.getInstance().platformRequest("native:NAT_MAIN_MENU");
} catch (Exception e) { }
}
//#ifdef LIGHT_CONFIG
//#ifdef PLUGINS
//# if (StaticData.getInstance().lightConfig)
//#endif
//# CustomLight.keyPressed();
//#endif
}
//#ifdef AUTOSTATUS
//# private void userActivity() {
//# if (autostatus==null) return;
//#
//# if (cf.autoAwayType==Config.AWAY_IDLE) {
//# if (!autoAway) {
//# autostatus.setTimeEvent(cf.autoAwayDelay* 60*1000);
//# return;
//# }
//# } else {
//# return;
//# }
//# autostatus.setTimeEvent(0);
//# setAutoStatus(Presence.PRESENCE_ONLINE);
//# }
//#
//# public final void messageActivity() {
//# if (autostatus==null) return;
//#
//# if (cf.autoAwayType==Config.AWAY_MESSAGE) {
//# //System.out.println("messageActivity "+myStatus.getImageIndex());
//# if (myStatus<2)
//# autostatus.setTimeEvent(cf.autoAwayDelay* 60*1000);
//# else if (!autoAway)
//# autostatus.setTimeEvent(0);
//# }
//# }
//#endif
//#ifdef POPUPS
public void showInfo() {
if (getFocusedObject()==null)
return;
try {
PopUp.getInstance().next();
if (getFocusedObject() instanceof Group
//#ifndef WMUC
|| getFocusedObject() instanceof ConferenceGroup
//#endif
)
return;
setWobbler(1, (Contact) null, null);
} catch (Exception e) { }
}
public void setWobbler(int type, Contact contact, String info) {
if (info==null) {
StringBuffer mess=new StringBuffer();
boolean isContact=(getFocusedObject() instanceof Contact);
Contact cntact=(Contact)getFocusedObject();
//#ifndef WMUC
boolean isMucContact=(getFocusedObject() instanceof MucContact);
if (isMucContact) {
MucContact mucContact=(MucContact)getFocusedObject();
if (mucContact.origin!=Contact.ORIGIN_GROUPCHAT){
mess.append((mucContact.realJid==null)?"":"jid: "+mucContact.realJid+"\n");
if (mucContact.affiliationCode>MucContact.AFFILIATION_NONE)
mess.append(MucContact.getAffiliationLocale(mucContact.affiliationCode));
if (!(mucContact.roleCode==MucContact.ROLE_PARTICIPANT && mucContact.affiliationCode==MucContact.AFFILIATION_MEMBER)) {
if (mucContact.affiliationCode>MucContact.AFFILIATION_NONE)
mess.append(SR.MS_AND);
mess.append(MucContact.getRoleLocale(mucContact.roleCode));
}
}
} else {
//#endif
mess.append("jid: ")
.append(cntact.bareJid)
.append(cntact.jid.getResource())
.append("\n")
.append(SR.MS_SUBSCRIPTION)
.append(": ")
.append(cntact.subscr);
//#ifdef PEP
//# if (cntact.hasMood()) {
//# mess.append("\n")
//# .append(SR.MS_USERMOOD)
//# .append(": ")
//# .append(cntact.getMoodString());
//# }
//#ifdef PEP_ACTIVITY
//# if (cntact.hasActivity()) {
//# mess.append("\n").append(SR.MS_USERACTIVITY).append(": ").append(cntact.activity);
//# }
//#endif
//#ifdef PEP_LOCATION
//# if (cntact.hasLocation()) {
//# mess.append("\n").append(SR.MS_USERLOCATION).append(": ").append(cntact.location);
//# }
//#endif
//#
//#ifdef PEP_TUNE
//# if (cntact.pepTune) {
//# mess.append("\n").append(SR.MS_USERTUNE);
//# if (!cntact.pepTuneText.equals("")) {
//# mess.append(": ").append(cntact.pepTuneText);
//# }
//# }
//#endif
//#endif
//#ifndef WMUC
}
//#endif
if (cntact.origin!=Contact.ORIGIN_GROUPCHAT){
mess.append((cntact.j2j!=null)?"\nJ2J: "+cntact.j2j:"");
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (cf.showClientIcon)
//#endif
if (cntact.client>-1) {
mess.append("\n")
.append(SR.MS_USE)
.append(": ")
.append(cntact.clientName);
}
//#endif
if (cntact.version!=null) {
mess.append("\n")
.append(SR.MS_VERSION)
.append(": ")
.append(cntact.version);
}
if (cntact.lang!=null) {
mess.append("\n")
.append(SR.MS_LANGUAGE)
.append(": ")
.append(cntact.lang);
}
}
if (cntact.statusString!=null) {
if (cntact.origin!=Contact.ORIGIN_GROUPCHAT){
mess.append("\n")
.append(SR.MS_STATUS)
.append(": ");
}
mess.append(cntact.statusString);
if (cntact.priority!=0) {
mess.append(" [")
.append(cntact.priority)
.append("]");
}
}
setWobble(1, null, mess.toString());
mess=null;
} else {
setWobble(type, contact.getJid(), info);
}
redraw();
}
//#endif
public void logoff(String mess){
if (isLoggedIn()) {
try {
if (mess==null) mess=sl.getStatus(Presence.PRESENCE_OFFLINE).getMessage();
sendPresence(Presence.PRESENCE_OFFLINE, mess);
} catch (Exception e) { }
}
//#ifdef STATS
//#ifdef PLUGINS
//# if (sd.Stats)
//#endif
//# Stats.getInstance().saveToStorage(false);
//#endif
}
public void quit() {
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType!=Config.AWAY_OFF) {
//# try {
//# autostatus.destroyTask();
//# } catch (Exception ex) {}
//# }
//#endif
logoff(null);
try {
Thread.sleep(250L);
} catch (InterruptedException ex) {
//#ifdef DEBUG
//# ex.printStackTrace();
//#endif
}
BombusMod.getInstance().notifyDestroyed();
}
public void menuAction(MenuCommand c, VirtualList d){
//#ifdef AUTOSTATUS
//# userActivity();
//#endif
if (c==cmdActions) { cmdActions(); }
else if (c==cmdMinimize) { cmdMinimize(); }
else if (c==cmdActiveContacts) { cmdActiveContacts(); }
else if (c==cmdAccount){ cmdAccount(); }
else if (c==cmdStatus) { cmdStatus(); }
else if (c==cmdAlert) { cmdAlert(); }
//#ifdef ARCHIVE
else if (c==cmdArchive) { cmdArchive(); }
//#endif
else if (c==cmdInfo) { cmdInfo(); }
else if (c==cmdTools) { cmdTools(); }
else if (c==cmdCleanAllMessages) { cmdCleanAllMessages(); }
//#ifndef WMUC
else if (c==cmdConference) { cmdConference(); }
//#endif
else if (c==cmdQuit) { cmdQuit(); }
else if (c==cmdAdd) { cmdAdd(); }
}
//menu actions
public void cmdQuit() {
if (cf.queryExit) {
new AlertBox(SR.MS_QUIT_ASK, SR.MS_SURE_QUIT) {
public void yes() { quit(); }
public void no() { }
};
} else {
quit();
}
}
public void cmdMinimize() { BombusMod.getInstance().hideApp(true); }
public void cmdActiveContacts() { new ActiveContacts(null); }
public void cmdAccount(){ new AccountSelect( false); }
public void cmdStatus() { currentReconnect=0; new StatusSelect(null); }
public void cmdAlert() { new AlertProfile(); }
//#ifdef ARCHIVE
public void cmdArchive() { new ArchiveList(-1, 1, null); }
//#endif
public void cmdInfo() { new Info.InfoWindow(); }
public void cmdTools() { new RosterToolsMenu(); }
//#ifdef POPUPS
public void cmdClearPopups() { PopUp.getInstance().clear(); }
//#endif
//#ifndef WMUC
public void cmdConference() { if (isLoggedIn()) new Bookmarks(null); }
//#endif
public void cmdActions() {
if (isLoggedIn()) {
try {
new RosterItemActions(getFocusedObject(), -1);
} catch (Exception ex) {}
}
}
public void cmdAdd() {
if (isLoggedIn()) {
Object o=getFocusedObject();
Contact cn=null;
if (o instanceof Contact) {
cn=(Contact)o;
if (cn.getGroupType()!=Groups.TYPE_NOT_IN_LIST && cn.getGroupType()!=Groups.TYPE_SEARCH_RESULT)
cn=null;
}
//#ifndef WMUC
if (o instanceof MucContact)
cn=(Contact)o;
//#endif
new ContactEdit(cn);
}
}
//#ifndef WMUC
public void reEnterRoom(Group group) {
ConferenceGroup confGroup=(ConferenceGroup)group;
String confJid=confGroup.selfContact.getJid();
String name=confGroup.name;
new ConferenceForm(name, confJid, confGroup.password, false);
}
public void leaveRoom(Group group){
ConferenceGroup confGroup=(ConferenceGroup)group;
Contact myself=confGroup.selfContact;
confGroup.confContact.commonPresence=false; //disable reenter after reconnect
sendPresence(myself.getJid(), "unavailable", null, true);
confGroup.inRoom=false;
roomOffline(group);
}
public void roomOffline(final Group group) {
int j=hContacts.size();
for (int i=0; i<j; i++) {
Contact contact=(Contact)hContacts.elementAt(i);
if (contact.group==group) {
contact.setStatus(Presence.PRESENCE_OFFLINE);
}
}
}
//#endif
protected void showNotify() {
super.showNotify();
countNewMsgs();
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType==Config.AWAY_IDLE) {
//# if (autostatus == null) // Issue 107
//# autostatus = new AutoStatusTask();
//# new Thread(autostatus).start();
//# if (!autostatus.isAwayTimerSet())
//# if (!autoAway)
//# autostatus.setTimeEvent(cf.autoAwayDelay* 60*1000);
//# }
//#endif
}
protected void hideNotify() {
super.hideNotify();
//#ifdef AUTOSTATUS
//# if (cf.autoAwayType==Config.AWAY_IDLE)
//# if (kHold==0)
//# autostatus.setTimeEvent(0);
//#endif
}
private int searchGroup(int direction){
int newpos=-1;
synchronized (vContacts) {
int size=vContacts.size();
int pos=cursor;
int count=size;
try {
while (count>0) {
pos+=direction;
if (pos<0) pos=size-1;
if (pos>=size) pos=0;
if (vContacts.elementAt(pos) instanceof Group) break;
}
} catch (Exception e) { }
newpos=pos;
}
return newpos;
}
public void searchActiveContact(int direction){
Vector activeContacts=new Vector();
int nowContact = -1, contacts=-1, currentContact=-1;
synchronized (hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++){
Contact c=(Contact)hContacts.elementAt(i);
if (c.active()) {
activeContacts.addElement(c);
contacts=contacts+1;
if (c==activeContact) {
nowContact=contacts;
currentContact=contacts;
}
}
}
}
int size=activeContacts.size();
if (size==0) return;
try {
nowContact+=direction;
if (nowContact<0) nowContact=size-1;
if (nowContact>=size) nowContact=0;
if (currentContact==nowContact) return;
Contact c=(Contact)activeContacts.elementAt(nowContact);
new ContactMessageList(c);
} catch (Exception e) { }
}
public void deleteContact(Contact c) {
synchronized (hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++) {
Contact c2=(Contact)hContacts. elementAt(i);
if (c.jid.equals(c2.jid,false)) {
c2.setStatus(Presence.PRESENCE_TRASH);
c2.offline_type=Presence.PRESENCE_TRASH;
}
}
if (c.jid.isTransport()) {
// double-check for empty jid or our server jid
if (c.bareJid.equals("")) return;
if (c.bareJid.equals(myJid.getServer())) return;
// automatically remove registration
JabberDataBlock unreg = new Iq(c.bareJid, Iq.TYPE_SET, "unreg" + System.currentTimeMillis());
JabberDataBlock query = unreg.addChildNs("query", "jabber:iq:register");
query.addChild("remove", null);
theStream.send(unreg);
}
if (c.getGroupType()==Groups.TYPE_NOT_IN_LIST) {
hContacts.removeElement(c);
countNewMsgs();
reEnumRoster();
} else {
theStream.send(new IqQueryRoster(c.bareJid,null,null,"remove"));
sendPresence(c.bareJid, "unsubscribe", null, false);
sendPresence(c.bareJid, "unsubscribed", null, false);
}
}
}
public void setQuerySign(boolean requestState) {
querysign=requestState;
updateMainBar();
}
public void storeContact(String jid, String name, String group, boolean askSubscribe){
theStream.send(new IqQueryRoster(jid, name, group, null));
if (askSubscribe) theStream.send(new Presence(jid,"subscribe"));
}
public void loginMessage(String msg, int pos) {
setProgress(msg, pos);
}
//#ifdef AUTOSTATUS
//# public void setAutoAway() {
//# if (!autoAway) {
//# oldStatus=myStatus;
//# if (myStatus==0 || myStatus==1) {
//# autoAway=true;
//# if (cf.useMyStatusMessages) {
//# sendPresence(Presence.PRESENCE_AWAY, null);
//# } else {
//# sendPresence(Presence.PRESENCE_AWAY, SR.MS_AUTO_AWAY);
//# }
//# }
//# }
//# }
//#
//# public void setAutoXa() {
//# if (autoAway && !autoXa) {
//# autoXa=true;
//# if (cf.useMyStatusMessages) {
//# sendPresence(Presence.PRESENCE_XA, null);
//# } else {
//# sendPresence(Presence.PRESENCE_XA, SR.MS_AUTO_XA);
//# }
//# }
//# }
//#
//# public void setAutoStatus(int status) {
//# if (!isLoggedIn())
//# return;
//# if (status==Presence.PRESENCE_ONLINE && autoAway) {
//# autoAway=false;
//# autoXa=false;
//# sendPresence(Presence.PRESENCE_ONLINE, null);
//# return;
//# }
//# if (status!=Presence.PRESENCE_ONLINE && myStatus==Presence.PRESENCE_ONLINE && !autoAway) {
//# autoAway=true;
//# if (cf.useMyStatusMessages) {
//# sendPresence(Presence.PRESENCE_AWAY, null);
//# } else {
//# sendPresence(Presence.PRESENCE_AWAY, "Auto Status on KeyLock since %t");
//# }
//# }
//# }
//#endif
public void deleteGroup(Group deleteGroup) {
synchronized (hContacts) {
int j=hContacts.size();
for (int i=0; i<j; i++){
Contact cr=(Contact)hContacts.elementAt(i);
if (cr.group==deleteGroup)
deleteContact(cr);
}
}
}
public void destroyView() {
}
public void showMenu() {
commandState();
new MyMenu( this, this, SR.MS_MAIN_MENU, MenuIcons.getInstance(), menuCommands);
}
public String touchRightCommand(){ return (Config.getInstance().oldSE)?SR.MS_MENU:SR.MS_ACTION; }
public String touchLeftCommand(){ return (Config.getInstance().oldSE)?SR.MS_ACTION:SR.MS_MENU; }
public void touchRightPressed(){ if (Config.getInstance().oldSE) showMenu(); else cmdActions(); }
public void touchLeftPressed(){ if (Config.getInstance().oldSE) cmdActions(); else showMenu(); }
public void captionPressed() {new ActiveContacts(null);}
//#ifdef RUNNING_MESSAGE
//# void setTicker(Contact c, String message) {
//# if (cf.notifyWhenMessageType) {
//# if (me!=null)
//# if (me.to==c)
//# me.setMyTicker(message);
//# }
//# }
//#endif
private class ReEnumerator implements Runnable{
Thread thread=null;
int pendingRepaints=0;
boolean force;
Object desiredFocus;
public synchronized void queueEnum(Object focusTo, boolean force) {
desiredFocus=focusTo;
this.force=force;
queueEnum();
}
synchronized public void queueEnum() {
pendingRepaints++;
if (thread==null || thread.isAlive() == false) (thread=new Thread(this)).start();
}
public synchronized void run() {
//#ifdef PRIVACY
boolean needUpdatePrivacy = false;
//#endif
//try {
while (pendingRepaints > 0) {
pendingRepaints = 0;
int locCursor = cursor;
Object focused = (desiredFocus == null) ? getFocusedObject() : desiredFocus;
desiredFocus = null;
Vector tContacts = new Vector(vContacts.size());
groups.resetCounters();
synchronized (hContacts) {
int j = hContacts.size();
for (int i = 0; i < j; i++) {
Contact c = (Contact) hContacts.elementAt(i);
Group grp = c.group;
if (c.group != null) {
grp.addContact(c);
//#ifdef PRIVACY
//#ifdef PLUGINS
//# if (sd.Privacy) {
//#endif
if (QuickPrivacy.groupsList == null) {
QuickPrivacy.groupsList = new Vector();
}
if (c.group.type != Groups.TYPE_MUC) {
if (!QuickPrivacy.groupsList.contains(c.group.name)) {
QuickPrivacy.groupsList.addElement(c.group.name);
needUpdatePrivacy = true;
}
}
//#ifdef PLUGINS
//# }
//#endif
//#endif
}
}
}
//#ifdef PRIVACY
//#ifdef PLUGINS
//# if (sd.Privacy) {
//#endif
if (needUpdatePrivacy)
new QuickPrivacy().updateQuickPrivacyList();
//#ifdef PLUGINS
//# }
//#endif
//#endif
// self-contact group
Group selfContactGroup = groups.getGroup(Groups.TYPE_SELF);
selfContactGroup.visible = (cf.selfContact || selfContactGroup.tonlines > 1 || selfContactGroup.unreadMessages > 0);
// hiddens
groups.getGroup(Groups.TYPE_IGNORE).visible = cf.ignore;
// transports
Group transpGroup = groups.getGroup(Groups.TYPE_TRANSP);
transpGroup.visible = (cf.showTransports || transpGroup.unreadMessages > 0);
// adding groups
for (int i = 0; i < groups.getCount(); i++) {
groups.addToVector(tContacts, i);
}
vContacts = tContacts;
tContacts = null;
StringBuffer onl = new StringBuffer().append("(").append(groups.getRosterOnline()).append("/").append(groups.getRosterContacts()).append(")");
setRosterMainBar(onl.toString());
onl = null;
if (cursor < 0) {
cursor = 0;
}
if (locCursor == cursor && focused != null) {
itemsList = vContacts;
int c = vContacts.indexOf(focused);
if (c >= 0) {
moveCursorTo(c);
}
force = false;
}
focusedItem(cursor);
redraw();
}
//} catch (Exception e) {
//#ifdef DEBUG
//# //e.printStackTrace();
//#endif
//}
//thread=null;
systemGC();
}
}
}
| true | true | public int blockArrived( JabberDataBlock data ) {
try {
if( data instanceof Iq ) {
String from = data.getAttribute("from");
String type = data.getTypeAttribute();
String id = data.getAttribute("id");
if (id!=null) {
if (id.startsWith("nickvc")) {
if (type.equals("get") || type.equals("set")) return JabberBlockListener.BLOCK_REJECTED;
VCard vc=new VCard(data);//.getNickName();
String nick=vc.getNickName();
Contact c=findContact(new Jid(from), false);
String group=(c.getGroupType()==Groups.TYPE_NO_GROUP)? null: c.group.name;
if (nick!=null) storeContact(from,nick,group, false);
//updateContact( nick, c.rosterJid, group, c.subscr, c.ask_subscribe);
sendVCardReq();
return JabberBlockListener.BLOCK_PROCESSED;
}
if (id.startsWith("getvc")) {
if (type.equals("error")) {
setQuerySign(false);
AlertBox alertBox = new AlertBox(SR.MS_ERROR, XmppError.findInStanza(data).toString()) {
public void yes() {
destroyView();
}
public void no() {
destroyView();
}
};
return JabberBlockListener.BLOCK_PROCESSED;
}
if (type.equals("get") || type.equals("set") ) return JabberBlockListener.BLOCK_REJECTED;
setQuerySign(false);
VCard vcard=new VCard(data);
String jid=id.substring(5);
Contact c=getContact(jid, false); // drop unwanted vcards
if (c!=null) {
c.vcard=vcard;
if (midlet.BombusMod.getInstance().getCurrentDisplayable() instanceof VirtualList) {
// if (c.getGroupType()==Groups.TYPE_SELF) { // Not able to edit VCard if self contact in roster
if (c.getJid().equals(myJid.getJid())) {
new VCardEdit(vcard);
} else {
new VCardView(c);
}
}
} else {
new VCardView(c);
}
return JabberBlockListener.BLOCK_PROCESSED;
}
} // id!=null
if ( type.equals( "result" ) ) {
if (id.equals("getros")) {
//theStream.enableRosterNotify(false); //voffk
processRoster(data);
if(!cf.collapsedGroups)
groups.queryGroupState(true);
setProgress(SR.MS_CONNECTED,100);
reEnumRoster();
querysign=doReconnect=false;
if (cf.loginstatus==5) {
sendPresence(Presence.PRESENCE_INVISIBLE, null);
} else {
sendPresence(cf.loginstatus, null);
}
SplashScreen.getInstance().close();
return JabberBlockListener.BLOCK_PROCESSED;
}
} else if (type.equals("set")) {
if (processRoster(data)) {
theStream.send(new Iq(from, Iq.TYPE_RESULT, id));
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
}
}
} else if( data instanceof Message ) { // If we've received a message
//System.out.println(data.toString());
querysign=false;
Message message = (Message) data;
String from=message.getFrom();
if (myJid.equals(new Jid(from), false)) //Enable forwarding only from self-jids
from=message.getXFrom();
String type=message.getTypeAttribute();
boolean groupchat=false;
int start_me=-1;
String name=null;
if (type!=null)
if (type.equals("groupchat"))
groupchat=true;
if (groupchat) {
start_me=0;
int rp=from.indexOf('/');
name=from.substring(rp+1);
if (rp>0) from=from.substring(0, rp);
}
Contact c=getContact(from, (cf.notInListDropLevel != NotInListFilter.DROP_MESSAGES_PRESENCES || groupchat));
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //not-in-list message dropped
boolean highlite=false;
String body=message.getBody().trim();
String oob=message.getOOB();
if (oob!=null) body+=oob;
if (body.length()==0)
body=null;
String subj=message.getSubject().trim();
if (subj.length()==0)
subj=null;
long tStamp=message.getMessageTime();
int mType=Msg.MESSAGE_TYPE_IN;
if (groupchat) {
if (subj!=null) { // subject
if (body==null)
body=name+" "+SR.MS_HAS_SET_TOPIC_TO+": "+subj;
if (!subj.equals(c.statusString)) {
c.statusString=subj; // adding secondLine to conference
} else {
return JabberBlockListener.BLOCK_PROCESSED;
}
subj=null;
start_me=-1;
highlite=true;
mType=Msg.MESSAGE_TYPE_SUBJ;
}
} else if (type!=null){
if (type.equals("error")) {
body=SR.MS_ERROR_ + XmppError.findInStanza(message).toString();
} else if (type.equals("headline")) {
mType=Msg.MESSAGE_TYPE_HEADLINE;
}
} else {
type="chat";
}
//#ifndef WMUC
try {
JabberDataBlock xmlns=message.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmlns!=null) {
JabberDataBlock invite=xmlns.getChildBlock("invite");
if (invite!=null) {
if (message.getTypeAttribute().equals("error")) {
ConferenceGroup invConf=(ConferenceGroup)groups.getGroup(from);
body=XmppError.decodeStanzaError(message).toString(); /*"error: invites are forbidden"*/
} else {
String inviteReason=invite.getChildBlockText("reason");
String room=from+'/'+sd.account.getNickName();
ConferenceGroup invConf=initMuc(room, xmlns.getChildBlockText("password"));
invConf.confContact.commonPresence=false; //FS#761
if (invConf.selfContact.status==Presence.PRESENCE_OFFLINE)
invConf.confContact.status=Presence.PRESENCE_OFFLINE;
if (inviteReason!=null)
inviteReason=(inviteReason.length()>0)?" ("+inviteReason+")":"";
body=invite.getAttribute("from")+SR.MS_IS_INVITING_YOU+from+inviteReason;
reEnumRoster();
}
}
}
} catch (Exception e) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
}
//#endif
if (name==null) name=c.getName();
// /me
if (body!=null) {
//forme=false;
if (body.startsWith("/me ")) start_me=3;
if (start_me>=0) {
StringBuffer b=new StringBuffer();
//#if NICK_COLORS
b.append("\01");
//#endif
b.append(name);
//#if NICK_COLORS
b.append("\02");
//#endif
if (start_me==0) {
if (!cf.showBalloons) b.insert(0,"<");
b.append("> ");
}
else
b.insert(0,'*');
b.append(body.substring(start_me));
body=b.toString();
b=null;
}
//#ifdef LIGHT_CONFIG
//#ifdef PLUGINS
//# if (StaticData.getInstance().lightConfig)
//#endif
//# if (type.equals("chat")) CustomLight.message();
//#endif
}
//boolean compose=false;
if (type.equals("chat") && myStatus!=Presence.PRESENCE_INVISIBLE) {
if (message.findNamespace("request", "urn:xmpp:receipts")!=null) {
sendDeliveryMessage(c, data.getAttribute("id"));
}
if (message.findNamespace("received", "urn:xmpp:receipts")!=null) {
c.markDelivered(data.getAttribute("id"));
}
if (message.findNamespace("active", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("paused", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("composing", "http://jabber.org/protocol/chatstates")!=null) {
playNotify(SOUND_COMPOSING);
c.acceptComposing=true;
c.showComposing=true;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, SR.MS_COMPOSING_NOTIFY);
//#endif
}
}
redraw();
if (body==null)
return JabberBlockListener.BLOCK_REJECTED;
Msg m=new Msg(mType, from, subj, body);
if (tStamp!=0)
m.dateGmt=tStamp;
//#ifndef WMUC
if (m.body.indexOf(SR.MS_IS_INVITING_YOU)>-1) m.dateGmt=0;
if (groupchat) {
ConferenceGroup mucGrp=(ConferenceGroup)c.group;
if (mucGrp.selfContact.getJid().equals(message.getFrom())) {
m.messageType=Msg.MESSAGE_TYPE_OUT;
m.unread=false;
} else {
//#ifdef LIGHT_CONFIG
//#ifdef PLUGINS
//# if (StaticData.getInstance().lightConfig)
//#endif
//# CustomLight.message();
//#endif
if (m.dateGmt<= ((ConferenceGroup)c.group).conferenceJoinTime)
m.messageType=Msg.MESSAGE_TYPE_HISTORY;
// highliting messages with myNick substring
String myNick=mucGrp.selfContact.getName();
String myNick_=myNick+" ";
String _myNick=" "+myNick;
if (body.indexOf(myNick)>-1) {
if (body.indexOf("> "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+",")>-1)
highlite=true;
else if (body.indexOf(": "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+" ")>-1)
highlite=true;
else if (body.indexOf(", "+myNick)>-1)
highlite=true;
else if (body.endsWith(_myNick))
highlite=true;
else if (body.indexOf(_myNick+"?")>-1)
highlite=true;
else if (body.indexOf(_myNick+"!")>-1)
highlite=true;
else if (body.indexOf(_myNick+".")>-1)
highlite=true;
}
myNick=null; myNick_=null; _myNick=null;
//TODO: custom highliting dictionary
}
m.from=name;
}
//#endif
m.highlite=highlite;
messageStore(c, m);
return JabberBlockListener.BLOCK_PROCESSED;
} else if( data instanceof Presence ) { // If we've received a presence
//System.out.println("presence");
if (myStatus==Presence.PRESENCE_OFFLINE)
return JabberBlockListener.BLOCK_REJECTED;
Presence pr = (Presence) data;
String from=pr.getFrom();
pr.dispathch();
int ti=pr.getTypeIndex();
//PresenceContact(from, ti);
Msg m=new Msg( (ti==Presence.PRESENCE_AUTH || ti==Presence.PRESENCE_AUTH_ASK)?Msg.MESSAGE_TYPE_AUTH:Msg.MESSAGE_TYPE_PRESENCE, from, null, pr.getPresenceTxt());
//#ifndef WMUC
JabberDataBlock xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmuc==null) xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc"); //join errors
if (xmuc!=null) {
try {
MucContact c = mucContact(from);
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) {
if (pr.hasEntityCaps()) {
getClientIcon(c, pr.getEntityNode());
c.version = pr.getEntityVer();
}
}
//#endif
String lang=pr.getAttribute("xml:lang");
if (lang!=null) c.lang=lang;
lang=null;
c.statusString=pr.getStatus();
String chatPres=c.processPresence(xmuc, pr);
if (cf.storeConfPresence
|| chatPres.indexOf(SR.MS_WAS_BANNED)>-1
|| chatPres.indexOf(SR.MS_WAS_KICKED)>-1
|| data.getTypeAttribute().equals("error")) {
int rp=from.indexOf('/');
String name=from.substring(rp+1);
Msg chatPresence=new Msg(Msg.MESSAGE_TYPE_PRESENCE, name, null, chatPres );
chatPresence.color=c.getMainColor();
messageStore(getContact(from.substring(0, rp), false), chatPresence);
name=null;
}
chatPres=null;
messageStore(c,m);
c.priority=pr.getPriority();
//System.gc();
//Thread.sleep(20);
} catch (Exception e) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
}
} else {
//#endif
Contact c=null;
if (ti==Presence.PRESENCE_AUTH_ASK) {
//processing subscriptions
if (cf.autoSubscribe==Config.SUBSCR_DROP)
return JabberBlockListener.BLOCK_REJECTED;
if (cf.autoSubscribe==Config.SUBSCR_REJECT) {
//#ifdef DEBUG
//# System.out.print(from);
//# System.out.println(": decline subscription");
//#endif
sendPresence(from, "unsubscribed", null, false);
return JabberBlockListener.BLOCK_PROCESSED;
}
c=getContact(from, true);
messageStore(c, m);
if (cf.autoSubscribe==Config.SUBSCR_AUTO) {
doSubscribe(c);
messageStore(c, new Msg(Msg.MESSAGE_TYPE_AUTH, from, null, SR.MS_AUTH_AUTO));
}
} else {
// processing presences
boolean enNIL = cf.notInListDropLevel > NotInListFilter.DROP_PRESENCES;
c=getContact(from, enNIL);
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //drop not-in-list presence
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
if (pr.getTypeIndex()!=Presence.PRESENCE_ERROR) {
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) if (ti<Presence.PRESENCE_OFFLINE)
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null) {
ClientsIconsData.processData(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
} else if (c.jid.hasResource()) {
ClientsIconsData.processData(c, c.getResource().substring(1));
}
//#endif
JabberDataBlock j2j=pr.findNamespace("x", "j2j:history");
if (j2j!=null) {
if (j2j.getChildBlock("jid")!=null)
c.j2j=j2j.getChildBlock("jid").getAttribute("gateway");
}
j2j=null;
String lang=pr.getAttribute("xml:lang");
//#if DEBUG
//# //System.out.println("xml:lang="+lang); // Very much output!
//#endif
c.lang=lang; lang=null;
c.statusString=pr.getStatus();
}
messageStore(c, m);
}
c.priority=pr.getPriority();
if (ti>=0)
c.setStatus(ti);
if (c.nick==null && c.status<=Presence.PRESENCE_DND) {
JabberDataBlock nick = pr.findNamespace("nick", "http://jabber.org/protocol/nick");
if (nick!=null) c.nick=nick.getText();
}
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT) && notifyReady(-111)) {
//#if USE_ROTATOR
if (cf.notifyBlink)
c.setNewContact();
//#endif
if (cf.notifyPicture) {
if (c.getGroupType()!=Groups.TYPE_TRANSP)
c.setIncoming(Contact.INC_APPEARING);
}
}
if (ti==Presence.PRESENCE_OFFLINE) {
c.setIncoming(Contact.INC_NONE);
c.showComposing=false;
}
if (ti>=0) {
//#ifdef RUNNING_MESSAGE
//# if (ti==Presence.PRESENCE_OFFLINE)
//# setTicker(c, SR.MS_OFFLINE);
//# else if (ti==Presence.PRESENCE_ONLINE)
//# setTicker(c, SR.MS_ONLINE);
//#endif
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT || ti==Presence.PRESENCE_OFFLINE) && (c.getGroupType()!=Groups.TYPE_TRANSP) && (c.getGroupType()!=Groups.TYPE_IGNORE))
playNotify(ti);
}
//#ifndef WMUC
}
//#endif
if (cf.autoClean) {
cleanAllGroups();
sort(hContacts);
}
else {
sort(hContacts);
reEnumRoster();
}
return JabberBlockListener.BLOCK_PROCESSED;
} // if presence
} catch(OutOfMemoryError eom){
System.out.println("error bombusmod\\src\\Client\\Roster.java:12");
} catch( Exception e ) {
//#if DEBUG
//# e.printStackTrace();
//#endif
}
return JabberBlockListener.BLOCK_REJECTED;
}
| public int blockArrived( JabberDataBlock data ) {
try {
if( data instanceof Iq ) {
String from = data.getAttribute("from");
String type = data.getTypeAttribute();
String id = data.getAttribute("id");
if (id!=null) {
if (id.startsWith("nickvc")) {
if (type.equals("get") || type.equals("set")) return JabberBlockListener.BLOCK_REJECTED;
VCard vc=new VCard(data);//.getNickName();
String nick=vc.getNickName();
Contact c=findContact(new Jid(from), false);
String group=(c.getGroupType()==Groups.TYPE_NO_GROUP)? null: c.group.name;
if (nick!=null) storeContact(from,nick,group, false);
//updateContact( nick, c.rosterJid, group, c.subscr, c.ask_subscribe);
sendVCardReq();
return JabberBlockListener.BLOCK_PROCESSED;
}
if (id.startsWith("getvc")) {
if (type.equals("error")) {
setQuerySign(false);
AlertBox alertBox = new AlertBox(SR.MS_ERROR, XmppError.findInStanza(data).toString()) {
public void yes() {
destroyView();
}
public void no() {
destroyView();
}
};
return JabberBlockListener.BLOCK_PROCESSED;
}
if (type.equals("get") || type.equals("set") ) return JabberBlockListener.BLOCK_REJECTED;
setQuerySign(false);
VCard vcard=new VCard(data);
String jid=id.substring(5);
Contact c=getContact(jid, false); // drop unwanted vcards
if (c!=null) {
c.vcard=vcard;
if (midlet.BombusMod.getInstance().getCurrentDisplayable() instanceof VirtualList) {
// if (c.getGroupType()==Groups.TYPE_SELF) { // Not able to edit VCard if self contact in roster
if (c.getJid().equals(myJid.getJid())) {
new VCardEdit(vcard);
} else {
new VCardView(c);
}
}
} else {
new VCardView(c);
}
return JabberBlockListener.BLOCK_PROCESSED;
}
} // id!=null
if ( type.equals( "result" ) ) {
if (id.equals("getros")) {
//theStream.enableRosterNotify(false); //voffk
processRoster(data);
if(!cf.collapsedGroups)
groups.queryGroupState(true);
setProgress(SR.MS_CONNECTED,100);
reEnumRoster();
querysign=doReconnect=false;
if (cf.loginstatus==5) {
sendPresence(Presence.PRESENCE_INVISIBLE, null);
} else {
sendPresence(cf.loginstatus, null);
}
SplashScreen.getInstance().close();
return JabberBlockListener.BLOCK_PROCESSED;
}
} else if (type.equals("set")) {
if (processRoster(data)) {
theStream.send(new Iq(from, Iq.TYPE_RESULT, id));
reEnumRoster();
return JabberBlockListener.BLOCK_PROCESSED;
}
}
} else if( data instanceof Message ) { // If we've received a message
//System.out.println(data.toString());
querysign=false;
Message message = (Message) data;
String from=message.getFrom();
if (myJid.equals(new Jid(from), false)) //Enable forwarding only from self-jids
from=message.getXFrom();
String type=message.getTypeAttribute();
boolean groupchat=false;
int start_me=-1;
String name=null;
if (type!=null)
if (type.equals("groupchat"))
groupchat=true;
if (groupchat) {
start_me=0;
int rp=from.indexOf('/');
name=from.substring(rp+1);
if (rp>0) from=from.substring(0, rp);
}
Contact c=getContact(from, (cf.notInListDropLevel != NotInListFilter.DROP_MESSAGES_PRESENCES || groupchat));
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //not-in-list message dropped
boolean highlite=false;
String body=message.getBody().trim();
String oob=message.getOOB();
if (oob!=null) body+=oob;
if (body.length()==0)
body=null;
String subj=message.getSubject().trim();
if (subj.length()==0)
subj=null;
long tStamp=message.getMessageTime();
int mType=Msg.MESSAGE_TYPE_IN;
if (groupchat) {
if (subj!=null) { // subject
if (body==null)
body=name+" "+SR.MS_HAS_SET_TOPIC_TO+": "+subj;
if (!subj.equals(c.statusString)) {
c.statusString=subj; // adding secondLine to conference
} else {
return JabberBlockListener.BLOCK_PROCESSED;
}
subj=null;
start_me=-1;
highlite=true;
mType=Msg.MESSAGE_TYPE_SUBJ;
}
} else if (type!=null){
if (type.equals("error")) {
body=SR.MS_ERROR_ + XmppError.findInStanza(message).toString();
} else if (type.equals("headline")) {
mType=Msg.MESSAGE_TYPE_HEADLINE;
}
} else {
type="chat";
}
//#ifndef WMUC
try {
JabberDataBlock xmlns=message.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmlns!=null) {
JabberDataBlock invite=xmlns.getChildBlock("invite");
if (invite!=null) {
if (message.getTypeAttribute().equals("error")) {
ConferenceGroup invConf=(ConferenceGroup)groups.getGroup(from);
body=XmppError.decodeStanzaError(message).toString(); /*"error: invites are forbidden"*/
} else {
String inviteReason=invite.getChildBlockText("reason");
String room=from+'/'+sd.account.getNickName();
ConferenceGroup invConf=initMuc(room, xmlns.getChildBlockText("password"));
invConf.confContact.commonPresence=false; //FS#761
if (invConf.selfContact.status==Presence.PRESENCE_OFFLINE)
invConf.confContact.status=Presence.PRESENCE_OFFLINE;
if (inviteReason!=null)
inviteReason=(inviteReason.length()>0)?" ("+inviteReason+")":"";
body=invite.getAttribute("from")+SR.MS_IS_INVITING_YOU+from+inviteReason;
reEnumRoster();
}
}
}
} catch (Exception e) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
}
//#endif
if (name==null) name=c.getName();
// /me
if (body!=null) {
//forme=false;
if (body.startsWith("/me ")) start_me=3;
if (start_me>=0) {
StringBuffer b=new StringBuffer();
//#if NICK_COLORS
b.append("\01");
//#endif
b.append(name);
//#if NICK_COLORS
b.append("\02");
//#endif
if (start_me==0) {
if (!cf.showBalloons) b.insert(0,"<");
b.append("> ");
}
else
b.insert(0,'*');
b.append(body.substring(start_me));
body=b.toString();
b=null;
}
//#ifdef LIGHT_CONFIG
//#ifdef PLUGINS
//# if (StaticData.getInstance().lightConfig)
//#endif
//# if (type.equals("chat")) CustomLight.message();
//#endif
}
//boolean compose=false;
if (type.equals("chat") && myStatus!=Presence.PRESENCE_INVISIBLE) {
if (message.findNamespace("request", "urn:xmpp:receipts")!=null) {
sendDeliveryMessage(c, data.getAttribute("id"));
}
if (message.findNamespace("received", "urn:xmpp:receipts")!=null) {
c.markDelivered(data.getAttribute("id"));
}
if (message.findNamespace("active", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("paused", "http://jabber.org/protocol/chatstates")!=null) {
c.acceptComposing=true;
c.showComposing=false;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, "");
//#endif
}
if (message.findNamespace("composing", "http://jabber.org/protocol/chatstates")!=null) {
playNotify(SOUND_COMPOSING);
c.acceptComposing=true;
c.showComposing=true;
//#ifdef RUNNING_MESSAGE
//# setTicker(c, SR.MS_COMPOSING_NOTIFY);
//#endif
}
}
redraw();
if (body==null)
return JabberBlockListener.BLOCK_REJECTED;
Msg m=new Msg(mType, from, subj, body);
if (tStamp!=0)
m.dateGmt=tStamp;
//#ifndef WMUC
if (m.body.indexOf(SR.MS_IS_INVITING_YOU)>-1) m.dateGmt=0;
if (groupchat) {
ConferenceGroup mucGrp=(ConferenceGroup)c.group;
if (mucGrp.selfContact.getJid().equals(message.getFrom())) {
m.messageType=Msg.MESSAGE_TYPE_OUT;
m.unread=false;
} else {
//#ifdef LIGHT_CONFIG
//#ifdef PLUGINS
//# if (StaticData.getInstance().lightConfig)
//#endif
//# CustomLight.message();
//#endif
if (m.dateGmt<= ((ConferenceGroup)c.group).conferenceJoinTime)
m.messageType=Msg.MESSAGE_TYPE_HISTORY;
// highliting messages with myNick substring
String myNick=mucGrp.selfContact.getName();
String myNick_=myNick+" ";
String _myNick=" "+myNick;
if (body.indexOf(myNick)>-1) {
if (body.indexOf("> "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+",")>-1)
highlite=true;
else if (body.indexOf(": "+myNick+": ")>-1)
highlite=true;
else if (body.indexOf(_myNick+" ")>-1)
highlite=true;
else if (body.indexOf(", "+myNick)>-1)
highlite=true;
else if (body.endsWith(_myNick))
highlite=true;
else if (body.indexOf(_myNick+"?")>-1)
highlite=true;
else if (body.indexOf(_myNick+"!")>-1)
highlite=true;
else if (body.indexOf(_myNick+".")>-1)
highlite=true;
}
myNick=null; myNick_=null; _myNick=null;
//TODO: custom highliting dictionary
}
m.from=name;
}
//#endif
m.highlite=highlite;
messageStore(c, m);
return JabberBlockListener.BLOCK_PROCESSED;
} else if( data instanceof Presence ) { // If we've received a presence
//System.out.println("presence");
if (myStatus==Presence.PRESENCE_OFFLINE)
return JabberBlockListener.BLOCK_REJECTED;
Presence pr = (Presence) data;
String from=pr.getFrom();
pr.dispathch();
int ti=pr.getTypeIndex();
//PresenceContact(from, ti);
Msg m=new Msg( (ti==Presence.PRESENCE_AUTH || ti==Presence.PRESENCE_AUTH_ASK)?Msg.MESSAGE_TYPE_AUTH:Msg.MESSAGE_TYPE_PRESENCE, from, null, pr.getPresenceTxt());
//#ifndef WMUC
JabberDataBlock xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc#user");
if (xmuc==null) xmuc=pr.findNamespace("x", "http://jabber.org/protocol/muc"); //join errors
if (xmuc!=null) {
try {
MucContact c = mucContact(from);
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) {
if (pr.hasEntityCaps()) {
getClientIcon(c, pr.getEntityNode());
String presenceVer = pr.getEntityVer();
if (presenceVer != null)
c.version = presenceVer;
}
}
//#endif
String lang=pr.getAttribute("xml:lang");
if (lang!=null) c.lang=lang;
lang=null;
c.statusString=pr.getStatus();
String chatPres=c.processPresence(xmuc, pr);
if (cf.storeConfPresence
|| chatPres.indexOf(SR.MS_WAS_BANNED)>-1
|| chatPres.indexOf(SR.MS_WAS_KICKED)>-1
|| data.getTypeAttribute().equals("error")) {
int rp=from.indexOf('/');
String name=from.substring(rp+1);
Msg chatPresence=new Msg(Msg.MESSAGE_TYPE_PRESENCE, name, null, chatPres );
chatPresence.color=c.getMainColor();
messageStore(getContact(from.substring(0, rp), false), chatPresence);
name=null;
}
chatPres=null;
messageStore(c,m);
c.priority=pr.getPriority();
//System.gc();
//Thread.sleep(20);
} catch (Exception e) {
//#ifdef DEBUG
//# e.printStackTrace();
//#endif
}
} else {
//#endif
Contact c=null;
if (ti==Presence.PRESENCE_AUTH_ASK) {
//processing subscriptions
if (cf.autoSubscribe==Config.SUBSCR_DROP)
return JabberBlockListener.BLOCK_REJECTED;
if (cf.autoSubscribe==Config.SUBSCR_REJECT) {
//#ifdef DEBUG
//# System.out.print(from);
//# System.out.println(": decline subscription");
//#endif
sendPresence(from, "unsubscribed", null, false);
return JabberBlockListener.BLOCK_PROCESSED;
}
c=getContact(from, true);
messageStore(c, m);
if (cf.autoSubscribe==Config.SUBSCR_AUTO) {
doSubscribe(c);
messageStore(c, new Msg(Msg.MESSAGE_TYPE_AUTH, from, null, SR.MS_AUTH_AUTO));
}
} else {
// processing presences
boolean enNIL = cf.notInListDropLevel > NotInListFilter.DROP_PRESENCES;
c=getContact(from, enNIL);
if (c==null) return JabberBlockListener.BLOCK_REJECTED; //drop not-in-list presence
if (pr.getAttribute("ver")!=null) c.version=pr.getAttribute("ver"); // for bombusmod only
if (pr.getTypeIndex()!=Presence.PRESENCE_ERROR) {
//#ifdef CLIENTS_ICONS
//#ifdef PLUGINS
//# if (sd.ClientsIcons)
//#endif
if (cf.showClientIcon) if (ti<Presence.PRESENCE_OFFLINE)
if (pr.hasEntityCaps()) {
if (pr.getEntityNode()!=null) {
ClientsIconsData.processData(c, pr.getEntityNode());
if (pr.getEntityVer()!=null)
c.version=pr.getEntityVer();
}
} else if (c.jid.hasResource()) {
ClientsIconsData.processData(c, c.getResource().substring(1));
}
//#endif
JabberDataBlock j2j=pr.findNamespace("x", "j2j:history");
if (j2j!=null) {
if (j2j.getChildBlock("jid")!=null)
c.j2j=j2j.getChildBlock("jid").getAttribute("gateway");
}
j2j=null;
String lang=pr.getAttribute("xml:lang");
//#if DEBUG
//# //System.out.println("xml:lang="+lang); // Very much output!
//#endif
c.lang=lang; lang=null;
c.statusString=pr.getStatus();
}
messageStore(c, m);
}
c.priority=pr.getPriority();
if (ti>=0)
c.setStatus(ti);
if (c.nick==null && c.status<=Presence.PRESENCE_DND) {
JabberDataBlock nick = pr.findNamespace("nick", "http://jabber.org/protocol/nick");
if (nick!=null) c.nick=nick.getText();
}
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT) && notifyReady(-111)) {
//#if USE_ROTATOR
if (cf.notifyBlink)
c.setNewContact();
//#endif
if (cf.notifyPicture) {
if (c.getGroupType()!=Groups.TYPE_TRANSP)
c.setIncoming(Contact.INC_APPEARING);
}
}
if (ti==Presence.PRESENCE_OFFLINE) {
c.setIncoming(Contact.INC_NONE);
c.showComposing=false;
}
if (ti>=0) {
//#ifdef RUNNING_MESSAGE
//# if (ti==Presence.PRESENCE_OFFLINE)
//# setTicker(c, SR.MS_OFFLINE);
//# else if (ti==Presence.PRESENCE_ONLINE)
//# setTicker(c, SR.MS_ONLINE);
//#endif
if ((ti==Presence.PRESENCE_ONLINE || ti==Presence.PRESENCE_CHAT || ti==Presence.PRESENCE_OFFLINE) && (c.getGroupType()!=Groups.TYPE_TRANSP) && (c.getGroupType()!=Groups.TYPE_IGNORE))
playNotify(ti);
}
//#ifndef WMUC
}
//#endif
if (cf.autoClean) {
cleanAllGroups();
sort(hContacts);
}
else {
sort(hContacts);
reEnumRoster();
}
return JabberBlockListener.BLOCK_PROCESSED;
} // if presence
} catch(OutOfMemoryError eom){
System.out.println("error bombusmod\\src\\Client\\Roster.java:12");
} catch( Exception e ) {
//#if DEBUG
//# e.printStackTrace();
//#endif
}
return JabberBlockListener.BLOCK_REJECTED;
}
|
diff --git a/core/src/classes/org/jdesktop/wonderland/client/jme/login/WonderlandLoginDialog.java b/core/src/classes/org/jdesktop/wonderland/client/jme/login/WonderlandLoginDialog.java
index cf2cbc429..247032bcc 100644
--- a/core/src/classes/org/jdesktop/wonderland/client/jme/login/WonderlandLoginDialog.java
+++ b/core/src/classes/org/jdesktop/wonderland/client/jme/login/WonderlandLoginDialog.java
@@ -1,530 +1,530 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.client.jme.login;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.jdesktop.wonderland.client.assetmgr.Asset;
import org.jdesktop.wonderland.client.assetmgr.AssetManager;
import org.jdesktop.wonderland.client.assetmgr.AssetManager.AssetProgressListener;
import org.jdesktop.wonderland.client.jme.utils.GUIUtils;
import org.jdesktop.wonderland.client.login.ServerSessionManager;
import org.jdesktop.wonderland.client.login.ServerSessionManager.LoginControl;
import org.jdesktop.wonderland.client.login.ServerStatusListener;
/**
*
* @author jkaplan
* @author Ronny Standtke <[email protected]>
*/
public class WonderlandLoginDialog extends javax.swing.JDialog
implements AssetProgressListener, ServerStatusListener {
private static final Logger LOGGER =
Logger.getLogger(WonderlandLoginDialog.class.getName());
private final static ResourceBundle BUNDLE = ResourceBundle.getBundle(
"org/jdesktop/wonderland/client/jme/login/Bundle");
private Frame parent;
private LoginPanel login;
/** the set of modules we are downloading */
private Map<Integer, String> statusMessages =
new LinkedHashMap<Integer, String>();
private int nextDownloadID;
/** a map from asset ids to status message ids for that asset */
private Map<Asset, Integer> assetIDs =
new HashMap<Asset, Integer>();
/** the status message id of the server session manager status message */
private final int sessionStatusID;
/** Creates new form NoAuthLoginDialog */
public WonderlandLoginDialog(Frame parent, boolean modal,
LoginPanel login) {
super(parent, modal);
this.parent = parent;
// remember the child panel
this.login = login;
login.addValidityListener(new ValidityListener());
sessionStatusID = nextMessageID();
// create our graphics
GUIUtils.initLookAndFeel();
initComponents();
// set the status text to empty
statusLabel.setText(" ");
// add a listener that will be notified of any downloads in progress
// assuming those are relevant to the current login
AssetManager.getAssetManager().addProgressListener(this);
// add a listener that will be notified of server status messages
login.getLoginControl().getSessionManager().addServerStatusListener(
this);
// add the child panel
loginSpecificPanel.add(login.getPanel(), BorderLayout.CENTER);
}
@Override
public void dispose() {
// unregister listeners
AssetManager.getAssetManager().removeProgressListener(this);
login.getLoginControl().getSessionManager().removeServerStatusListener(
this);
super.dispose();
}
public void downloadProgress(final Asset asset,
final int readBytes,
final int percentage) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// remove any session status messages, since they will block
// the download message from being displayed
statusMessages.remove(sessionStatusID);
// find the message id for this asset
Integer messageID = assetIDs.get(asset);
if (messageID == null) {
messageID = nextMessageID();
assetIDs.put(asset, messageID);
}
// format the asset loading message
String name = asset.getAssetURI().getURI();
if (name.lastIndexOf('/') != -1) {
name = name.substring(name.lastIndexOf('/') + 1);
}
// set the status text
String message = BUNDLE.getString("Downloading module");
message = MessageFormat.format(message, name, percentage);
statusMessages.put(messageID, message);
updateStatus();
}
});
}
public void downloadFailed(final Asset asset) {
downloadCompleted(asset);
}
public void downloadCompleted(final Asset asset) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Integer messageID = assetIDs.remove(asset);
if (messageID != null) {
statusMessages.remove(messageID);
}
updateStatus();
}
});
}
public void connecting(ServerSessionManager manager, final String message) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusMessages.put(sessionStatusID, message);
updateStatus();
}
});
}
public void connected(ServerSessionManager sessionManager) {
}
public void disconnected(ServerSessionManager sessionManager) {
}
private void updateStatus() {
if (!statusMessages.isEmpty()) {
// get the first message in status message list
String message = statusMessages.values().iterator().next();
statusLabel.setText(message);
}
}
private synchronized int nextMessageID() {
return nextDownloadID++;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
userPasswordPanel = new javax.swing.JPanel();
upServerLabel = new javax.swing.JLabel();
upPasswordLabel = new javax.swing.JLabel();
upUsernameLabel = new javax.swing.JLabel();
upServerField = new javax.swing.JTextField();
upPasswordField = new javax.swing.JPasswordField();
upUsernameField = new javax.swing.JTextField();
webPanel = new javax.swing.JPanel();
webServerLabel = new javax.swing.JLabel();
webServerField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
gradientPanel1 = new org.jdesktop.wonderland.client.jme.login.GradientPanel();
worldNameLabel = new javax.swing.JLabel();
gradientPanel2 = new org.jdesktop.wonderland.client.jme.login.GradientPanel();
loginSpecificPanel = new javax.swing.JPanel();
tagLineLabel = new javax.swing.JLabel();
buttonPanel = new javax.swing.JPanel();
cancelButton = new javax.swing.JButton();
loginButton = new javax.swing.JButton();
getRootPane().setDefaultButton(loginButton);
statusLabel = new javax.swing.JLabel();
advancedButton = new javax.swing.JButton();
userPasswordPanel.setOpaque(false);
upServerLabel.setFont(new java.awt.Font("Dialog", 1, 13));
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/client/jme/login/Bundle"); // NOI18N
upServerLabel.setText(bundle.getString("WonderlandLoginDialog.upServerLabel.text")); // NOI18N
upPasswordLabel.setFont(new java.awt.Font("Dialog", 1, 13));
upPasswordLabel.setText(bundle.getString("WonderlandLoginDialog.upPasswordLabel.text")); // NOI18N
upUsernameLabel.setFont(new java.awt.Font("Dialog", 1, 13));
upUsernameLabel.setText(bundle.getString("WonderlandLoginDialog.upUsernameLabel.text")); // NOI18N
upServerField.setEditable(false);
upPasswordField.setFont(new java.awt.Font("Dialog", 0, 13));
upPasswordField.setMinimumSize(new java.awt.Dimension(98, 22));
upUsernameField.setFont(new java.awt.Font("Dialog", 0, 13));
upUsernameField.setMinimumSize(new java.awt.Dimension(98, 22));
org.jdesktop.layout.GroupLayout userPasswordPanelLayout = new org.jdesktop.layout.GroupLayout(userPasswordPanel);
userPasswordPanel.setLayout(userPasswordPanelLayout);
userPasswordPanelLayout.setHorizontalGroup(
userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(userPasswordPanelLayout.createSequentialGroup()
.add(26, 26, 26)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(upPasswordLabel)
.add(upUsernameLabel)
.add(upServerLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(upUsernameField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(upPasswordField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(upServerField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE))
.addContainerGap())
);
userPasswordPanelLayout.setVerticalGroup(
userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, userPasswordPanelLayout.createSequentialGroup()
.addContainerGap()
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upUsernameLabel)
.add(upUsernameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upPasswordLabel)
.add(upPasswordField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upServerField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(upServerLabel))
.add(20, 20, 20))
);
webPanel.setOpaque(false);
webPanel.setPreferredSize(new java.awt.Dimension(402, 140));
webServerLabel.setFont(new java.awt.Font("Dialog", 1, 13));
webServerLabel.setText(bundle.getString("WonderlandLoginDialog.webServerLabel.text")); // NOI18N
webServerField.setEditable(false);
webServerField.setFont(new java.awt.Font("Dialog", 0, 13));
webServerField.setMinimumSize(new java.awt.Dimension(98, 22));
jLabel1.setText(bundle.getString("WonderlandLoginDialog.jLabel1.text")); // NOI18N
org.jdesktop.layout.GroupLayout webPanelLayout = new org.jdesktop.layout.GroupLayout(webPanel);
webPanel.setLayout(webPanelLayout);
webPanelLayout.setHorizontalGroup(
webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(webPanelLayout.createSequentialGroup()
.addContainerGap()
.add(webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(webPanelLayout.createSequentialGroup()
.add(webServerLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(webServerField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE))
.add(jLabel1))
.addContainerGap())
);
webPanelLayout.setVerticalGroup(
webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, webPanelLayout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 56, Short.MAX_VALUE)
.add(webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(webServerLabel)
.add(webServerField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
gradientPanel1.setGradientEndColor(new java.awt.Color(163, 183, 255));
gradientPanel1.setGradientStartColor(new java.awt.Color(0, 51, 255));
gradientPanel1.setMinimumSize(new java.awt.Dimension(0, 82));
- worldNameLabel.setFont(new java.awt.Font("Arial", 1, 36));
+ worldNameLabel.setFont(new java.awt.Font("Arial", 1, 36)); // NOI18N
worldNameLabel.setForeground(new java.awt.Color(255, 255, 255));
worldNameLabel.setText(bundle.getString("WonderlandLoginDialog.worldNameLabel.text")); // NOI18N
org.jdesktop.layout.GroupLayout gradientPanel1Layout = new org.jdesktop.layout.GroupLayout(gradientPanel1);
gradientPanel1.setLayout(gradientPanel1Layout);
gradientPanel1Layout.setHorizontalGroup(
gradientPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(worldNameLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 372, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
- .addContainerGap(66, Short.MAX_VALUE))
+ .addContainerGap(72, Short.MAX_VALUE))
);
gradientPanel1Layout.setVerticalGroup(
gradientPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(worldNameLabel)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gradientPanel2.setGradientEndColor(new java.awt.Color(217, 225, 255));
gradientPanel2.setGradientStartColor(new java.awt.Color(163, 183, 255));
gradientPanel2.setLayout(new java.awt.BorderLayout());
loginSpecificPanel.setOpaque(false);
loginSpecificPanel.setLayout(new java.awt.BorderLayout());
gradientPanel2.add(loginSpecificPanel, java.awt.BorderLayout.CENTER);
tagLineLabel.setFont(new java.awt.Font("Arial", 1, 18));
tagLineLabel.setForeground(new java.awt.Color(255, 255, 255));
tagLineLabel.setText(bundle.getString("WonderlandLoginDialog.tagLineLabel.text")); // NOI18N
tagLineLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
tagLineLabel.setAlignmentY(0.0F);
tagLineLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
tagLineLabel.setFocusable(false);
gradientPanel2.add(tagLineLabel, java.awt.BorderLayout.NORTH);
buttonPanel.setOpaque(false);
buttonPanel.setPreferredSize(new java.awt.Dimension(453, 65));
cancelButton.setBackground(new java.awt.Color(255, 255, 255));
cancelButton.setFont(new java.awt.Font("Dialog", 1, 13));
cancelButton.setText(bundle.getString("WonderlandLoginDialog.cancelButton.text")); // NOI18N
cancelButton.setAlignmentX(0.5F);
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
loginButton.setBackground(new java.awt.Color(255, 255, 255));
loginButton.setFont(new java.awt.Font("Dialog", 1, 13));
loginButton.setText(bundle.getString("WonderlandLoginDialog.loginButton.text")); // NOI18N
loginButton.setAlignmentX(0.5F);
loginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginButtonActionPerformed(evt);
}
});
- statusLabel.setFont(new java.awt.Font("Arial", 1, 12));
+ statusLabel.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
statusLabel.setForeground(new java.awt.Color(45, 45, 45));
statusLabel.setText(bundle.getString("WonderlandLoginDialog.statusLabel.text")); // NOI18N
- advancedButton.setFont(new java.awt.Font("Dialog", 0, 13));
+ advancedButton.setFont(new java.awt.Font("Dialog", 0, 13)); // NOI18N
advancedButton.setText(bundle.getString("WonderlandLoginDialog.advancedButton.text")); // NOI18N
advancedButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
advancedButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel);
buttonPanel.setLayout(buttonPanelLayout);
buttonPanelLayout.setHorizontalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(statusLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 308, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(10, 10, 10))
.add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup()
- .addContainerGap(110, Short.MAX_VALUE)
+ .addContainerGap(103, Short.MAX_VALUE)
.add(cancelButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(loginButton)
.add(40, 40, 40)))
.add(advancedButton)
.addContainerGap())
);
buttonPanelLayout.linkSize(new java.awt.Component[] {cancelButton, loginButton}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
buttonPanelLayout.setVerticalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusLabel)
.add(advancedButton))
- .addContainerGap(24, Short.MAX_VALUE))
+ .addContainerGap(30, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup()
- .addContainerGap(24, Short.MAX_VALUE)
+ .addContainerGap(30, Short.MAX_VALUE)
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loginButton)
.add(cancelButton))
.addContainerGap())
);
gradientPanel2.add(buttonPanel, java.awt.BorderLayout.PAGE_END);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
.add(gradientPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(gradientPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 54, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(4, 4, 4)
.add(gradientPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
login.cancel();
dispose();
}//GEN-LAST:event_cancelButtonActionPerformed
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
loginButton.setEnabled(false);
statusLabel.setText(BUNDLE.getString("Connecting..."));
// perform the actual login in a separate thread, so we don't
// block the AWT event thread
new Thread(new Runnable() {
public void run() {
String errorMessage = login.doLogin();
if (errorMessage == null) {
// success
dispose();
} else {
String text = BUNDLE.getString("Error_Connecting");
text = MessageFormat.format(text, errorMessage);
statusLabel.setText(text);
loginButton.setEnabled(true);
}
}
}, "Login thread").start();
}//GEN-LAST:event_loginButtonActionPerformed
private LoginOptionsFrame loginOptionsFrame;
private void advancedButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_advancedButtonActionPerformed
if (loginOptionsFrame == null) {
loginOptionsFrame = new LoginOptionsFrame();
}
loginOptionsFrame.setVisible(true);
}//GEN-LAST:event_advancedButtonActionPerformed
public class ValidityListener {
public void setValidity(boolean isValid) {
loginButton.setEnabled(isValid);
}
}
public interface LoginPanel {
public JPanel getPanel();
public LoginControl getLoginControl();
public void setServer(String server);
public void addValidityListener(ValidityListener listener);
public void removeValidityListener(ValidityListener listener);
public void notifyValidityListeners();
public String doLogin(); // return null on success or an error string
// on failure
public void cancel();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton advancedButton;
private javax.swing.JPanel buttonPanel;
private javax.swing.JButton cancelButton;
private org.jdesktop.wonderland.client.jme.login.GradientPanel gradientPanel1;
private org.jdesktop.wonderland.client.jme.login.GradientPanel gradientPanel2;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton loginButton;
private javax.swing.JPanel loginSpecificPanel;
private javax.swing.JLabel statusLabel;
private javax.swing.JLabel tagLineLabel;
private javax.swing.JPasswordField upPasswordField;
private javax.swing.JLabel upPasswordLabel;
private javax.swing.JTextField upServerField;
private javax.swing.JLabel upServerLabel;
private javax.swing.JTextField upUsernameField;
private javax.swing.JLabel upUsernameLabel;
private javax.swing.JPanel userPasswordPanel;
private javax.swing.JPanel webPanel;
private javax.swing.JTextField webServerField;
private javax.swing.JLabel webServerLabel;
private javax.swing.JLabel worldNameLabel;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
userPasswordPanel = new javax.swing.JPanel();
upServerLabel = new javax.swing.JLabel();
upPasswordLabel = new javax.swing.JLabel();
upUsernameLabel = new javax.swing.JLabel();
upServerField = new javax.swing.JTextField();
upPasswordField = new javax.swing.JPasswordField();
upUsernameField = new javax.swing.JTextField();
webPanel = new javax.swing.JPanel();
webServerLabel = new javax.swing.JLabel();
webServerField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
gradientPanel1 = new org.jdesktop.wonderland.client.jme.login.GradientPanel();
worldNameLabel = new javax.swing.JLabel();
gradientPanel2 = new org.jdesktop.wonderland.client.jme.login.GradientPanel();
loginSpecificPanel = new javax.swing.JPanel();
tagLineLabel = new javax.swing.JLabel();
buttonPanel = new javax.swing.JPanel();
cancelButton = new javax.swing.JButton();
loginButton = new javax.swing.JButton();
getRootPane().setDefaultButton(loginButton);
statusLabel = new javax.swing.JLabel();
advancedButton = new javax.swing.JButton();
userPasswordPanel.setOpaque(false);
upServerLabel.setFont(new java.awt.Font("Dialog", 1, 13));
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/client/jme/login/Bundle"); // NOI18N
upServerLabel.setText(bundle.getString("WonderlandLoginDialog.upServerLabel.text")); // NOI18N
upPasswordLabel.setFont(new java.awt.Font("Dialog", 1, 13));
upPasswordLabel.setText(bundle.getString("WonderlandLoginDialog.upPasswordLabel.text")); // NOI18N
upUsernameLabel.setFont(new java.awt.Font("Dialog", 1, 13));
upUsernameLabel.setText(bundle.getString("WonderlandLoginDialog.upUsernameLabel.text")); // NOI18N
upServerField.setEditable(false);
upPasswordField.setFont(new java.awt.Font("Dialog", 0, 13));
upPasswordField.setMinimumSize(new java.awt.Dimension(98, 22));
upUsernameField.setFont(new java.awt.Font("Dialog", 0, 13));
upUsernameField.setMinimumSize(new java.awt.Dimension(98, 22));
org.jdesktop.layout.GroupLayout userPasswordPanelLayout = new org.jdesktop.layout.GroupLayout(userPasswordPanel);
userPasswordPanel.setLayout(userPasswordPanelLayout);
userPasswordPanelLayout.setHorizontalGroup(
userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(userPasswordPanelLayout.createSequentialGroup()
.add(26, 26, 26)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(upPasswordLabel)
.add(upUsernameLabel)
.add(upServerLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(upUsernameField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(upPasswordField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(upServerField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE))
.addContainerGap())
);
userPasswordPanelLayout.setVerticalGroup(
userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, userPasswordPanelLayout.createSequentialGroup()
.addContainerGap()
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upUsernameLabel)
.add(upUsernameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upPasswordLabel)
.add(upPasswordField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upServerField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(upServerLabel))
.add(20, 20, 20))
);
webPanel.setOpaque(false);
webPanel.setPreferredSize(new java.awt.Dimension(402, 140));
webServerLabel.setFont(new java.awt.Font("Dialog", 1, 13));
webServerLabel.setText(bundle.getString("WonderlandLoginDialog.webServerLabel.text")); // NOI18N
webServerField.setEditable(false);
webServerField.setFont(new java.awt.Font("Dialog", 0, 13));
webServerField.setMinimumSize(new java.awt.Dimension(98, 22));
jLabel1.setText(bundle.getString("WonderlandLoginDialog.jLabel1.text")); // NOI18N
org.jdesktop.layout.GroupLayout webPanelLayout = new org.jdesktop.layout.GroupLayout(webPanel);
webPanel.setLayout(webPanelLayout);
webPanelLayout.setHorizontalGroup(
webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(webPanelLayout.createSequentialGroup()
.addContainerGap()
.add(webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(webPanelLayout.createSequentialGroup()
.add(webServerLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(webServerField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE))
.add(jLabel1))
.addContainerGap())
);
webPanelLayout.setVerticalGroup(
webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, webPanelLayout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 56, Short.MAX_VALUE)
.add(webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(webServerLabel)
.add(webServerField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
gradientPanel1.setGradientEndColor(new java.awt.Color(163, 183, 255));
gradientPanel1.setGradientStartColor(new java.awt.Color(0, 51, 255));
gradientPanel1.setMinimumSize(new java.awt.Dimension(0, 82));
worldNameLabel.setFont(new java.awt.Font("Arial", 1, 36));
worldNameLabel.setForeground(new java.awt.Color(255, 255, 255));
worldNameLabel.setText(bundle.getString("WonderlandLoginDialog.worldNameLabel.text")); // NOI18N
org.jdesktop.layout.GroupLayout gradientPanel1Layout = new org.jdesktop.layout.GroupLayout(gradientPanel1);
gradientPanel1.setLayout(gradientPanel1Layout);
gradientPanel1Layout.setHorizontalGroup(
gradientPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(worldNameLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 372, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(66, Short.MAX_VALUE))
);
gradientPanel1Layout.setVerticalGroup(
gradientPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(worldNameLabel)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gradientPanel2.setGradientEndColor(new java.awt.Color(217, 225, 255));
gradientPanel2.setGradientStartColor(new java.awt.Color(163, 183, 255));
gradientPanel2.setLayout(new java.awt.BorderLayout());
loginSpecificPanel.setOpaque(false);
loginSpecificPanel.setLayout(new java.awt.BorderLayout());
gradientPanel2.add(loginSpecificPanel, java.awt.BorderLayout.CENTER);
tagLineLabel.setFont(new java.awt.Font("Arial", 1, 18));
tagLineLabel.setForeground(new java.awt.Color(255, 255, 255));
tagLineLabel.setText(bundle.getString("WonderlandLoginDialog.tagLineLabel.text")); // NOI18N
tagLineLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
tagLineLabel.setAlignmentY(0.0F);
tagLineLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
tagLineLabel.setFocusable(false);
gradientPanel2.add(tagLineLabel, java.awt.BorderLayout.NORTH);
buttonPanel.setOpaque(false);
buttonPanel.setPreferredSize(new java.awt.Dimension(453, 65));
cancelButton.setBackground(new java.awt.Color(255, 255, 255));
cancelButton.setFont(new java.awt.Font("Dialog", 1, 13));
cancelButton.setText(bundle.getString("WonderlandLoginDialog.cancelButton.text")); // NOI18N
cancelButton.setAlignmentX(0.5F);
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
loginButton.setBackground(new java.awt.Color(255, 255, 255));
loginButton.setFont(new java.awt.Font("Dialog", 1, 13));
loginButton.setText(bundle.getString("WonderlandLoginDialog.loginButton.text")); // NOI18N
loginButton.setAlignmentX(0.5F);
loginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginButtonActionPerformed(evt);
}
});
statusLabel.setFont(new java.awt.Font("Arial", 1, 12));
statusLabel.setForeground(new java.awt.Color(45, 45, 45));
statusLabel.setText(bundle.getString("WonderlandLoginDialog.statusLabel.text")); // NOI18N
advancedButton.setFont(new java.awt.Font("Dialog", 0, 13));
advancedButton.setText(bundle.getString("WonderlandLoginDialog.advancedButton.text")); // NOI18N
advancedButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
advancedButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel);
buttonPanel.setLayout(buttonPanelLayout);
buttonPanelLayout.setHorizontalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(statusLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 308, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(10, 10, 10))
.add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup()
.addContainerGap(110, Short.MAX_VALUE)
.add(cancelButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(loginButton)
.add(40, 40, 40)))
.add(advancedButton)
.addContainerGap())
);
buttonPanelLayout.linkSize(new java.awt.Component[] {cancelButton, loginButton}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
buttonPanelLayout.setVerticalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusLabel)
.add(advancedButton))
.addContainerGap(24, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup()
.addContainerGap(24, Short.MAX_VALUE)
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loginButton)
.add(cancelButton))
.addContainerGap())
);
gradientPanel2.add(buttonPanel, java.awt.BorderLayout.PAGE_END);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
.add(gradientPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(gradientPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 54, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(4, 4, 4)
.add(gradientPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
userPasswordPanel = new javax.swing.JPanel();
upServerLabel = new javax.swing.JLabel();
upPasswordLabel = new javax.swing.JLabel();
upUsernameLabel = new javax.swing.JLabel();
upServerField = new javax.swing.JTextField();
upPasswordField = new javax.swing.JPasswordField();
upUsernameField = new javax.swing.JTextField();
webPanel = new javax.swing.JPanel();
webServerLabel = new javax.swing.JLabel();
webServerField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
gradientPanel1 = new org.jdesktop.wonderland.client.jme.login.GradientPanel();
worldNameLabel = new javax.swing.JLabel();
gradientPanel2 = new org.jdesktop.wonderland.client.jme.login.GradientPanel();
loginSpecificPanel = new javax.swing.JPanel();
tagLineLabel = new javax.swing.JLabel();
buttonPanel = new javax.swing.JPanel();
cancelButton = new javax.swing.JButton();
loginButton = new javax.swing.JButton();
getRootPane().setDefaultButton(loginButton);
statusLabel = new javax.swing.JLabel();
advancedButton = new javax.swing.JButton();
userPasswordPanel.setOpaque(false);
upServerLabel.setFont(new java.awt.Font("Dialog", 1, 13));
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/client/jme/login/Bundle"); // NOI18N
upServerLabel.setText(bundle.getString("WonderlandLoginDialog.upServerLabel.text")); // NOI18N
upPasswordLabel.setFont(new java.awt.Font("Dialog", 1, 13));
upPasswordLabel.setText(bundle.getString("WonderlandLoginDialog.upPasswordLabel.text")); // NOI18N
upUsernameLabel.setFont(new java.awt.Font("Dialog", 1, 13));
upUsernameLabel.setText(bundle.getString("WonderlandLoginDialog.upUsernameLabel.text")); // NOI18N
upServerField.setEditable(false);
upPasswordField.setFont(new java.awt.Font("Dialog", 0, 13));
upPasswordField.setMinimumSize(new java.awt.Dimension(98, 22));
upUsernameField.setFont(new java.awt.Font("Dialog", 0, 13));
upUsernameField.setMinimumSize(new java.awt.Dimension(98, 22));
org.jdesktop.layout.GroupLayout userPasswordPanelLayout = new org.jdesktop.layout.GroupLayout(userPasswordPanel);
userPasswordPanel.setLayout(userPasswordPanelLayout);
userPasswordPanelLayout.setHorizontalGroup(
userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(userPasswordPanelLayout.createSequentialGroup()
.add(26, 26, 26)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(upPasswordLabel)
.add(upUsernameLabel)
.add(upServerLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(upUsernameField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(upPasswordField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(upServerField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE))
.addContainerGap())
);
userPasswordPanelLayout.setVerticalGroup(
userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, userPasswordPanelLayout.createSequentialGroup()
.addContainerGap()
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upUsernameLabel)
.add(upUsernameField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upPasswordLabel)
.add(upPasswordField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(userPasswordPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(upServerField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(upServerLabel))
.add(20, 20, 20))
);
webPanel.setOpaque(false);
webPanel.setPreferredSize(new java.awt.Dimension(402, 140));
webServerLabel.setFont(new java.awt.Font("Dialog", 1, 13));
webServerLabel.setText(bundle.getString("WonderlandLoginDialog.webServerLabel.text")); // NOI18N
webServerField.setEditable(false);
webServerField.setFont(new java.awt.Font("Dialog", 0, 13));
webServerField.setMinimumSize(new java.awt.Dimension(98, 22));
jLabel1.setText(bundle.getString("WonderlandLoginDialog.jLabel1.text")); // NOI18N
org.jdesktop.layout.GroupLayout webPanelLayout = new org.jdesktop.layout.GroupLayout(webPanel);
webPanel.setLayout(webPanelLayout);
webPanelLayout.setHorizontalGroup(
webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(webPanelLayout.createSequentialGroup()
.addContainerGap()
.add(webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(webPanelLayout.createSequentialGroup()
.add(webServerLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(webServerField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE))
.add(jLabel1))
.addContainerGap())
);
webPanelLayout.setVerticalGroup(
webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, webPanelLayout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 56, Short.MAX_VALUE)
.add(webPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(webServerLabel)
.add(webServerField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
gradientPanel1.setGradientEndColor(new java.awt.Color(163, 183, 255));
gradientPanel1.setGradientStartColor(new java.awt.Color(0, 51, 255));
gradientPanel1.setMinimumSize(new java.awt.Dimension(0, 82));
worldNameLabel.setFont(new java.awt.Font("Arial", 1, 36)); // NOI18N
worldNameLabel.setForeground(new java.awt.Color(255, 255, 255));
worldNameLabel.setText(bundle.getString("WonderlandLoginDialog.worldNameLabel.text")); // NOI18N
org.jdesktop.layout.GroupLayout gradientPanel1Layout = new org.jdesktop.layout.GroupLayout(gradientPanel1);
gradientPanel1.setLayout(gradientPanel1Layout);
gradientPanel1Layout.setHorizontalGroup(
gradientPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(worldNameLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 372, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(72, Short.MAX_VALUE))
);
gradientPanel1Layout.setVerticalGroup(
gradientPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(worldNameLabel)
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
gradientPanel2.setGradientEndColor(new java.awt.Color(217, 225, 255));
gradientPanel2.setGradientStartColor(new java.awt.Color(163, 183, 255));
gradientPanel2.setLayout(new java.awt.BorderLayout());
loginSpecificPanel.setOpaque(false);
loginSpecificPanel.setLayout(new java.awt.BorderLayout());
gradientPanel2.add(loginSpecificPanel, java.awt.BorderLayout.CENTER);
tagLineLabel.setFont(new java.awt.Font("Arial", 1, 18));
tagLineLabel.setForeground(new java.awt.Color(255, 255, 255));
tagLineLabel.setText(bundle.getString("WonderlandLoginDialog.tagLineLabel.text")); // NOI18N
tagLineLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
tagLineLabel.setAlignmentY(0.0F);
tagLineLabel.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
tagLineLabel.setFocusable(false);
gradientPanel2.add(tagLineLabel, java.awt.BorderLayout.NORTH);
buttonPanel.setOpaque(false);
buttonPanel.setPreferredSize(new java.awt.Dimension(453, 65));
cancelButton.setBackground(new java.awt.Color(255, 255, 255));
cancelButton.setFont(new java.awt.Font("Dialog", 1, 13));
cancelButton.setText(bundle.getString("WonderlandLoginDialog.cancelButton.text")); // NOI18N
cancelButton.setAlignmentX(0.5F);
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
loginButton.setBackground(new java.awt.Color(255, 255, 255));
loginButton.setFont(new java.awt.Font("Dialog", 1, 13));
loginButton.setText(bundle.getString("WonderlandLoginDialog.loginButton.text")); // NOI18N
loginButton.setAlignmentX(0.5F);
loginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginButtonActionPerformed(evt);
}
});
statusLabel.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
statusLabel.setForeground(new java.awt.Color(45, 45, 45));
statusLabel.setText(bundle.getString("WonderlandLoginDialog.statusLabel.text")); // NOI18N
advancedButton.setFont(new java.awt.Font("Dialog", 0, 13)); // NOI18N
advancedButton.setText(bundle.getString("WonderlandLoginDialog.advancedButton.text")); // NOI18N
advancedButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
advancedButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel);
buttonPanel.setLayout(buttonPanelLayout);
buttonPanelLayout.setHorizontalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(statusLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 308, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(10, 10, 10))
.add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup()
.addContainerGap(103, Short.MAX_VALUE)
.add(cancelButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(loginButton)
.add(40, 40, 40)))
.add(advancedButton)
.addContainerGap())
);
buttonPanelLayout.linkSize(new java.awt.Component[] {cancelButton, loginButton}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
buttonPanelLayout.setVerticalGroup(
buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(buttonPanelLayout.createSequentialGroup()
.addContainerGap()
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(statusLabel)
.add(advancedButton))
.addContainerGap(30, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup()
.addContainerGap(30, Short.MAX_VALUE)
.add(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loginButton)
.add(cancelButton))
.addContainerGap())
);
gradientPanel2.add(buttonPanel, java.awt.BorderLayout.PAGE_END);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(gradientPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
.add(gradientPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(gradientPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 54, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(4, 4, 4)
.add(gradientPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/TechGuard/Archers/Properties.java b/TechGuard/Archers/Properties.java
index b9125c2..0d0501a 100644
--- a/TechGuard/Archers/Properties.java
+++ b/TechGuard/Archers/Properties.java
@@ -1,104 +1,104 @@
package TechGuard.Archers;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.inventory.ItemStack;
import TechGuard.Archers.Arrow.EnumBowMaterial;
/**
* @author �TechGuard
*/
public class Properties {
public static HashMap<Short,ArrayList<ItemStack>> ArrowAmmo = new HashMap<Short,ArrayList<ItemStack>>();
private static String dir = "plugins/Archers/";
private static File ConfigFile;
public static void reload(){
load();
}
private static void load(){
ConfigFile = new File(dir + "config.ammo");
checkForConfig();
loadConfig();
}
private static void checkForConfig(){
try{
if(!ConfigFile.exists()){
ConfigFile.getParentFile().mkdirs();
ConfigFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(ConfigFile));
out.write("#The right order:"); out.newLine();
out.write("# ARROW NAME:ITEM ID,AMOUNT:NEW ITEM ID, AMOUNT, etc. etc."); out.newLine();
out.write("#Arrow names:"); out.newLine();
for(EnumBowMaterial bow : EnumBowMaterial.values()){
out.write(" "+bow.getName()); out.newLine();
}
out.write("#Lines witch start with the # symbol, will be ignored!"); out.newLine();
out.write(""); out.newLine();
out.write("#Normal Arrow"); out.newLine();
out.write("Normal:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Ice Arrow"); out.newLine();
out.write("Ice:332,1:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Fire Arrow"); out.newLine();
out.write("Fire:263,1:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#TNT Arrow"); out.newLine();
out.write("TNT:289,2:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Thunder Arrow"); out.newLine();
out.write("Thunder:331,5:262,1");out.newLine();
out.write(""); out.newLine();
out.write("#Monster Arrow"); out.newLine();
out.write("Monster:352,2:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Thrice Arrow"); out.newLine();
out.write("Thrice:262,3"); out.newLine();
out.write(""); out.newLine();
out.write("#Zombie Arrow"); out.newLine();
- out.write("Zombie:295,1,262,1"); out.newLine();
+ out.write("Zombie:295,1:262,1"); out.newLine();
out.write("#Tree Arrow");out.newLine();
- out.write("Tree:6,1,262,1");
+ out.write("Tree:6,1:262,1");
out.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
private static void loadConfig(){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(ConfigFile))));
String strLine;
while ((strLine = br.readLine()) != null){
if(strLine.startsWith("#") || strLine.startsWith(" ") || !strLine.contains(":")){
continue;
}
String[] split = strLine.split(":");
ArrayList<ItemStack> list = new ArrayList<ItemStack>();
for(String s : split){
if(s.contains(",")){
list.add(new ItemStack(Integer.parseInt(s.split(",")[0]), Integer.parseInt(s.split(",")[1])));
}
}
ArrowAmmo.put(EnumBowMaterial.fromName(split[0]).getDataValue(), list);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
| false | true | private static void checkForConfig(){
try{
if(!ConfigFile.exists()){
ConfigFile.getParentFile().mkdirs();
ConfigFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(ConfigFile));
out.write("#The right order:"); out.newLine();
out.write("# ARROW NAME:ITEM ID,AMOUNT:NEW ITEM ID, AMOUNT, etc. etc."); out.newLine();
out.write("#Arrow names:"); out.newLine();
for(EnumBowMaterial bow : EnumBowMaterial.values()){
out.write(" "+bow.getName()); out.newLine();
}
out.write("#Lines witch start with the # symbol, will be ignored!"); out.newLine();
out.write(""); out.newLine();
out.write("#Normal Arrow"); out.newLine();
out.write("Normal:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Ice Arrow"); out.newLine();
out.write("Ice:332,1:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Fire Arrow"); out.newLine();
out.write("Fire:263,1:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#TNT Arrow"); out.newLine();
out.write("TNT:289,2:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Thunder Arrow"); out.newLine();
out.write("Thunder:331,5:262,1");out.newLine();
out.write(""); out.newLine();
out.write("#Monster Arrow"); out.newLine();
out.write("Monster:352,2:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Thrice Arrow"); out.newLine();
out.write("Thrice:262,3"); out.newLine();
out.write(""); out.newLine();
out.write("#Zombie Arrow"); out.newLine();
out.write("Zombie:295,1,262,1"); out.newLine();
out.write("#Tree Arrow");out.newLine();
out.write("Tree:6,1,262,1");
out.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
| private static void checkForConfig(){
try{
if(!ConfigFile.exists()){
ConfigFile.getParentFile().mkdirs();
ConfigFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(ConfigFile));
out.write("#The right order:"); out.newLine();
out.write("# ARROW NAME:ITEM ID,AMOUNT:NEW ITEM ID, AMOUNT, etc. etc."); out.newLine();
out.write("#Arrow names:"); out.newLine();
for(EnumBowMaterial bow : EnumBowMaterial.values()){
out.write(" "+bow.getName()); out.newLine();
}
out.write("#Lines witch start with the # symbol, will be ignored!"); out.newLine();
out.write(""); out.newLine();
out.write("#Normal Arrow"); out.newLine();
out.write("Normal:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Ice Arrow"); out.newLine();
out.write("Ice:332,1:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Fire Arrow"); out.newLine();
out.write("Fire:263,1:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#TNT Arrow"); out.newLine();
out.write("TNT:289,2:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Thunder Arrow"); out.newLine();
out.write("Thunder:331,5:262,1");out.newLine();
out.write(""); out.newLine();
out.write("#Monster Arrow"); out.newLine();
out.write("Monster:352,2:262,1"); out.newLine();
out.write(""); out.newLine();
out.write("#Thrice Arrow"); out.newLine();
out.write("Thrice:262,3"); out.newLine();
out.write(""); out.newLine();
out.write("#Zombie Arrow"); out.newLine();
out.write("Zombie:295,1:262,1"); out.newLine();
out.write("#Tree Arrow");out.newLine();
out.write("Tree:6,1:262,1");
out.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
|
diff --git a/src/com/joeykrim/pbekeytester/MainActivity.java b/src/com/joeykrim/pbekeytester/MainActivity.java
index 8867b9e..99fa35e 100644
--- a/src/com/joeykrim/pbekeytester/MainActivity.java
+++ b/src/com/joeykrim/pbekeytester/MainActivity.java
@@ -1,125 +1,125 @@
package com.joeykrim.pbekeytester;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.security.*;
import javax.crypto.spec.*;
import javax.crypto.*;
import java.security.spec.*;
import android.util.*;
import java.util.*;
import android.support.v4.util.*;
import java.math.*;
public class MainActivity extends Activity {
String LOG_TAG = "TestIterations";
//set algorithm name
String algorithName = "PBEWITHSHA1AND128BITAES-CBC-BC";
//set generic password
String passphrase = "thisisatest"; //10 characters long
//Baseline starting point for key iterations
int keyIterationBaseline = 15000;
//Baseline duration
long baselineDuration = 0L;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((TextView) findViewById(R.id.resultsText)).setText("Solving...");
backgroundIterationCount bTask = new backgroundIterationCount();
bTask.execute();
}
public ArrayList<Long> solveTargetIteractionCount() {
ArrayList<Long> results = new ArrayList<Long>();
long startTime = SystemClock.elapsedRealtime();
SecretKey sk = generateKey(passphrase, generateSalt(), keyIterationBaseline, algorithName);
long finishTime = SystemClock.elapsedRealtime();
long elapsedTime = finishTime - startTime;
int iterationsPerMS = (int) (keyIterationBaseline / elapsedTime);
Log.d(LOG_TAG, "Iterations per millisecond: " + iterationsPerMS);
results.add(elapsedTime); //overall time consumed
results.add((long) keyIterationBaseline); //baseline key iterations
results.add((long) iterationsPerMS); //iterations per millisecond
- int scaledTargetIerations = (int) iterationsPerMS * 500;
+ int scaledTargetIterations = (int) iterationsPerMS * 500;
results.add((long) scaledTargetIterations); //scaled target iteration count
- long startTime = SystemClock.elapsedRealtime();
+ startTime = SystemClock.elapsedRealtime();
- SecretKey sk = generateKey(passphrase, generateSalt(), scaledTargetIterations, algorithName);
+ sk = generateKey(passphrase, generateSalt(), scaledTargetIterations, algorithName);
- long finishTime = SystemClock.elapsedRealtime();
+ finishTime = SystemClock.elapsedRealtime();
results.add((long) finishTime-startTime); //scaled elapsed time
return results;
}
//https://github.com/WhisperSystems/TextSecure/blob/master/src/org/thoughtcrime/securesms/crypto/MasterSecretUtil.java#L233
//notes, this changed in android 4+? to SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "Crypto");
public byte[] generateSalt() {
byte[] salt = new byte[16];
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
//textsecure uses 8, NIST recommends minimum 16
random.nextBytes(salt);
} catch (NoSuchAlgorithmException e) {
Log.e(LOG_TAG, "NoSuchAlgorithmException: " + e.toString());
}
return salt;
}
//https://github.com/WhisperSystems/TextSecure/blob/master/src/org/thoughtcrime/securesms/crypto/MasterSecretUtil.java#L241
public SecretKey generateKey(String passphrase, byte[] salt, int currentIterationCount, String algorithName) {
SecretKey sk = null;
try {
PBEKeySpec keyspec = new PBEKeySpec(passphrase.toCharArray(), salt, currentIterationCount);
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithName);
sk = skf.generateSecret(keyspec);
} catch (InvalidKeySpecException e) {
Log.e(LOG_TAG, "InvalidKeySpecException: " + e.toString());
} catch (NoSuchAlgorithmException e2){
Log.e(LOG_TAG, "NoSuchAlgorithmException: " + e2.toString());
}
return sk;
}
public class backgroundIterationCount extends AsyncTask<Void, Void, ArrayList<Long>> {
@Override protected ArrayList<Long> doInBackground(Void... params) {
return solveTargetIteractionCount();
}
@Override protected void onPostExecute(ArrayList<Long> results) {
if (!isCancelled()) {
((TextView) findViewById(R.id.resultsText)).setText("The below results are using the algorithm: "+ algorithName
+ " with passphrase: " + passphrase + System.getProperty("line.separator")
+ System.getProperty("line.separator") + "Overall time required: " + results.get(0) + "ms"
+ System.getProperty("line.separator") + " for " + results.get(1) + " iterations."
+ System.getProperty("line.separator") + "Iterations per millisecond: " + results.get(2)
+ System.getProperty("line.separator") + "Scaled iteration count: " + results.get(3)
+ System.getProperty("line.separator") + "Scaled elapsed time: " + results.get(4));
}
}
}
}
| false | true | public ArrayList<Long> solveTargetIteractionCount() {
ArrayList<Long> results = new ArrayList<Long>();
long startTime = SystemClock.elapsedRealtime();
SecretKey sk = generateKey(passphrase, generateSalt(), keyIterationBaseline, algorithName);
long finishTime = SystemClock.elapsedRealtime();
long elapsedTime = finishTime - startTime;
int iterationsPerMS = (int) (keyIterationBaseline / elapsedTime);
Log.d(LOG_TAG, "Iterations per millisecond: " + iterationsPerMS);
results.add(elapsedTime); //overall time consumed
results.add((long) keyIterationBaseline); //baseline key iterations
results.add((long) iterationsPerMS); //iterations per millisecond
int scaledTargetIerations = (int) iterationsPerMS * 500;
results.add((long) scaledTargetIterations); //scaled target iteration count
long startTime = SystemClock.elapsedRealtime();
SecretKey sk = generateKey(passphrase, generateSalt(), scaledTargetIterations, algorithName);
long finishTime = SystemClock.elapsedRealtime();
results.add((long) finishTime-startTime); //scaled elapsed time
return results;
}
| public ArrayList<Long> solveTargetIteractionCount() {
ArrayList<Long> results = new ArrayList<Long>();
long startTime = SystemClock.elapsedRealtime();
SecretKey sk = generateKey(passphrase, generateSalt(), keyIterationBaseline, algorithName);
long finishTime = SystemClock.elapsedRealtime();
long elapsedTime = finishTime - startTime;
int iterationsPerMS = (int) (keyIterationBaseline / elapsedTime);
Log.d(LOG_TAG, "Iterations per millisecond: " + iterationsPerMS);
results.add(elapsedTime); //overall time consumed
results.add((long) keyIterationBaseline); //baseline key iterations
results.add((long) iterationsPerMS); //iterations per millisecond
int scaledTargetIterations = (int) iterationsPerMS * 500;
results.add((long) scaledTargetIterations); //scaled target iteration count
startTime = SystemClock.elapsedRealtime();
sk = generateKey(passphrase, generateSalt(), scaledTargetIterations, algorithName);
finishTime = SystemClock.elapsedRealtime();
results.add((long) finishTime-startTime); //scaled elapsed time
return results;
}
|
diff --git a/src/main/java/com/araeosia/ArcherGames/CommandHandler.java b/src/main/java/com/araeosia/ArcherGames/CommandHandler.java
index 7354717..a1e1743 100644
--- a/src/main/java/com/araeosia/ArcherGames/CommandHandler.java
+++ b/src/main/java/com/araeosia/ArcherGames/CommandHandler.java
@@ -1,158 +1,158 @@
package com.araeosia.ArcherGames;
import com.araeosia.ArcherGames.utils.Archer;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandHandler implements CommandExecutor, Listener {
public ArcherGames plugin;
public CommandHandler(ArcherGames plugin) {
this.plugin = plugin;
}
public HashMap<String, Integer> chunkReloads;
/**
*
* @param sender
* @param cmd
* @param commandLabel
* @param args
* @return
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("vote")) {
sender.sendMessage(plugin.strings.get("voteinfo"));
for (String s : plugin.voteSites) {
sender.sendMessage(ChatColor.GREEN + s);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("money")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GREEN + sender.getName()+"'s balance is " + plugin.econ.getBalance(sender.getName()) + ""); //Or something
return true;
} else {
sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is "+plugin.econ.getBalance(args[0])); //Or something
return true;
}
} else if (cmd.getName().equalsIgnoreCase("stats")) {
if (args.length == 0) {
//plugin.getStats(sender.getName());
return true;
} else {
//plugin.getStats(args[0]);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("listkits")) {
sender.sendMessage(ChatColor.GREEN + plugin.strings.get("kitinfo"));
String kits = "";
for (String s : plugin.kits.keySet()) {
- kits += s.split(".")[2] + ", ";
+ kits += s.split(".")[1] + ", ";
}
sender.sendMessage(ChatColor.GREEN + kits);
return true;
} else if (cmd.getName().equalsIgnoreCase("kit") || args.length != 0) {
if (plugin.kits.containsKey(args[0])) {
if(sender.hasPermission("ArcherGames.kits." + args[0])){
plugin.serverwide.livingPlayers.add(Archer.getByName(sender.getName()));
Archer.getByName(sender.getName()).selectKit(args[0]);
sender.sendMessage(String.format(plugin.strings.get("kitgivin"), args[0]));
return true;
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit.");
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid kit.");
}
} else if(cmd.getName().equalsIgnoreCase("chunk")){
if(!(ScheduledTasks.gameStatus == 1)){
if(sender instanceof Player){
Player player = (Player) sender;
player.getWorld().unloadChunk(player.getLocation().getChunk());
player.getWorld().loadChunk(player.getLocation().getChunk());
player.sendMessage(ChatColor.GREEN + "Chunk Reloaded.");
} else{
return false;
}
} else{
return false;
}
} else if(cmd.getName().equalsIgnoreCase("pay")){
if(args.length != 0){
if(args.length != 1){
try {
if(Double.parseDouble(args[1]) > 0){
plugin.econ.takePlayer(sender.getName(), Double.parseDouble(args[1]));
plugin.econ.givePlayer(args[0], Double.parseDouble(args[1]));
sender.sendMessage(ChatColor.GREEN + "$"+args[0] + " paid to " + args[0]);
}
} catch(Exception e){
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if(cmd.getName().equalsIgnoreCase("time")){
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") +", "+((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if(cmd.getName().equalsIgnoreCase("timer")){
if(args.length != 0){
if(sender.hasPermission("ArcherGames.admin")){
try{
plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]);
plugin.scheduler.currentLoop = 0;
sender.sendMessage(ChatColor.GREEN + "Time left set to " + args[0] + " seconds left.");
}catch (Exception e){
sender.sendMessage(ChatColor.RED + "Time could not be set.");
}
}
}
} else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) {
if (args[0].equalsIgnoreCase("startGame")) {
ScheduledTasks.gameStatus = 2;
sender.sendMessage(ChatColor.GREEN + "Game started.");
plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName());
return true;
}
} else if (cmd.getName().equalsIgnoreCase("lockdown")){
if (sender.hasPermission("archergames.admin")){
plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode"));
plugin.saveConfig();
sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled.");
return true;
}else{
return false;
}
}
return false;
}
/**
*
* @param event
*/
@EventHandler
public void onCommandPreProccessEvent(final PlayerCommandPreprocessEvent event) {
if (!plugin.serverwide.getArcher(event.getPlayer()).canTalk && !event.getPlayer().hasPermission("archergames.overrides.command")) {
if (!event.getMessage().contains("kit") && false) { // Needs fixing.
event.setCancelled(true);
event.getPlayer().sendMessage(plugin.strings.get("nocommand"));
}
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("vote")) {
sender.sendMessage(plugin.strings.get("voteinfo"));
for (String s : plugin.voteSites) {
sender.sendMessage(ChatColor.GREEN + s);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("money")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GREEN + sender.getName()+"'s balance is " + plugin.econ.getBalance(sender.getName()) + ""); //Or something
return true;
} else {
sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is "+plugin.econ.getBalance(args[0])); //Or something
return true;
}
} else if (cmd.getName().equalsIgnoreCase("stats")) {
if (args.length == 0) {
//plugin.getStats(sender.getName());
return true;
} else {
//plugin.getStats(args[0]);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("listkits")) {
sender.sendMessage(ChatColor.GREEN + plugin.strings.get("kitinfo"));
String kits = "";
for (String s : plugin.kits.keySet()) {
kits += s.split(".")[2] + ", ";
}
sender.sendMessage(ChatColor.GREEN + kits);
return true;
} else if (cmd.getName().equalsIgnoreCase("kit") || args.length != 0) {
if (plugin.kits.containsKey(args[0])) {
if(sender.hasPermission("ArcherGames.kits." + args[0])){
plugin.serverwide.livingPlayers.add(Archer.getByName(sender.getName()));
Archer.getByName(sender.getName()).selectKit(args[0]);
sender.sendMessage(String.format(plugin.strings.get("kitgivin"), args[0]));
return true;
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit.");
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid kit.");
}
} else if(cmd.getName().equalsIgnoreCase("chunk")){
if(!(ScheduledTasks.gameStatus == 1)){
if(sender instanceof Player){
Player player = (Player) sender;
player.getWorld().unloadChunk(player.getLocation().getChunk());
player.getWorld().loadChunk(player.getLocation().getChunk());
player.sendMessage(ChatColor.GREEN + "Chunk Reloaded.");
} else{
return false;
}
} else{
return false;
}
} else if(cmd.getName().equalsIgnoreCase("pay")){
if(args.length != 0){
if(args.length != 1){
try {
if(Double.parseDouble(args[1]) > 0){
plugin.econ.takePlayer(sender.getName(), Double.parseDouble(args[1]));
plugin.econ.givePlayer(args[0], Double.parseDouble(args[1]));
sender.sendMessage(ChatColor.GREEN + "$"+args[0] + " paid to " + args[0]);
}
} catch(Exception e){
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if(cmd.getName().equalsIgnoreCase("time")){
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") +", "+((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if(cmd.getName().equalsIgnoreCase("timer")){
if(args.length != 0){
if(sender.hasPermission("ArcherGames.admin")){
try{
plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]);
plugin.scheduler.currentLoop = 0;
sender.sendMessage(ChatColor.GREEN + "Time left set to " + args[0] + " seconds left.");
}catch (Exception e){
sender.sendMessage(ChatColor.RED + "Time could not be set.");
}
}
}
} else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) {
if (args[0].equalsIgnoreCase("startGame")) {
ScheduledTasks.gameStatus = 2;
sender.sendMessage(ChatColor.GREEN + "Game started.");
plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName());
return true;
}
} else if (cmd.getName().equalsIgnoreCase("lockdown")){
if (sender.hasPermission("archergames.admin")){
plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode"));
plugin.saveConfig();
sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled.");
return true;
}else{
return false;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("vote")) {
sender.sendMessage(plugin.strings.get("voteinfo"));
for (String s : plugin.voteSites) {
sender.sendMessage(ChatColor.GREEN + s);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("money")) {
if (args.length == 0) {
sender.sendMessage(ChatColor.GREEN + sender.getName()+"'s balance is " + plugin.econ.getBalance(sender.getName()) + ""); //Or something
return true;
} else {
sender.sendMessage(ChatColor.GREEN + args[0] + "'s balance is "+plugin.econ.getBalance(args[0])); //Or something
return true;
}
} else if (cmd.getName().equalsIgnoreCase("stats")) {
if (args.length == 0) {
//plugin.getStats(sender.getName());
return true;
} else {
//plugin.getStats(args[0]);
return true;
}
} else if (cmd.getName().equalsIgnoreCase("listkits")) {
sender.sendMessage(ChatColor.GREEN + plugin.strings.get("kitinfo"));
String kits = "";
for (String s : plugin.kits.keySet()) {
kits += s.split(".")[1] + ", ";
}
sender.sendMessage(ChatColor.GREEN + kits);
return true;
} else if (cmd.getName().equalsIgnoreCase("kit") || args.length != 0) {
if (plugin.kits.containsKey(args[0])) {
if(sender.hasPermission("ArcherGames.kits." + args[0])){
plugin.serverwide.livingPlayers.add(Archer.getByName(sender.getName()));
Archer.getByName(sender.getName()).selectKit(args[0]);
sender.sendMessage(String.format(plugin.strings.get("kitgivin"), args[0]));
return true;
} else {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this kit.");
}
} else {
sender.sendMessage(ChatColor.RED + "That is not a valid kit.");
}
} else if(cmd.getName().equalsIgnoreCase("chunk")){
if(!(ScheduledTasks.gameStatus == 1)){
if(sender instanceof Player){
Player player = (Player) sender;
player.getWorld().unloadChunk(player.getLocation().getChunk());
player.getWorld().loadChunk(player.getLocation().getChunk());
player.sendMessage(ChatColor.GREEN + "Chunk Reloaded.");
} else{
return false;
}
} else{
return false;
}
} else if(cmd.getName().equalsIgnoreCase("pay")){
if(args.length != 0){
if(args.length != 1){
try {
if(Double.parseDouble(args[1]) > 0){
plugin.econ.takePlayer(sender.getName(), Double.parseDouble(args[1]));
plugin.econ.givePlayer(args[0], Double.parseDouble(args[1]));
sender.sendMessage(ChatColor.GREEN + "$"+args[0] + " paid to " + args[0]);
}
} catch(Exception e){
return false;
}
} else {
return false;
}
} else {
return false;
}
} else if(cmd.getName().equalsIgnoreCase("time")){
sender.sendMessage(ChatColor.GREEN + ((String.format(plugin.strings.get("starttimeleft"), ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60 + " minute" + (((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) / 60) == 1 ? "" : "s") +", "+((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop) % 60) + " second" + ((plugin.scheduler.preGameCountdown - plugin.scheduler.currentLoop != 1) ? "s" : ""))))));
} else if(cmd.getName().equalsIgnoreCase("timer")){
if(args.length != 0){
if(sender.hasPermission("ArcherGames.admin")){
try{
plugin.scheduler.preGameCountdown = Integer.parseInt(args[0]);
plugin.scheduler.currentLoop = 0;
sender.sendMessage(ChatColor.GREEN + "Time left set to " + args[0] + " seconds left.");
}catch (Exception e){
sender.sendMessage(ChatColor.RED + "Time could not be set.");
}
}
}
} else if (plugin.debug && cmd.getName().equalsIgnoreCase("ArcherGames")) {
if (args[0].equalsIgnoreCase("startGame")) {
ScheduledTasks.gameStatus = 2;
sender.sendMessage(ChatColor.GREEN + "Game started.");
plugin.log.info("[ArcherGames/Debug]: Game force-started by " + sender.getName());
return true;
}
} else if (cmd.getName().equalsIgnoreCase("lockdown")){
if (sender.hasPermission("archergames.admin")){
plugin.getConfig().set("ArcherGames.toggles.lockdownMode", !plugin.configToggles.get("ArcherGames.toggles.lockdownMode"));
plugin.saveConfig();
sender.sendMessage(ChatColor.GREEN + "LockDown mode toggled.");
return true;
}else{
return false;
}
}
return false;
}
|
diff --git a/dx/src/com/android/dx/ssa/back/IdenticalBlockCombiner.java b/dx/src/com/android/dx/ssa/back/IdenticalBlockCombiner.java
index e9974c0fd..cfc70153e 100644
--- a/dx/src/com/android/dx/ssa/back/IdenticalBlockCombiner.java
+++ b/dx/src/com/android/dx/ssa/back/IdenticalBlockCombiner.java
@@ -1,182 +1,182 @@
/*
* Copyright (C) 2007 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.dx.ssa.back;
import com.android.dx.rop.code.BasicBlock;
import com.android.dx.rop.code.BasicBlockList;
import com.android.dx.rop.code.CstInsn;
import com.android.dx.rop.code.Insn;
import com.android.dx.rop.code.InsnList;
import com.android.dx.rop.code.RegOps;
import com.android.dx.rop.code.RopMethod;
import com.android.dx.rop.code.SwitchInsn;
import com.android.dx.util.IntList;
import java.util.BitSet;
/**
* Searches for basic blocks that all have the same successor and insns
* but different predecessors. These blocks are then combined into a single
* block and the now-unused blocks are deleted. These identical blocks
* frequently are created when catch blocks are edge-split.
*/
public class IdenticalBlockCombiner {
private final RopMethod ropMethod;
private final BasicBlockList blocks;
private final BasicBlockList newBlocks;
/**
* Constructs instance. Call {@code process()} to run.
*
* @param rm {@code non-null;} instance to process
*/
public IdenticalBlockCombiner(RopMethod rm) {
ropMethod = rm;
blocks = ropMethod.getBlocks();
newBlocks = blocks.getMutableCopy();
}
/**
* Runs algorithm. TODO: This is n^2, and could be made linear-ish with
* a hash. In particular, hash the contents of each block and only
* compare blocks with the same hash.
*
* @return {@code non-null;} new method that has been processed
*/
public RopMethod process() {
int szBlocks = blocks.size();
// indexed by label
BitSet toDelete = new BitSet(blocks.getMaxLabel());
// For each non-deleted block...
for (int bindex = 0; bindex < szBlocks; bindex++) {
BasicBlock b = blocks.get(bindex);
if (toDelete.get(b.getLabel())) {
// doomed block
continue;
}
IntList preds = ropMethod.labelToPredecessors(b.getLabel());
// ...look at all of it's predecessors that have only one succ...
int szPreds = preds.size();
for (int i = 0; i < szPreds; i++) {
int iLabel = preds.get(i);
BasicBlock iBlock = blocks.labelToBlock(iLabel);
if (toDelete.get(iLabel)
- || iBlock.getSuccessors().size() > 1) {
+ || iBlock.getSuccessors().size() > 1
+ || iBlock.getFirstInsn().getOpcode().getOpcode() ==
+ RegOps.MOVE_RESULT) {
continue;
}
IntList toCombine = new IntList();
// ...and see if they can be combined with any other preds...
for (int j = i + 1; j < szPreds; j++) {
int jLabel = preds.get(j);
BasicBlock jBlock = blocks.labelToBlock(jLabel);
if (jBlock.getSuccessors().size() == 1
- && iBlock.getFirstInsn().getOpcode().getOpcode() !=
- RegOps.MOVE_RESULT
&& compareInsns(iBlock, jBlock)) {
toCombine.add(jLabel);
toDelete.set(jLabel);
}
}
combineBlocks(iLabel, toCombine);
}
}
for (int i = szBlocks - 1; i >= 0; i--) {
if (toDelete.get(newBlocks.get(i).getLabel())) {
newBlocks.set(i, null);
}
}
newBlocks.shrinkToFit();
newBlocks.setImmutable();
return new RopMethod(newBlocks, ropMethod.getFirstLabel());
}
/**
* Helper method to compare the contents of two blocks.
*
* @param a {@code non-null;} a block to compare
* @param b {@code non-null;} another block to compare
* @return {@code true} iff the two blocks' instructions are the same
*/
private static boolean compareInsns(BasicBlock a, BasicBlock b) {
return a.getInsns().contentEquals(b.getInsns());
}
/**
* Combines blocks proven identical into one alpha block, re-writing
* all of the successor links that point to the beta blocks to point
* to the alpha block instead.
*
* @param alphaLabel block that will replace all the beta block
* @param betaLabels label list of blocks to combine
*/
private void combineBlocks(int alphaLabel, IntList betaLabels) {
int szBetas = betaLabels.size();
for (int i = 0; i < szBetas; i++) {
int betaLabel = betaLabels.get(i);
BasicBlock bb = blocks.labelToBlock(betaLabel);
IntList preds = ropMethod.labelToPredecessors(bb.getLabel());
int szPreds = preds.size();
for (int j = 0; j < szPreds; j++) {
BasicBlock predBlock = newBlocks.labelToBlock(preds.get(j));
replaceSucc(predBlock, betaLabel, alphaLabel);
}
}
}
/**
* Replaces one of a block's successors with a different label. Constructs
* an updated BasicBlock instance and places it in {@code newBlocks}.
*
* @param block block to replace
* @param oldLabel label of successor to replace
* @param newLabel label of new successor
*/
private void replaceSucc(BasicBlock block, int oldLabel, int newLabel) {
IntList newSuccessors = block.getSuccessors().mutableCopy();
int newPrimarySuccessor;
newSuccessors.set(newSuccessors.indexOf(oldLabel), newLabel);
newPrimarySuccessor = block.getPrimarySuccessor();
if (newPrimarySuccessor == oldLabel) {
newPrimarySuccessor = newLabel;
}
newSuccessors.setImmutable();
BasicBlock newBB = new BasicBlock(block.getLabel(),
block.getInsns(), newSuccessors, newPrimarySuccessor);
newBlocks.set(newBlocks.indexOfLabel(block.getLabel()), newBB);
}
}
| false | true | public RopMethod process() {
int szBlocks = blocks.size();
// indexed by label
BitSet toDelete = new BitSet(blocks.getMaxLabel());
// For each non-deleted block...
for (int bindex = 0; bindex < szBlocks; bindex++) {
BasicBlock b = blocks.get(bindex);
if (toDelete.get(b.getLabel())) {
// doomed block
continue;
}
IntList preds = ropMethod.labelToPredecessors(b.getLabel());
// ...look at all of it's predecessors that have only one succ...
int szPreds = preds.size();
for (int i = 0; i < szPreds; i++) {
int iLabel = preds.get(i);
BasicBlock iBlock = blocks.labelToBlock(iLabel);
if (toDelete.get(iLabel)
|| iBlock.getSuccessors().size() > 1) {
continue;
}
IntList toCombine = new IntList();
// ...and see if they can be combined with any other preds...
for (int j = i + 1; j < szPreds; j++) {
int jLabel = preds.get(j);
BasicBlock jBlock = blocks.labelToBlock(jLabel);
if (jBlock.getSuccessors().size() == 1
&& iBlock.getFirstInsn().getOpcode().getOpcode() !=
RegOps.MOVE_RESULT
&& compareInsns(iBlock, jBlock)) {
toCombine.add(jLabel);
toDelete.set(jLabel);
}
}
combineBlocks(iLabel, toCombine);
}
}
for (int i = szBlocks - 1; i >= 0; i--) {
if (toDelete.get(newBlocks.get(i).getLabel())) {
newBlocks.set(i, null);
}
}
newBlocks.shrinkToFit();
newBlocks.setImmutable();
return new RopMethod(newBlocks, ropMethod.getFirstLabel());
}
| public RopMethod process() {
int szBlocks = blocks.size();
// indexed by label
BitSet toDelete = new BitSet(blocks.getMaxLabel());
// For each non-deleted block...
for (int bindex = 0; bindex < szBlocks; bindex++) {
BasicBlock b = blocks.get(bindex);
if (toDelete.get(b.getLabel())) {
// doomed block
continue;
}
IntList preds = ropMethod.labelToPredecessors(b.getLabel());
// ...look at all of it's predecessors that have only one succ...
int szPreds = preds.size();
for (int i = 0; i < szPreds; i++) {
int iLabel = preds.get(i);
BasicBlock iBlock = blocks.labelToBlock(iLabel);
if (toDelete.get(iLabel)
|| iBlock.getSuccessors().size() > 1
|| iBlock.getFirstInsn().getOpcode().getOpcode() ==
RegOps.MOVE_RESULT) {
continue;
}
IntList toCombine = new IntList();
// ...and see if they can be combined with any other preds...
for (int j = i + 1; j < szPreds; j++) {
int jLabel = preds.get(j);
BasicBlock jBlock = blocks.labelToBlock(jLabel);
if (jBlock.getSuccessors().size() == 1
&& compareInsns(iBlock, jBlock)) {
toCombine.add(jLabel);
toDelete.set(jLabel);
}
}
combineBlocks(iLabel, toCombine);
}
}
for (int i = szBlocks - 1; i >= 0; i--) {
if (toDelete.get(newBlocks.get(i).getLabel())) {
newBlocks.set(i, null);
}
}
newBlocks.shrinkToFit();
newBlocks.setImmutable();
return new RopMethod(newBlocks, ropMethod.getFirstLabel());
}
|
diff --git a/src/main/java/org/jboss/pressgang/ccms/model/contentspec/ContentSpecToPropertyTag.java b/src/main/java/org/jboss/pressgang/ccms/model/contentspec/ContentSpecToPropertyTag.java
index 1caacbb..d26d9ec 100644
--- a/src/main/java/org/jboss/pressgang/ccms/model/contentspec/ContentSpecToPropertyTag.java
+++ b/src/main/java/org/jboss/pressgang/ccms/model/contentspec/ContentSpecToPropertyTag.java
@@ -1,130 +1,130 @@
package org.jboss.pressgang.ccms.model.contentspec;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Query;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.hibernate.envers.Audited;
import org.hibernate.envers.query.AuditEntity;
import org.hibernate.envers.query.AuditQuery;
import org.hibernate.envers.query.AuditQueryCreator;
import org.jboss.pressgang.ccms.model.PropertyTag;
import org.jboss.pressgang.ccms.model.TopicToPropertyTag;
import org.jboss.pressgang.ccms.model.base.ToPropertyTag;
@Entity
@Audited
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
@Table(name = "ContentSpecToPropertyTag")
public class ContentSpecToPropertyTag extends ToPropertyTag<ContentSpecToPropertyTag> implements Serializable {
private static final long serialVersionUID = 7567494908179498295L;
public static String SELECT_ALL_QUERY = "SELECT contentSpecToPropertyTag FROM ContentSpecToPropertyTag AS contentSpecToPropertyTag";
public static String SELECT_SIZE_QUERY = "SELECT COUNT(contentSpecToPropertyTag) FROM ContentSpecToPropertyTag AS " +
"contentSpecToPropertyTag";
private Integer contentSpecToPropertyTagId = null;
private ContentSpec contentSpec = null;
@Override
@Transient
public Integer getId() {
return contentSpecToPropertyTagId;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ContentSpecToPropertyTagID", unique = true, nullable = false)
public Integer getContentSpecToPropertyTagId() {
return contentSpecToPropertyTagId;
}
public void setContentSpecToPropertyTagId(Integer contentSpecToPropertyTagId) {
this.contentSpecToPropertyTagId = contentSpecToPropertyTagId;
}
@ManyToOne
@JoinColumn(name = "ContentSpecID", nullable = false)
@NotNull
public ContentSpec getContentSpec() {
return contentSpec;
}
public void setContentSpec(ContentSpec contentSpec) {
this.contentSpec = contentSpec;
}
@Override
@ManyToOne
@JoinColumn(name = "PropertyTagID", nullable = false)
@NotNull
public PropertyTag getPropertyTag() {
return propertyTag;
}
@Override
public void setPropertyTag(final PropertyTag propertyTag) {
this.propertyTag = propertyTag;
}
@Override
@Column(name = "Value", columnDefinition = "TEXT")
@Size(max = 65535)
public String getValue() {
return value;
}
@Override
public void setValue(final String value) {
this.value = value;
}
@Override
protected boolean testUnique(final EntityManager entityManager, final Number revision) {
if (propertyTag.getPropertyTagIsUnique()) {
/*
* Since having to iterate over thousands of entities is slow, use a HQL query to find the count for us.
*/
final Long count;
if (revision == null) {
- final String query = ContentSpecToPropertyTag.SELECT_SIZE_QUERY + " WHERE contentSpecToPropertyTag.propertyTag = " +
- ":propertyTagId AND contentSpecToPropertyTag.value = :value";
+ final String query = ContentSpecToPropertyTag.SELECT_SIZE_QUERY + " WHERE contentSpecToPropertyTag.propertyTag" +
+ ".propertyTagId = :propertyTagId AND contentSpecToPropertyTag.value = :value";
final Query entityQuery = entityManager.createQuery(query);
entityQuery.setParameter("value", getValue());
entityQuery.setParameter("propertyTagId", getPropertyTag().getId());
count = (Long) entityQuery.getSingleResult();
} else {
final AuditReader reader = AuditReaderFactory.get(entityManager);
final AuditQueryCreator queryCreator = reader.createQuery();
final AuditQuery query = queryCreator.forEntitiesAtRevision(TopicToPropertyTag.class, revision).addProjection(
AuditEntity.id().count("contentSpecToPropertyTagId")).add(
AuditEntity.relatedId("propertyTag").eq(getPropertyTag().getId())).add(
AuditEntity.property("value").eq(getValue()));
query.setCacheable(true);
count = (Long) query.getSingleResult();
}
if (count > 1) return false;
}
return true;
}
}
| true | true | protected boolean testUnique(final EntityManager entityManager, final Number revision) {
if (propertyTag.getPropertyTagIsUnique()) {
/*
* Since having to iterate over thousands of entities is slow, use a HQL query to find the count for us.
*/
final Long count;
if (revision == null) {
final String query = ContentSpecToPropertyTag.SELECT_SIZE_QUERY + " WHERE contentSpecToPropertyTag.propertyTag = " +
":propertyTagId AND contentSpecToPropertyTag.value = :value";
final Query entityQuery = entityManager.createQuery(query);
entityQuery.setParameter("value", getValue());
entityQuery.setParameter("propertyTagId", getPropertyTag().getId());
count = (Long) entityQuery.getSingleResult();
} else {
final AuditReader reader = AuditReaderFactory.get(entityManager);
final AuditQueryCreator queryCreator = reader.createQuery();
final AuditQuery query = queryCreator.forEntitiesAtRevision(TopicToPropertyTag.class, revision).addProjection(
AuditEntity.id().count("contentSpecToPropertyTagId")).add(
AuditEntity.relatedId("propertyTag").eq(getPropertyTag().getId())).add(
AuditEntity.property("value").eq(getValue()));
query.setCacheable(true);
count = (Long) query.getSingleResult();
}
if (count > 1) return false;
}
return true;
}
| protected boolean testUnique(final EntityManager entityManager, final Number revision) {
if (propertyTag.getPropertyTagIsUnique()) {
/*
* Since having to iterate over thousands of entities is slow, use a HQL query to find the count for us.
*/
final Long count;
if (revision == null) {
final String query = ContentSpecToPropertyTag.SELECT_SIZE_QUERY + " WHERE contentSpecToPropertyTag.propertyTag" +
".propertyTagId = :propertyTagId AND contentSpecToPropertyTag.value = :value";
final Query entityQuery = entityManager.createQuery(query);
entityQuery.setParameter("value", getValue());
entityQuery.setParameter("propertyTagId", getPropertyTag().getId());
count = (Long) entityQuery.getSingleResult();
} else {
final AuditReader reader = AuditReaderFactory.get(entityManager);
final AuditQueryCreator queryCreator = reader.createQuery();
final AuditQuery query = queryCreator.forEntitiesAtRevision(TopicToPropertyTag.class, revision).addProjection(
AuditEntity.id().count("contentSpecToPropertyTagId")).add(
AuditEntity.relatedId("propertyTag").eq(getPropertyTag().getId())).add(
AuditEntity.property("value").eq(getValue()));
query.setCacheable(true);
count = (Long) query.getSingleResult();
}
if (count > 1) return false;
}
return true;
}
|
diff --git a/fap/app/documentacionHTML/DocumentacionHTMLPlugin.java b/fap/app/documentacionHTML/DocumentacionHTMLPlugin.java
index bf2ebcd4..67d25a89 100644
--- a/fap/app/documentacionHTML/DocumentacionHTMLPlugin.java
+++ b/fap/app/documentacionHTML/DocumentacionHTMLPlugin.java
@@ -1,25 +1,25 @@
package documentacionHTML;
import play.Play;
import play.PlayPlugin;
import play.libs.IO;
import play.libs.MimeTypes;
import play.mvc.Http;
import play.mvc.Router;
import play.mvc.results.Result;
import play.vfs.VirtualFile;
import java.io.File;
public class DocumentacionHTMLPlugin extends PlayPlugin {
@Override
public void onRoutesLoaded() {
- Router.addRoute("GET", "/@documentation/html/{id}", "fap.DocumentacionHTML.index");
+ Router.addRoute("GET", "/@documentation/modules/fap/html/{id}", "fap.DocumentacionHTML.index");
}
}
| true | true | public void onRoutesLoaded() {
Router.addRoute("GET", "/@documentation/html/{id}", "fap.DocumentacionHTML.index");
}
| public void onRoutesLoaded() {
Router.addRoute("GET", "/@documentation/modules/fap/html/{id}", "fap.DocumentacionHTML.index");
}
|
diff --git a/membrane-esb/cli/src/test/java/com/predic8/membrane/examples/tests/QuickstartSOAPTest.java b/membrane-esb/cli/src/test/java/com/predic8/membrane/examples/tests/QuickstartSOAPTest.java
index 756ac707..88bbb291 100644
--- a/membrane-esb/cli/src/test/java/com/predic8/membrane/examples/tests/QuickstartSOAPTest.java
+++ b/membrane-esb/cli/src/test/java/com/predic8/membrane/examples/tests/QuickstartSOAPTest.java
@@ -1,178 +1,178 @@
/* Copyright 2012 predic8 GmbH, www.predic8.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 com.predic8.membrane.examples.tests;
import static com.predic8.membrane.test.AssertUtils.assertContains;
import static com.predic8.membrane.test.AssertUtils.assertContainsNot;
import static com.predic8.membrane.test.AssertUtils.getAndAssert200;
import static com.predic8.membrane.test.AssertUtils.postAndAssert;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import com.predic8.membrane.examples.DistributionExtractingTestcase;
import com.predic8.membrane.examples.Process2;
import com.predic8.membrane.examples.ProxiesXmlUtil;
import com.predic8.membrane.test.AssertUtils;
public class QuickstartSOAPTest extends DistributionExtractingTestcase {
@Test
public void doit() throws IOException, InterruptedException {
File baseDir = getExampleDir("quickstart-soap");
Process2 sl = new Process2.Builder().in(baseDir).script("router").waitForMembrane().start();
try {
ProxiesXmlUtil pxu = new ProxiesXmlUtil(new File(baseDir, "proxies.xml"));
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
String endpoint = "http://localhost:2000/MyBLZService";
String result = getAndAssert200(endpoint + "?wsdl");
assertContains("wsdl:documentation", result);
assertContains("localhost:2000/MyBLZService", result); // assert that rewriting did take place
result = AssertUtils.postAndAssert200(endpoint,
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:blz=\"http://thomas-bayer.com/blz/\">\r\n" +
" <soapenv:Header/>\r\n" +
" <soapenv:Body>\r\n" +
" <blz:getBank>\r\n" +
" <blz:blz>37050198</blz:blz>\r\n" +
" </blz:getBank>\r\n" +
" </soapenv:Body>\r\n" +
"</soapenv:Envelope>");
assertContains("Sparkasse", result);
- AssertUtils.setupHTTPAuthentication("localhost", 2000, "admin", "membrane");
+ AssertUtils.setupHTTPAuthentication("localhost", 9000, "admin", "membrane");
result = getAndAssert200("http://localhost:9000/admin/");
result.contains("BLZService");
String invalidRequest =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:blz=\"http://thomas-bayer.com/blz/\">\r\n" +
" <soapenv:Header/>\r\n" +
" <soapenv:Body>\r\n" +
" <blz:getBank>\r\n" +
" <blz:blz>37050198</blz:blz>\r\n" +
" <foo />\r\n" +
" </blz:getBank>\r\n" +
" </soapenv:Body>\r\n" +
"</soapenv:Envelope>";
result = postAndAssert(500, endpoint, invalidRequest);
assertContains(".java:", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = postAndAssert(500, endpoint, invalidRequest);
assertContainsNot(".java:", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" <validator/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = postAndAssert(400, endpoint, invalidRequest);
assertContains("Validation failed", result);
result = getAndAssert200("http://localhost:9000/admin/service-proxy/show?name=BLZService%3A2000");
result.contains("1 of 1 messages have been invalid");
result = getAndAssert200(endpoint);
assertContains("Target Namespace", result);
result = getAndAssert200(endpoint + "/operation/BLZServiceSOAP11Binding/BLZServicePortType/getBank");
assertContains("blz>?XXX?", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" <validator/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"2000\">\r\n" +
" <index />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = getAndAssert200("http://localhost:2000");
assertContains("/MyBLZService", result);
} finally {
sl.killScript();
}
}
}
| true | true | public void doit() throws IOException, InterruptedException {
File baseDir = getExampleDir("quickstart-soap");
Process2 sl = new Process2.Builder().in(baseDir).script("router").waitForMembrane().start();
try {
ProxiesXmlUtil pxu = new ProxiesXmlUtil(new File(baseDir, "proxies.xml"));
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
String endpoint = "http://localhost:2000/MyBLZService";
String result = getAndAssert200(endpoint + "?wsdl");
assertContains("wsdl:documentation", result);
assertContains("localhost:2000/MyBLZService", result); // assert that rewriting did take place
result = AssertUtils.postAndAssert200(endpoint,
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:blz=\"http://thomas-bayer.com/blz/\">\r\n" +
" <soapenv:Header/>\r\n" +
" <soapenv:Body>\r\n" +
" <blz:getBank>\r\n" +
" <blz:blz>37050198</blz:blz>\r\n" +
" </blz:getBank>\r\n" +
" </soapenv:Body>\r\n" +
"</soapenv:Envelope>");
assertContains("Sparkasse", result);
AssertUtils.setupHTTPAuthentication("localhost", 2000, "admin", "membrane");
result = getAndAssert200("http://localhost:9000/admin/");
result.contains("BLZService");
String invalidRequest =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:blz=\"http://thomas-bayer.com/blz/\">\r\n" +
" <soapenv:Header/>\r\n" +
" <soapenv:Body>\r\n" +
" <blz:getBank>\r\n" +
" <blz:blz>37050198</blz:blz>\r\n" +
" <foo />\r\n" +
" </blz:getBank>\r\n" +
" </soapenv:Body>\r\n" +
"</soapenv:Envelope>";
result = postAndAssert(500, endpoint, invalidRequest);
assertContains(".java:", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = postAndAssert(500, endpoint, invalidRequest);
assertContainsNot(".java:", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" <validator/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = postAndAssert(400, endpoint, invalidRequest);
assertContains("Validation failed", result);
result = getAndAssert200("http://localhost:9000/admin/service-proxy/show?name=BLZService%3A2000");
result.contains("1 of 1 messages have been invalid");
result = getAndAssert200(endpoint);
assertContains("Target Namespace", result);
result = getAndAssert200(endpoint + "/operation/BLZServiceSOAP11Binding/BLZServicePortType/getBank");
assertContains("blz>?XXX?", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" <validator/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"2000\">\r\n" +
" <index />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = getAndAssert200("http://localhost:2000");
assertContains("/MyBLZService", result);
} finally {
sl.killScript();
}
}
| public void doit() throws IOException, InterruptedException {
File baseDir = getExampleDir("quickstart-soap");
Process2 sl = new Process2.Builder().in(baseDir).script("router").waitForMembrane().start();
try {
ProxiesXmlUtil pxu = new ProxiesXmlUtil(new File(baseDir, "proxies.xml"));
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
String endpoint = "http://localhost:2000/MyBLZService";
String result = getAndAssert200(endpoint + "?wsdl");
assertContains("wsdl:documentation", result);
assertContains("localhost:2000/MyBLZService", result); // assert that rewriting did take place
result = AssertUtils.postAndAssert200(endpoint,
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:blz=\"http://thomas-bayer.com/blz/\">\r\n" +
" <soapenv:Header/>\r\n" +
" <soapenv:Body>\r\n" +
" <blz:getBank>\r\n" +
" <blz:blz>37050198</blz:blz>\r\n" +
" </blz:getBank>\r\n" +
" </soapenv:Body>\r\n" +
"</soapenv:Envelope>");
assertContains("Sparkasse", result);
AssertUtils.setupHTTPAuthentication("localhost", 9000, "admin", "membrane");
result = getAndAssert200("http://localhost:9000/admin/");
result.contains("BLZService");
String invalidRequest =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:blz=\"http://thomas-bayer.com/blz/\">\r\n" +
" <soapenv:Header/>\r\n" +
" <soapenv:Body>\r\n" +
" <blz:getBank>\r\n" +
" <blz:blz>37050198</blz:blz>\r\n" +
" <foo />\r\n" +
" </blz:getBank>\r\n" +
" </soapenv:Body>\r\n" +
"</soapenv:Envelope>";
result = postAndAssert(500, endpoint, invalidRequest);
assertContains(".java:", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = postAndAssert(500, endpoint, invalidRequest);
assertContainsNot(".java:", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" <validator/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = postAndAssert(400, endpoint, invalidRequest);
assertContains("Validation failed", result);
result = getAndAssert200("http://localhost:9000/admin/service-proxy/show?name=BLZService%3A2000");
result.contains("1 of 1 messages have been invalid");
result = getAndAssert200(endpoint);
assertContains("Target Namespace", result);
result = getAndAssert200(endpoint + "/operation/BLZServiceSOAP11Binding/BLZServicePortType/getBank");
assertContains("blz>?XXX?", result);
pxu.updateWith(
"<proxies xmlns=\"http://membrane-soa.org/schemas/proxies/v1/\"\r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://membrane-soa.org/schemas/proxies/v1/ http://membrane-soa.org/schemas/proxies/v1/proxies.xsd\">\r\n" +
" \r\n" +
" <soapProxy port=\"2000\" wsdl=\"http://www.thomas-bayer.com/axis2/services/BLZService?wsdl\">\r\n" +
" <path>/MyBLZService</path>\r\n" +
" <soapStackTraceFilter/>\r\n" +
" <validator/>\r\n" +
" </soapProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"9000\">\r\n" +
" <basicAuthentication>\r\n" +
" <user name=\"admin\" password=\"membrane\" />\r\n" +
" </basicAuthentication> \r\n" +
" <adminConsole />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
" <serviceProxy port=\"2000\">\r\n" +
" <index />\r\n" +
" </serviceProxy>\r\n" +
" \r\n" +
"</proxies>", sl);
result = getAndAssert200("http://localhost:2000");
assertContains("/MyBLZService", result);
} finally {
sl.killScript();
}
}
|
diff --git a/common/logisticspipes/renderer/LogisticsHUDRenderer.java b/common/logisticspipes/renderer/LogisticsHUDRenderer.java
index d7a36b7e..81f2c963 100644
--- a/common/logisticspipes/renderer/LogisticsHUDRenderer.java
+++ b/common/logisticspipes/renderer/LogisticsHUDRenderer.java
@@ -1,575 +1,577 @@
package logisticspipes.renderer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import logisticspipes.api.IHUDArmor;
import logisticspipes.config.Configs;
import logisticspipes.hud.HUDConfig;
import logisticspipes.interfaces.IHeadUpDisplayBlockRendererProvider;
import logisticspipes.interfaces.IHeadUpDisplayRendererProvider;
import logisticspipes.pipes.basic.CoreRoutedPipe;
import logisticspipes.proxy.MainProxy;
import logisticspipes.proxy.SimpleServiceLocator;
import logisticspipes.routing.IRouter;
import logisticspipes.routing.LaserData;
import logisticspipes.routing.PipeRoutingConnectionType;
import logisticspipes.utils.ItemIdentifierStack;
import logisticspipes.utils.MathVector;
import logisticspipes.utils.Pair;
import logisticspipes.utils.gui.BasicGuiHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MovingObjectPosition;
import net.minecraftforge.client.GuiIngameForge;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.client.FMLClientHandler;
public class LogisticsHUDRenderer {
private LinkedList<IHeadUpDisplayRendererProvider> list = new LinkedList<IHeadUpDisplayRendererProvider>();
private double lastXPos = 0;
private double lastYPos = 0;
private double lastZPos = 0;
private int progress = 0;
private ArrayList<IHeadUpDisplayBlockRendererProvider> providers = new ArrayList<IHeadUpDisplayBlockRendererProvider>();
private List<LaserData> lasers = new ArrayList<LaserData>();
private static LogisticsHUDRenderer renderer = null;
public void add(IHeadUpDisplayBlockRendererProvider provider) {
IHeadUpDisplayBlockRendererProvider toRemove = null;
for(IHeadUpDisplayBlockRendererProvider listedProvider:providers) {
if(listedProvider.getX() == provider.getX() && listedProvider.getY() == provider.getY() && listedProvider.getZ() == provider.getZ()) {
toRemove = listedProvider;
break;
}
}
if(toRemove != null) {
providers.remove(toRemove);
}
providers.add(provider);
}
public void remove(IHeadUpDisplayBlockRendererProvider provider) {
providers.remove(provider);
}
public void clear() {
providers.clear();
instance().clearList(false);
}
private void clearList(boolean flag) {
if(flag) {
for(IHeadUpDisplayRendererProvider renderer:list) {
renderer.stopWatching();
}
}
list.clear();
}
private void refreshList(double x,double y,double z) {
ArrayList<Pair<Double,IHeadUpDisplayRendererProvider>> newList = new ArrayList<Pair<Double,IHeadUpDisplayRendererProvider>>();
for(IRouter router:SimpleServiceLocator.routerManager.getRouters()) {
if(router == null)
continue;
CoreRoutedPipe pipe = router.getPipe();
if(!(pipe instanceof IHeadUpDisplayRendererProvider)) continue;
if(MainProxy.getDimensionForWorld(pipe.worldObj) == MainProxy.getDimensionForWorld(FMLClientHandler.instance().getClient().theWorld)) {
double dis = Math.hypot(pipe.xCoord - x + 0.5,Math.hypot(pipe.yCoord - y + 0.5, pipe.zCoord - z + 0.5));
if(dis < Configs.LOGISTICS_HUD_RENDER_DISTANCE && dis > 0.75) {
newList.add(new Pair<Double,IHeadUpDisplayRendererProvider>(dis,(IHeadUpDisplayRendererProvider)pipe));
if(!list.contains(pipe)) {
((IHeadUpDisplayRendererProvider)pipe).startWatching();
}
}
}
}
List<IHeadUpDisplayBlockRendererProvider> remove = new ArrayList<IHeadUpDisplayBlockRendererProvider>();
for(IHeadUpDisplayBlockRendererProvider provider:providers) {
if(MainProxy.getDimensionForWorld(provider.getWorld()) == MainProxy.getDimensionForWorld(FMLClientHandler.instance().getClient().theWorld)) {
double dis = Math.hypot(provider.getX() - x + 0.5,Math.hypot(provider.getY() - y + 0.5, provider.getZ() - z + 0.5));
if(dis < Configs.LOGISTICS_HUD_RENDER_DISTANCE && dis > 0.75 && !provider.isInvalid() && provider.isExistent()) {
newList.add(new Pair<Double,IHeadUpDisplayRendererProvider>(dis,provider));
if(!list.contains(provider)) {
provider.startWatching();
}
} else if(provider.isInvalid() || !provider.isExistent()) {
remove.add(provider);
}
}
}
for(IHeadUpDisplayBlockRendererProvider provider:remove) {
providers.remove(provider);
}
if(newList.size() < 1) {
clearList(false);
return;
}
Collections.sort(newList, new Comparator<Pair<Double, IHeadUpDisplayRendererProvider>>() {
@Override
public int compare(
Pair<Double, IHeadUpDisplayRendererProvider> o1,
Pair<Double, IHeadUpDisplayRendererProvider> o2) {
if (o1.getValue1() < o2.getValue1()) {
return -1;
} else if (o1.getValue1() > o2.getValue1()) {
return 1;
} else {
return 0;
}
}
});
for(IHeadUpDisplayRendererProvider part:list) {
boolean contains = false;
for(Pair<Double,IHeadUpDisplayRendererProvider> inpart:newList) {
if(inpart.getValue2().equals(part)) {
contains = true;
break;
}
}
if(!contains) {
part.stopWatching();
}
}
clearList(false);
for (Pair<Double, IHeadUpDisplayRendererProvider> part : newList) {
list.addLast(part.getValue2());
}
}
private boolean playerWearsHUD() {
return FMLClientHandler.instance().getClient().thePlayer != null && FMLClientHandler.instance().getClient().thePlayer.inventory != null && FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory != null && FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3] != null && FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3].getItem() instanceof IHUDArmor && ((IHUDArmor)FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3].getItem()).isEnabled(FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3]);
}
private boolean displayCross = false;
public void renderPlayerDisplay(long renderTicks) {
if(!displayRenderer()) return;
Minecraft mc = FMLClientHandler.instance().getClient();
if(displayCross) {
ScaledResolution res = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
int width = res.getScaledWidth();
int height = res.getScaledHeight();
if (GuiIngameForge.renderCrosshairs && mc.ingameGUI != null) {
mc.renderEngine.bindTexture("/gui/icons.png");
GL11.glColor4d(0.0D, 0.0D, 0.0D, 1.0D);
GL11.glDisable(GL11.GL_BLEND);
mc.ingameGUI.drawTexturedModalRect(width / 2 - 7, height / 2 - 7, 0, 0, 16, 16);
}
}
}
public void renderWorldRelative(long renderTicks, float partialTick) {
if(!displayRenderer()) return;
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
if(list.size() == 0 || Math.hypot(lastXPos - player.posX,Math.hypot(lastYPos - player.posY, lastZPos - player.posZ)) > 0.5 || (renderTicks % 10 == 0 && (lastXPos != player.posX || lastYPos != player.posY + player.getEyeHeight() || lastZPos != player.posZ)) || renderTicks % 600 == 0) {
refreshList(player.posX,player.posY,player.posZ);
lastXPos = player.posX;
lastYPos = player.posY + player.getEyeHeight();
lastZPos = player.posZ;
}
boolean cursorHandled = false;
displayCross = false;
HUDConfig config = new HUDConfig(FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3]);
IHeadUpDisplayRendererProvider thisIsLast = null;
for(IHeadUpDisplayRendererProvider renderer:list) {
if(renderer.getRenderer() == null) continue;
if(renderer.getRenderer().display(config)) {
GL11.glPushMatrix();
if(!cursorHandled) {
double x = renderer.getX() + 0.5 - player.posX;
double y = renderer.getY() + 0.5 - player.posY;
double z = renderer.getZ() + 0.5 - player.posZ;
if(Math.hypot(x,Math.hypot(y, z)) < 0.75 || (renderer instanceof IHeadUpDisplayBlockRendererProvider && (((IHeadUpDisplayBlockRendererProvider)renderer).isInvalid() || !((IHeadUpDisplayBlockRendererProvider)renderer).isExistent()))) {
refreshList(player.posX,player.posY,player.posZ);
GL11.glPopMatrix();
break;
}
int[] pos = getCursor(renderer);
if(pos.length == 2) {
if(renderer.getRenderer().cursorOnWindow(pos[0], pos[1])) {
renderer.getRenderer().handleCursor(pos[0], pos[1]);
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) { //if(FMLClientHandler.instance().getClient().thePlayer.isSneaking()) {
thisIsLast = renderer;
displayCross = true;
}
cursorHandled = true;
}
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(thisIsLast != renderer) {
displayOneView(renderer, config, partialTick);
}
GL11.glPopMatrix();
}
}
if(thisIsLast != null) {
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
displayOneView(thisIsLast, config, partialTick);
+ GL11.glEnable(GL11.GL_BLEND);
+ GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glPopMatrix();
}
GL11.glPushMatrix();
MovingObjectPosition box = FMLClientHandler.instance().getClient().objectMouseOver;
if(box != null && box.typeOfHit == EnumMovingObjectType.TILE) {
if(Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
progress = Math.min(progress + 2, 100);
} else {
progress = Math.max(progress - 2, 0);
}
if(progress != 0) {
List<String> textData = SimpleServiceLocator.neiProxy.getInfoForPosition(player.worldObj, player, box);
if(!textData.isEmpty()) {
double xCoord = box.blockX + 0.5D;
double yCoord = box.blockY + 0.5D;
double zCoord = box.blockZ + 0.5D;
double x = xCoord - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = yCoord - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = zCoord - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float) x, (float) y, (float) z);
GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(getAngle(z, x) + 110F, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(( -1) * getAngle(Math.hypot(x + 0.8, z + 0.8), y + 0.5) + 180, 1.0F, 0.0F, 0.0F);
double dProgress = progress / 100D;
GL11.glTranslated(0.4D * dProgress + 0.6D, -0.2D * dProgress - 0.6D, -0.0D);
GL11.glScalef(0.01F, 0.01F, 1F);
int heigth = Math.max(32, 10 * textData.size() + 15);
int width = Math.max(32, SimpleServiceLocator.neiProxy.getWidthForList(textData, mc.fontRenderer) + 15);
GL11.glColor4b((byte) 127, (byte) 127, (byte) 127, (byte) 96);
BasicGuiHelper.drawGuiBackGround(mc, (int) (( -0.5 * (width - 32)) * dProgress) - 16, (int) (( -0.5 * (heigth - 32)) * dProgress) - 16, (int) ((0.5 * (width - 32)) * dProgress) + 16, (int) ((0.5 * (heigth - 32)) * dProgress) + 16, 0, false);
GL11.glColor4b((byte) 127, (byte) 127, (byte) 127, (byte) 127);
if(progress == 100) {
GL11.glTranslated((int) (( -0.5 * (width - 32)) * dProgress) - 16, (int) (( -0.5 * (heigth - 32)) * dProgress) - 16, -0.0001D);
for(int i=0;i<textData.size();i++) {
mc.fontRenderer.drawString(textData.get(i), 28, 8 + i * 10, 0x000000);
}
ItemStack item = SimpleServiceLocator.neiProxy.getItemForPosition(player.worldObj, player, box);
if(item != null) {
GL11.glScalef(1.5F, 1.5F, 0.0001F);
GL11.glScalef(0.8F, 0.8F, -1F);
List<ItemIdentifierStack> list = new ArrayList<ItemIdentifierStack>(1);
list.add(ItemIdentifierStack.GetFromStack(item));
BasicGuiHelper.renderItemIdentifierStackListIntoGui(list, null, 0, 5, 5, 1, 1, 18, 18, mc, false, false, true, true);
}
}
}
}
} else if(!Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
progress = 0;
}
GL11.glPopMatrix();
//Render Laser
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
//GL11.glEnable(GL11.GL_LIGHTING);
for(LaserData data: lasers) {
GL11.glPushMatrix();
double x = data.getPosX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = data.getPosY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = data.getPosZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
switch(data.getDir()) {
case NORTH:
GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
break;
case SOUTH:
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
break;
case EAST:
break;
case WEST:
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
break;
case UP:
GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
break;
case DOWN:
GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
break;
default:
break;
}
GL11.glScalef(0.01F, 0.01F, 0.01F);
Tessellator tessellator = Tessellator.instance;
for(float i = 0; i < 6 * data.getLength(); i++) {
setColor(i, data.getConnectionType());
float shift = 100f * i / 6f;
float start = 0.0f;
if(data.isStartPipe() && i == 0) {
start = -6.0f;
}
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.draw();
}
if(data.isStartPipe()) {
setColor(0, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(-3.0f, 3.0f, 3.0f);
tessellator.addVertex(-3.0f, 3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, 3.0f);
tessellator.draw();
}
if(data.isFinalPipe()) {
setColor(6 * data.getLength() - 1, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, -3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, -3.0f);
tessellator.draw();
}
GL11.glPopMatrix();
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
private void setColor(float i, EnumSet<PipeRoutingConnectionType> flags) {
GL11.glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
if(!flags.isEmpty()) {
int k=0;
for(int j=0;j<PipeRoutingConnectionType.values.length;j++) {
PipeRoutingConnectionType type = PipeRoutingConnectionType.values[j];
if(flags.contains(type)) {
k++;
}
if(k - 1 == (int) i % flags.size()) {
setColor(type);
break;
}
}
}
}
private void setColor(PipeRoutingConnectionType type) {
switch (type) {
case canRouteTo:
GL11.glColor4f(1.0f, 1.0f, 0.0f, 0.5f);
break;
case canRequestFrom:
GL11.glColor4f(0.0f, 1.0f, 0.0f, 0.5f);
break;
case canPowerFrom:
GL11.glColor4f(0.0f, 0.0f, 1.0f, 0.5f);
break;
default:
}
}
private void displayOneView(IHeadUpDisplayRendererProvider renderer, HUDConfig config, float partialTick) {
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
double x = renderer.getX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = renderer.getY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = renderer.getZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(getAngle(z,x) + 90, 0.0F, 0.0F, 1.0F);
GL11.glRotatef((-1)*getAngle(Math.hypot(x,z),y) + 180, 1.0F, 0.0F, 0.0F);
GL11.glTranslatef(0.0F, 0.0F, -0.4F);
GL11.glScalef(0.01F, 0.01F, 1F);
renderer.getRenderer().renderHeadUpDisplay(Math.hypot(x,Math.hypot(y, z)), false, mc, config);
}
private float getAngle(double x, double y) {
return (float) (Math.atan2(x,y) * 360 / (2 * Math.PI));
}
public double up(double input) {
input %= 360.0D;
while(input < 0 && !Double.isNaN(input) && !Double.isInfinite(input)) {
input += 360;
}
return input;
}
private int[] getCursor(IHeadUpDisplayRendererProvider renderer) {
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
MathVector playerView = MathVector.getFromAngles((270 - player.rotationYaw) / 360 * -2 * Math.PI, (player.rotationPitch) / 360 * -2 * Math.PI);
MathVector playerPos = new MathVector();
playerPos.X = player.posX;
playerPos.Y = player.posY;
playerPos.Z = player.posZ;
MathVector panelPos = new MathVector();
panelPos.X = renderer.getX() + 0.5;
panelPos.Y = renderer.getY() + 0.5;
panelPos.Z = renderer.getZ() + 0.5;
MathVector panelView = new MathVector();
panelView.X = playerPos.X - panelPos.X;
panelView.Y = playerPos.Y - panelPos.Y;
panelView.Z = playerPos.Z - panelPos.Z;
panelPos.add(panelView, 0.44D);
double d = panelPos.X * panelView.X + panelPos.Y * panelView.Y + panelPos.Z * panelView.Z;
double c = panelView.X * playerPos.X + panelView.Y * playerPos.Y + panelView.Z * playerPos.Z;
double b = panelView.X * playerView.X + panelView.Y * playerView.Y + panelView.Z * playerView.Z;
double a = (d - c) / b;
MathVector viewPos = new MathVector();
viewPos.X = playerPos.X + a * playerView.X - panelPos.X;
viewPos.Y = playerPos.Y + a * playerView.Y - panelPos.Y;
viewPos.Z = playerPos.Z + a * playerView.Z - panelPos.Z;
MathVector panelScalVector1 = new MathVector();
if(panelView.Y == 0) {
panelScalVector1.X = 0;
panelScalVector1.Y = 1;
panelScalVector1.Z = 0;
} else {
panelScalVector1 = panelView.getOrtogonal(-panelView.X, null, -panelView.Z).makeVectorLength(1.0D);
}
MathVector panelScalVector2 = new MathVector();
if(panelView.Z == 0) {
panelScalVector2.X = 0;
panelScalVector2.Y = 0;
panelScalVector2.Z = 1;
} else {
panelScalVector2 = panelView.getOrtogonal(1.0D, 0.0D, null).makeVectorLength(1.0D);
}
if(panelScalVector1.Y == 0) {
return new int[]{};
}
double cursorY = -viewPos.Y / panelScalVector1.Y;
MathVector restViewPos = viewPos.clone();
restViewPos.X += cursorY*panelScalVector1.X;
restViewPos.Y = 0;
restViewPos.Z += cursorY*panelScalVector1.Z;
double cursorX;
if(panelScalVector2.X == 0) {
cursorX = restViewPos.Z / panelScalVector2.Z;
} else {
cursorX = restViewPos.X / panelScalVector2.X;
}
cursorX *= 50 / 0.47D;
cursorY *= 50 / 0.47D;
if(panelView.Z < 0) {
cursorX *= -1;
}
if(panelView.Y < 0) {
cursorY *= -1;
}
return new int[]{(int) cursorX, (int)cursorY};
}
public boolean displayRenderer() {
if(!displayHUD()) {
if(list.size() != 0) {
clearList(true);
}
}
return displayHUD();
}
private boolean displayHUD() {
return playerWearsHUD() && FMLClientHandler.instance().getClient().currentScreen == null && FMLClientHandler.instance().getClient().gameSettings.thirdPersonView == 0 && !FMLClientHandler.instance().getClient().gameSettings.hideGUI;
}
public void resetLasers() {
lasers.clear();
}
public void setLasers(List<LaserData> newLasers) {
lasers.clear();
lasers.addAll(newLasers);
}
public boolean hasLasers() {
return !lasers.isEmpty();
}
public static LogisticsHUDRenderer instance() {
if(renderer == null) {
renderer = new LogisticsHUDRenderer();
}
return renderer;
}
}
| true | true | public void renderWorldRelative(long renderTicks, float partialTick) {
if(!displayRenderer()) return;
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
if(list.size() == 0 || Math.hypot(lastXPos - player.posX,Math.hypot(lastYPos - player.posY, lastZPos - player.posZ)) > 0.5 || (renderTicks % 10 == 0 && (lastXPos != player.posX || lastYPos != player.posY + player.getEyeHeight() || lastZPos != player.posZ)) || renderTicks % 600 == 0) {
refreshList(player.posX,player.posY,player.posZ);
lastXPos = player.posX;
lastYPos = player.posY + player.getEyeHeight();
lastZPos = player.posZ;
}
boolean cursorHandled = false;
displayCross = false;
HUDConfig config = new HUDConfig(FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3]);
IHeadUpDisplayRendererProvider thisIsLast = null;
for(IHeadUpDisplayRendererProvider renderer:list) {
if(renderer.getRenderer() == null) continue;
if(renderer.getRenderer().display(config)) {
GL11.glPushMatrix();
if(!cursorHandled) {
double x = renderer.getX() + 0.5 - player.posX;
double y = renderer.getY() + 0.5 - player.posY;
double z = renderer.getZ() + 0.5 - player.posZ;
if(Math.hypot(x,Math.hypot(y, z)) < 0.75 || (renderer instanceof IHeadUpDisplayBlockRendererProvider && (((IHeadUpDisplayBlockRendererProvider)renderer).isInvalid() || !((IHeadUpDisplayBlockRendererProvider)renderer).isExistent()))) {
refreshList(player.posX,player.posY,player.posZ);
GL11.glPopMatrix();
break;
}
int[] pos = getCursor(renderer);
if(pos.length == 2) {
if(renderer.getRenderer().cursorOnWindow(pos[0], pos[1])) {
renderer.getRenderer().handleCursor(pos[0], pos[1]);
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) { //if(FMLClientHandler.instance().getClient().thePlayer.isSneaking()) {
thisIsLast = renderer;
displayCross = true;
}
cursorHandled = true;
}
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(thisIsLast != renderer) {
displayOneView(renderer, config, partialTick);
}
GL11.glPopMatrix();
}
}
if(thisIsLast != null) {
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
displayOneView(thisIsLast, config, partialTick);
GL11.glPopMatrix();
}
GL11.glPushMatrix();
MovingObjectPosition box = FMLClientHandler.instance().getClient().objectMouseOver;
if(box != null && box.typeOfHit == EnumMovingObjectType.TILE) {
if(Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
progress = Math.min(progress + 2, 100);
} else {
progress = Math.max(progress - 2, 0);
}
if(progress != 0) {
List<String> textData = SimpleServiceLocator.neiProxy.getInfoForPosition(player.worldObj, player, box);
if(!textData.isEmpty()) {
double xCoord = box.blockX + 0.5D;
double yCoord = box.blockY + 0.5D;
double zCoord = box.blockZ + 0.5D;
double x = xCoord - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = yCoord - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = zCoord - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float) x, (float) y, (float) z);
GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(getAngle(z, x) + 110F, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(( -1) * getAngle(Math.hypot(x + 0.8, z + 0.8), y + 0.5) + 180, 1.0F, 0.0F, 0.0F);
double dProgress = progress / 100D;
GL11.glTranslated(0.4D * dProgress + 0.6D, -0.2D * dProgress - 0.6D, -0.0D);
GL11.glScalef(0.01F, 0.01F, 1F);
int heigth = Math.max(32, 10 * textData.size() + 15);
int width = Math.max(32, SimpleServiceLocator.neiProxy.getWidthForList(textData, mc.fontRenderer) + 15);
GL11.glColor4b((byte) 127, (byte) 127, (byte) 127, (byte) 96);
BasicGuiHelper.drawGuiBackGround(mc, (int) (( -0.5 * (width - 32)) * dProgress) - 16, (int) (( -0.5 * (heigth - 32)) * dProgress) - 16, (int) ((0.5 * (width - 32)) * dProgress) + 16, (int) ((0.5 * (heigth - 32)) * dProgress) + 16, 0, false);
GL11.glColor4b((byte) 127, (byte) 127, (byte) 127, (byte) 127);
if(progress == 100) {
GL11.glTranslated((int) (( -0.5 * (width - 32)) * dProgress) - 16, (int) (( -0.5 * (heigth - 32)) * dProgress) - 16, -0.0001D);
for(int i=0;i<textData.size();i++) {
mc.fontRenderer.drawString(textData.get(i), 28, 8 + i * 10, 0x000000);
}
ItemStack item = SimpleServiceLocator.neiProxy.getItemForPosition(player.worldObj, player, box);
if(item != null) {
GL11.glScalef(1.5F, 1.5F, 0.0001F);
GL11.glScalef(0.8F, 0.8F, -1F);
List<ItemIdentifierStack> list = new ArrayList<ItemIdentifierStack>(1);
list.add(ItemIdentifierStack.GetFromStack(item));
BasicGuiHelper.renderItemIdentifierStackListIntoGui(list, null, 0, 5, 5, 1, 1, 18, 18, mc, false, false, true, true);
}
}
}
}
} else if(!Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
progress = 0;
}
GL11.glPopMatrix();
//Render Laser
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
//GL11.glEnable(GL11.GL_LIGHTING);
for(LaserData data: lasers) {
GL11.glPushMatrix();
double x = data.getPosX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = data.getPosY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = data.getPosZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
switch(data.getDir()) {
case NORTH:
GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
break;
case SOUTH:
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
break;
case EAST:
break;
case WEST:
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
break;
case UP:
GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
break;
case DOWN:
GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
break;
default:
break;
}
GL11.glScalef(0.01F, 0.01F, 0.01F);
Tessellator tessellator = Tessellator.instance;
for(float i = 0; i < 6 * data.getLength(); i++) {
setColor(i, data.getConnectionType());
float shift = 100f * i / 6f;
float start = 0.0f;
if(data.isStartPipe() && i == 0) {
start = -6.0f;
}
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.draw();
}
if(data.isStartPipe()) {
setColor(0, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(-3.0f, 3.0f, 3.0f);
tessellator.addVertex(-3.0f, 3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, 3.0f);
tessellator.draw();
}
if(data.isFinalPipe()) {
setColor(6 * data.getLength() - 1, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, -3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, -3.0f);
tessellator.draw();
}
GL11.glPopMatrix();
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
private void setColor(float i, EnumSet<PipeRoutingConnectionType> flags) {
GL11.glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
if(!flags.isEmpty()) {
int k=0;
for(int j=0;j<PipeRoutingConnectionType.values.length;j++) {
PipeRoutingConnectionType type = PipeRoutingConnectionType.values[j];
if(flags.contains(type)) {
k++;
}
if(k - 1 == (int) i % flags.size()) {
setColor(type);
break;
}
}
}
}
private void setColor(PipeRoutingConnectionType type) {
switch (type) {
case canRouteTo:
GL11.glColor4f(1.0f, 1.0f, 0.0f, 0.5f);
break;
case canRequestFrom:
GL11.glColor4f(0.0f, 1.0f, 0.0f, 0.5f);
break;
case canPowerFrom:
GL11.glColor4f(0.0f, 0.0f, 1.0f, 0.5f);
break;
default:
}
}
private void displayOneView(IHeadUpDisplayRendererProvider renderer, HUDConfig config, float partialTick) {
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
double x = renderer.getX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = renderer.getY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = renderer.getZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(getAngle(z,x) + 90, 0.0F, 0.0F, 1.0F);
GL11.glRotatef((-1)*getAngle(Math.hypot(x,z),y) + 180, 1.0F, 0.0F, 0.0F);
GL11.glTranslatef(0.0F, 0.0F, -0.4F);
GL11.glScalef(0.01F, 0.01F, 1F);
renderer.getRenderer().renderHeadUpDisplay(Math.hypot(x,Math.hypot(y, z)), false, mc, config);
}
private float getAngle(double x, double y) {
return (float) (Math.atan2(x,y) * 360 / (2 * Math.PI));
}
public double up(double input) {
input %= 360.0D;
while(input < 0 && !Double.isNaN(input) && !Double.isInfinite(input)) {
input += 360;
}
return input;
}
private int[] getCursor(IHeadUpDisplayRendererProvider renderer) {
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
MathVector playerView = MathVector.getFromAngles((270 - player.rotationYaw) / 360 * -2 * Math.PI, (player.rotationPitch) / 360 * -2 * Math.PI);
MathVector playerPos = new MathVector();
playerPos.X = player.posX;
playerPos.Y = player.posY;
playerPos.Z = player.posZ;
MathVector panelPos = new MathVector();
panelPos.X = renderer.getX() + 0.5;
panelPos.Y = renderer.getY() + 0.5;
panelPos.Z = renderer.getZ() + 0.5;
MathVector panelView = new MathVector();
panelView.X = playerPos.X - panelPos.X;
panelView.Y = playerPos.Y - panelPos.Y;
panelView.Z = playerPos.Z - panelPos.Z;
panelPos.add(panelView, 0.44D);
double d = panelPos.X * panelView.X + panelPos.Y * panelView.Y + panelPos.Z * panelView.Z;
double c = panelView.X * playerPos.X + panelView.Y * playerPos.Y + panelView.Z * playerPos.Z;
double b = panelView.X * playerView.X + panelView.Y * playerView.Y + panelView.Z * playerView.Z;
double a = (d - c) / b;
MathVector viewPos = new MathVector();
viewPos.X = playerPos.X + a * playerView.X - panelPos.X;
viewPos.Y = playerPos.Y + a * playerView.Y - panelPos.Y;
viewPos.Z = playerPos.Z + a * playerView.Z - panelPos.Z;
MathVector panelScalVector1 = new MathVector();
if(panelView.Y == 0) {
panelScalVector1.X = 0;
panelScalVector1.Y = 1;
panelScalVector1.Z = 0;
} else {
panelScalVector1 = panelView.getOrtogonal(-panelView.X, null, -panelView.Z).makeVectorLength(1.0D);
}
MathVector panelScalVector2 = new MathVector();
if(panelView.Z == 0) {
panelScalVector2.X = 0;
panelScalVector2.Y = 0;
panelScalVector2.Z = 1;
} else {
panelScalVector2 = panelView.getOrtogonal(1.0D, 0.0D, null).makeVectorLength(1.0D);
}
if(panelScalVector1.Y == 0) {
return new int[]{};
}
double cursorY = -viewPos.Y / panelScalVector1.Y;
MathVector restViewPos = viewPos.clone();
restViewPos.X += cursorY*panelScalVector1.X;
restViewPos.Y = 0;
restViewPos.Z += cursorY*panelScalVector1.Z;
double cursorX;
if(panelScalVector2.X == 0) {
cursorX = restViewPos.Z / panelScalVector2.Z;
} else {
cursorX = restViewPos.X / panelScalVector2.X;
}
cursorX *= 50 / 0.47D;
cursorY *= 50 / 0.47D;
if(panelView.Z < 0) {
cursorX *= -1;
}
if(panelView.Y < 0) {
cursorY *= -1;
}
return new int[]{(int) cursorX, (int)cursorY};
}
public boolean displayRenderer() {
if(!displayHUD()) {
if(list.size() != 0) {
clearList(true);
}
}
return displayHUD();
}
private boolean displayHUD() {
return playerWearsHUD() && FMLClientHandler.instance().getClient().currentScreen == null && FMLClientHandler.instance().getClient().gameSettings.thirdPersonView == 0 && !FMLClientHandler.instance().getClient().gameSettings.hideGUI;
}
public void resetLasers() {
lasers.clear();
}
public void setLasers(List<LaserData> newLasers) {
lasers.clear();
lasers.addAll(newLasers);
}
public boolean hasLasers() {
return !lasers.isEmpty();
}
public static LogisticsHUDRenderer instance() {
if(renderer == null) {
renderer = new LogisticsHUDRenderer();
}
return renderer;
}
}
| public void renderWorldRelative(long renderTicks, float partialTick) {
if(!displayRenderer()) return;
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
if(list.size() == 0 || Math.hypot(lastXPos - player.posX,Math.hypot(lastYPos - player.posY, lastZPos - player.posZ)) > 0.5 || (renderTicks % 10 == 0 && (lastXPos != player.posX || lastYPos != player.posY + player.getEyeHeight() || lastZPos != player.posZ)) || renderTicks % 600 == 0) {
refreshList(player.posX,player.posY,player.posZ);
lastXPos = player.posX;
lastYPos = player.posY + player.getEyeHeight();
lastZPos = player.posZ;
}
boolean cursorHandled = false;
displayCross = false;
HUDConfig config = new HUDConfig(FMLClientHandler.instance().getClient().thePlayer.inventory.armorInventory[3]);
IHeadUpDisplayRendererProvider thisIsLast = null;
for(IHeadUpDisplayRendererProvider renderer:list) {
if(renderer.getRenderer() == null) continue;
if(renderer.getRenderer().display(config)) {
GL11.glPushMatrix();
if(!cursorHandled) {
double x = renderer.getX() + 0.5 - player.posX;
double y = renderer.getY() + 0.5 - player.posY;
double z = renderer.getZ() + 0.5 - player.posZ;
if(Math.hypot(x,Math.hypot(y, z)) < 0.75 || (renderer instanceof IHeadUpDisplayBlockRendererProvider && (((IHeadUpDisplayBlockRendererProvider)renderer).isInvalid() || !((IHeadUpDisplayBlockRendererProvider)renderer).isExistent()))) {
refreshList(player.posX,player.posY,player.posZ);
GL11.glPopMatrix();
break;
}
int[] pos = getCursor(renderer);
if(pos.length == 2) {
if(renderer.getRenderer().cursorOnWindow(pos[0], pos[1])) {
renderer.getRenderer().handleCursor(pos[0], pos[1]);
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) { //if(FMLClientHandler.instance().getClient().thePlayer.isSneaking()) {
thisIsLast = renderer;
displayCross = true;
}
cursorHandled = true;
}
}
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(thisIsLast != renderer) {
displayOneView(renderer, config, partialTick);
}
GL11.glPopMatrix();
}
}
if(thisIsLast != null) {
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
displayOneView(thisIsLast, config, partialTick);
GL11.glEnable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glPopMatrix();
}
GL11.glPushMatrix();
MovingObjectPosition box = FMLClientHandler.instance().getClient().objectMouseOver;
if(box != null && box.typeOfHit == EnumMovingObjectType.TILE) {
if(Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
progress = Math.min(progress + 2, 100);
} else {
progress = Math.max(progress - 2, 0);
}
if(progress != 0) {
List<String> textData = SimpleServiceLocator.neiProxy.getInfoForPosition(player.worldObj, player, box);
if(!textData.isEmpty()) {
double xCoord = box.blockX + 0.5D;
double yCoord = box.blockY + 0.5D;
double zCoord = box.blockZ + 0.5D;
double x = xCoord - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = yCoord - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = zCoord - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float) x, (float) y, (float) z);
GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(getAngle(z, x) + 110F, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(( -1) * getAngle(Math.hypot(x + 0.8, z + 0.8), y + 0.5) + 180, 1.0F, 0.0F, 0.0F);
double dProgress = progress / 100D;
GL11.glTranslated(0.4D * dProgress + 0.6D, -0.2D * dProgress - 0.6D, -0.0D);
GL11.glScalef(0.01F, 0.01F, 1F);
int heigth = Math.max(32, 10 * textData.size() + 15);
int width = Math.max(32, SimpleServiceLocator.neiProxy.getWidthForList(textData, mc.fontRenderer) + 15);
GL11.glColor4b((byte) 127, (byte) 127, (byte) 127, (byte) 96);
BasicGuiHelper.drawGuiBackGround(mc, (int) (( -0.5 * (width - 32)) * dProgress) - 16, (int) (( -0.5 * (heigth - 32)) * dProgress) - 16, (int) ((0.5 * (width - 32)) * dProgress) + 16, (int) ((0.5 * (heigth - 32)) * dProgress) + 16, 0, false);
GL11.glColor4b((byte) 127, (byte) 127, (byte) 127, (byte) 127);
if(progress == 100) {
GL11.glTranslated((int) (( -0.5 * (width - 32)) * dProgress) - 16, (int) (( -0.5 * (heigth - 32)) * dProgress) - 16, -0.0001D);
for(int i=0;i<textData.size();i++) {
mc.fontRenderer.drawString(textData.get(i), 28, 8 + i * 10, 0x000000);
}
ItemStack item = SimpleServiceLocator.neiProxy.getItemForPosition(player.worldObj, player, box);
if(item != null) {
GL11.glScalef(1.5F, 1.5F, 0.0001F);
GL11.glScalef(0.8F, 0.8F, -1F);
List<ItemIdentifierStack> list = new ArrayList<ItemIdentifierStack>(1);
list.add(ItemIdentifierStack.GetFromStack(item));
BasicGuiHelper.renderItemIdentifierStackListIntoGui(list, null, 0, 5, 5, 1, 1, 18, 18, mc, false, false, true, true);
}
}
}
}
} else if(!Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {
progress = 0;
}
GL11.glPopMatrix();
//Render Laser
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
//GL11.glEnable(GL11.GL_LIGHTING);
for(LaserData data: lasers) {
GL11.glPushMatrix();
double x = data.getPosX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = data.getPosY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = data.getPosZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
switch(data.getDir()) {
case NORTH:
GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
break;
case SOUTH:
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
break;
case EAST:
break;
case WEST:
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
break;
case UP:
GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
break;
case DOWN:
GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
break;
default:
break;
}
GL11.glScalef(0.01F, 0.01F, 0.01F);
Tessellator tessellator = Tessellator.instance;
for(float i = 0; i < 6 * data.getLength(); i++) {
setColor(i, data.getConnectionType());
float shift = 100f * i / 6f;
float start = 0.0f;
if(data.isStartPipe() && i == 0) {
start = -6.0f;
}
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, 3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, 3.0f);
tessellator.addVertex(19.7f + shift , -3.0f, 3.0f);
tessellator.draw();
tessellator.startDrawingQuads();
tessellator.addVertex(19.7f + shift , -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, -3.0f, -3.0f);
tessellator.addVertex( 3.0f + shift + start, 3.0f, -3.0f);
tessellator.addVertex(19.7f + shift , 3.0f, -3.0f);
tessellator.draw();
}
if(data.isStartPipe()) {
setColor(0, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(-3.0f, 3.0f, 3.0f);
tessellator.addVertex(-3.0f, 3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, -3.0f);
tessellator.addVertex(-3.0f, -3.0f, 3.0f);
tessellator.draw();
}
if(data.isFinalPipe()) {
setColor(6 * data.getLength() - 1, data.getConnectionType());
tessellator.startDrawingQuads();
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, -3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, 3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, 3.0f);
tessellator.addVertex(100.0f * data.getLength() + 3f, -3.0f, -3.0f);
tessellator.draw();
}
GL11.glPopMatrix();
}
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
private void setColor(float i, EnumSet<PipeRoutingConnectionType> flags) {
GL11.glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
if(!flags.isEmpty()) {
int k=0;
for(int j=0;j<PipeRoutingConnectionType.values.length;j++) {
PipeRoutingConnectionType type = PipeRoutingConnectionType.values[j];
if(flags.contains(type)) {
k++;
}
if(k - 1 == (int) i % flags.size()) {
setColor(type);
break;
}
}
}
}
private void setColor(PipeRoutingConnectionType type) {
switch (type) {
case canRouteTo:
GL11.glColor4f(1.0f, 1.0f, 0.0f, 0.5f);
break;
case canRequestFrom:
GL11.glColor4f(0.0f, 1.0f, 0.0f, 0.5f);
break;
case canPowerFrom:
GL11.glColor4f(0.0f, 0.0f, 1.0f, 0.5f);
break;
default:
}
}
private void displayOneView(IHeadUpDisplayRendererProvider renderer, HUDConfig config, float partialTick) {
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
double x = renderer.getX() + 0.5 - player.prevPosX - ((player.posX - player.prevPosX) * partialTick);
double y = renderer.getY() + 0.5 - player.prevPosY - ((player.posY - player.prevPosY) * partialTick);
double z = renderer.getZ() + 0.5 - player.prevPosZ - ((player.posZ - player.prevPosZ) * partialTick);
GL11.glTranslatef((float)x, (float)y, (float)z);
GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(getAngle(z,x) + 90, 0.0F, 0.0F, 1.0F);
GL11.glRotatef((-1)*getAngle(Math.hypot(x,z),y) + 180, 1.0F, 0.0F, 0.0F);
GL11.glTranslatef(0.0F, 0.0F, -0.4F);
GL11.glScalef(0.01F, 0.01F, 1F);
renderer.getRenderer().renderHeadUpDisplay(Math.hypot(x,Math.hypot(y, z)), false, mc, config);
}
private float getAngle(double x, double y) {
return (float) (Math.atan2(x,y) * 360 / (2 * Math.PI));
}
public double up(double input) {
input %= 360.0D;
while(input < 0 && !Double.isNaN(input) && !Double.isInfinite(input)) {
input += 360;
}
return input;
}
private int[] getCursor(IHeadUpDisplayRendererProvider renderer) {
Minecraft mc = FMLClientHandler.instance().getClient();
EntityPlayer player = mc.thePlayer;
MathVector playerView = MathVector.getFromAngles((270 - player.rotationYaw) / 360 * -2 * Math.PI, (player.rotationPitch) / 360 * -2 * Math.PI);
MathVector playerPos = new MathVector();
playerPos.X = player.posX;
playerPos.Y = player.posY;
playerPos.Z = player.posZ;
MathVector panelPos = new MathVector();
panelPos.X = renderer.getX() + 0.5;
panelPos.Y = renderer.getY() + 0.5;
panelPos.Z = renderer.getZ() + 0.5;
MathVector panelView = new MathVector();
panelView.X = playerPos.X - panelPos.X;
panelView.Y = playerPos.Y - panelPos.Y;
panelView.Z = playerPos.Z - panelPos.Z;
panelPos.add(panelView, 0.44D);
double d = panelPos.X * panelView.X + panelPos.Y * panelView.Y + panelPos.Z * panelView.Z;
double c = panelView.X * playerPos.X + panelView.Y * playerPos.Y + panelView.Z * playerPos.Z;
double b = panelView.X * playerView.X + panelView.Y * playerView.Y + panelView.Z * playerView.Z;
double a = (d - c) / b;
MathVector viewPos = new MathVector();
viewPos.X = playerPos.X + a * playerView.X - panelPos.X;
viewPos.Y = playerPos.Y + a * playerView.Y - panelPos.Y;
viewPos.Z = playerPos.Z + a * playerView.Z - panelPos.Z;
MathVector panelScalVector1 = new MathVector();
if(panelView.Y == 0) {
panelScalVector1.X = 0;
panelScalVector1.Y = 1;
panelScalVector1.Z = 0;
} else {
panelScalVector1 = panelView.getOrtogonal(-panelView.X, null, -panelView.Z).makeVectorLength(1.0D);
}
MathVector panelScalVector2 = new MathVector();
if(panelView.Z == 0) {
panelScalVector2.X = 0;
panelScalVector2.Y = 0;
panelScalVector2.Z = 1;
} else {
panelScalVector2 = panelView.getOrtogonal(1.0D, 0.0D, null).makeVectorLength(1.0D);
}
if(panelScalVector1.Y == 0) {
return new int[]{};
}
double cursorY = -viewPos.Y / panelScalVector1.Y;
MathVector restViewPos = viewPos.clone();
restViewPos.X += cursorY*panelScalVector1.X;
restViewPos.Y = 0;
restViewPos.Z += cursorY*panelScalVector1.Z;
double cursorX;
if(panelScalVector2.X == 0) {
cursorX = restViewPos.Z / panelScalVector2.Z;
} else {
cursorX = restViewPos.X / panelScalVector2.X;
}
cursorX *= 50 / 0.47D;
cursorY *= 50 / 0.47D;
if(panelView.Z < 0) {
cursorX *= -1;
}
if(panelView.Y < 0) {
cursorY *= -1;
}
return new int[]{(int) cursorX, (int)cursorY};
}
public boolean displayRenderer() {
if(!displayHUD()) {
if(list.size() != 0) {
clearList(true);
}
}
return displayHUD();
}
private boolean displayHUD() {
return playerWearsHUD() && FMLClientHandler.instance().getClient().currentScreen == null && FMLClientHandler.instance().getClient().gameSettings.thirdPersonView == 0 && !FMLClientHandler.instance().getClient().gameSettings.hideGUI;
}
public void resetLasers() {
lasers.clear();
}
public void setLasers(List<LaserData> newLasers) {
lasers.clear();
lasers.addAll(newLasers);
}
public boolean hasLasers() {
return !lasers.isEmpty();
}
public static LogisticsHUDRenderer instance() {
if(renderer == null) {
renderer = new LogisticsHUDRenderer();
}
return renderer;
}
}
|
diff --git a/cdi/plugins/org.jboss.tools.cdi.seam.solder.core/src/org/jboss/tools/cdi/seam/solder/core/CDISeamSolderDefaultBeanExtension.java b/cdi/plugins/org.jboss.tools.cdi.seam.solder.core/src/org/jboss/tools/cdi/seam/solder/core/CDISeamSolderDefaultBeanExtension.java
index 4d480df85..0d444c062 100644
--- a/cdi/plugins/org.jboss.tools.cdi.seam.solder.core/src/org/jboss/tools/cdi/seam/solder/core/CDISeamSolderDefaultBeanExtension.java
+++ b/cdi/plugins/org.jboss.tools.cdi.seam.solder.core/src/org/jboss/tools/cdi/seam/solder/core/CDISeamSolderDefaultBeanExtension.java
@@ -1,302 +1,303 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.seam.solder.core;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IType;
import org.eclipse.osgi.util.NLS;
import org.jboss.tools.cdi.core.CDIConstants;
import org.jboss.tools.cdi.core.CDICoreNature;
import org.jboss.tools.cdi.core.CDICorePlugin;
import org.jboss.tools.cdi.core.CDIUtil;
import org.jboss.tools.cdi.core.IBean;
import org.jboss.tools.cdi.core.ICDIProject;
import org.jboss.tools.cdi.core.IClassBean;
import org.jboss.tools.cdi.core.IProducer;
import org.jboss.tools.cdi.core.IProducerField;
import org.jboss.tools.cdi.core.IQualifierDeclaration;
import org.jboss.tools.cdi.core.IRootDefinitionContext;
import org.jboss.tools.cdi.core.IScope;
import org.jboss.tools.cdi.core.extension.ICDIExtension;
import org.jboss.tools.cdi.core.extension.feature.IAmbiguousBeanResolverFeature;
import org.jboss.tools.cdi.core.extension.feature.IBeanKeyProvider;
import org.jboss.tools.cdi.core.extension.feature.IBeanStoreFeature;
import org.jboss.tools.cdi.core.extension.feature.IProcessAnnotatedTypeFeature;
import org.jboss.tools.cdi.core.extension.feature.IValidatorFeature;
import org.jboss.tools.cdi.internal.core.impl.BeanMember;
import org.jboss.tools.cdi.internal.core.impl.CDIProject;
import org.jboss.tools.cdi.internal.core.impl.definition.AbstractMemberDefinition;
import org.jboss.tools.cdi.internal.core.impl.definition.BeanMemberDefinition;
import org.jboss.tools.cdi.internal.core.impl.definition.FieldDefinition;
import org.jboss.tools.cdi.internal.core.impl.definition.MethodDefinition;
import org.jboss.tools.cdi.internal.core.impl.definition.TypeDefinition;
import org.jboss.tools.cdi.internal.core.validation.CDICoreValidator;
import org.jboss.tools.cdi.seam.solder.core.validation.SeamSolderValidationMessages;
import org.jboss.tools.common.java.IAnnotationDeclaration;
import org.jboss.tools.common.java.IJavaAnnotation;
import org.jboss.tools.common.java.IJavaReference;
import org.jboss.tools.common.java.IParametedType;
import org.jboss.tools.common.java.ITypeDeclaration;
import org.jboss.tools.common.java.impl.AnnotationLiteral;
import org.jboss.tools.common.preferences.SeverityPreferences;
import org.jboss.tools.common.text.ITextSourceReference;
/**
* Implements support for org.jboss.seam.solder.bean.defaultbean.DefaultBeanExtension.
*
* In processing annotated type adds to each bean definition, which is a default bean,
* faked @Typed annotation with type set by @DefaultBean.
*
* In resolving ambiguous beans removes default beans out of the result set if it
* contains at least one non-default bean;
*
* @author Viacheslav Kabanovich
*
*/
public class CDISeamSolderDefaultBeanExtension implements ICDIExtension, IProcessAnnotatedTypeFeature, IAmbiguousBeanResolverFeature, IValidatorFeature, IBeanKeyProvider, IBeanStoreFeature {
private static String ID = "org.jboss.solder.bean.defaultbean.DefaultBeanExtension"; //$NON-NLS-1$
private static String ID_30 = "org.jboss.seam.solder.bean.defaultbean.DefaultBeanExtension"; //$NON-NLS-1$
protected Map<String, Set<IBean>> defaultBeansByKey = new HashMap<String, Set<IBean>>();
public static CDISeamSolderDefaultBeanExtension getExtension(CDICoreNature project) {
ICDIExtension result = project.getExtensionManager().getExtensionByRuntime(ID);
if(result == null) {
result = project.getExtensionManager().getExtensionByRuntime(ID_30);
}
if(result instanceof CDISeamSolderDefaultBeanExtension) {
return (CDISeamSolderDefaultBeanExtension)result;
}
return null;
}
protected Version getVersion() {
return Version.instance;
}
public void processAnnotatedType(TypeDefinition typeDefinition, IRootDefinitionContext context) {
String defaultBeanAnnotationTypeName = getVersion().getDefaultBeanAnnotationTypeName();
boolean defaultBean = typeDefinition.isAnnotationPresent(defaultBeanAnnotationTypeName);
IJavaAnnotation beanTyped = null;
if(defaultBean) {
beanTyped = createFakeTypedAnnotation(typeDefinition, context);
if(beanTyped != null) {
typeDefinition.addAnnotation(beanTyped, context);
}
}
List<MethodDefinition> ms = typeDefinition.getMethods();
for (MethodDefinition m: ms) {
if(m.isAnnotationPresent(CDIConstants.PRODUCES_ANNOTATION_TYPE_NAME)) {
if(defaultBean || m.isAnnotationPresent(defaultBeanAnnotationTypeName)) {
IJavaAnnotation methodTyped = createFakeTypedAnnotation(m, context);
if(methodTyped != null) {
m.addAnnotation(methodTyped, context);
}
}
}
}
List<FieldDefinition> fs = typeDefinition.getFields();
for (FieldDefinition f: fs) {
if(f.isAnnotationPresent(CDIConstants.PRODUCES_ANNOTATION_TYPE_NAME)) {
if(defaultBean || f.isAnnotationPresent(defaultBeanAnnotationTypeName)) {
IJavaAnnotation fieldTyped = createFakeTypedAnnotation(f, context);
if(fieldTyped != null) {
f.addAnnotation(fieldTyped, context);
}
}
}
}
}
IJavaAnnotation createFakeTypedAnnotation(AbstractMemberDefinition def, IRootDefinitionContext context) {
IJavaAnnotation result = null;
IAnnotationDeclaration a = def.getAnnotation(getVersion().getDefaultBeanAnnotationTypeName());
if(a != null) {
Object n = a.getMemberValue(null);
if(n != null && n.toString().length() > 0) {
String defaultType = n.toString();
IType typedAnnotation = context.getProject().getType(CDIConstants.TYPED_ANNOTATION_TYPE_NAME);
if (typedAnnotation != null) {
result = new AnnotationLiteral(def.getResource(), a.getStartPosition(), a.getLength(), defaultType, IMemberValuePair.K_CLASS, typedAnnotation);
}
}
} else if(def instanceof BeanMemberDefinition) {
ITypeDeclaration type = BeanMember.getTypeDeclaration(def, context.getProject().getTypeFactory());
if(type != null) {
IType typedAnnotation = context.getProject().getType(CDIConstants.TYPED_ANNOTATION_TYPE_NAME);
if (typedAnnotation != null) {
result = new AnnotationLiteral(def.getResource(), type.getStartPosition(), type.getLength(), type.getType().getFullyQualifiedName(), IMemberValuePair.K_CLASS, typedAnnotation);
}
}
}
return result;
}
public Set<IBean> getResolvedBeans(Set<IBean> result) {
Set<IBean> defaultBeans = new HashSet<IBean>();
for (IBean b: result) {
if(isBeanDefault(b)) {
defaultBeans.add(b);
}
}
if(!defaultBeans.isEmpty() && defaultBeans.size() < result.size()) {
result.removeAll(defaultBeans);
}
return result;
}
public boolean isBeanDefault(IBean bean) {
String defaultBeanAnnotationTypeName = getVersion().getDefaultBeanAnnotationTypeName();
if(bean.isAnnotationPresent(defaultBeanAnnotationTypeName)) {
return true;
} else if(bean instanceof IProducer) {
IProducer producer = (IProducer)bean;
IClassBean parent = producer.getClassBean();
if(parent != null && parent.isAnnotationPresent(defaultBeanAnnotationTypeName)) {
return true;
}
}
return false;
}
public void validateResource(IFile file, CDICoreValidator validator) {
String defaultBeanAnnotationTypeName = getVersion().getDefaultBeanAnnotationTypeName();
ICDIProject cdiProject = CDICorePlugin.getCDIProject(file.getProject(), true);
+ if(cdiProject == null) return;
Set<IBean> bs = cdiProject.getBeans(file.getFullPath());
for (IBean bean: bs) {
if(isBeanDefault(bean)) {
ITextSourceReference a = bean.getAnnotation(defaultBeanAnnotationTypeName);
if(a == null) {
Set<ITypeDeclaration> ds = bean.getAllTypeDeclarations();
if(!ds.isEmpty()) {
IMember e = bean instanceof IJavaReference ? ((IJavaReference)bean).getSourceMember() : bean.getBeanClass();
a = CDIUtil.convertToJavaSourceReference(ds.iterator().next(), e);
} else {
continue;
}
}
if(bean instanceof IProducerField) {
IClassBean cb = ((IProducerField) bean).getClassBean();
IScope scope = cb.getScope();
if(scope != null && scope.isNorlmalScope()) {
validator.addError(SeamSolderValidationMessages.DEFAULT_PRODUCER_FIELD_ON_NORMAL_SCOPED_BEAN,
CDISeamSolderPreferences.DEFAULT_PRODUCER_FIELD_ON_NORMAL_SCOPED_BEAN, new String[]{}, a, file);
}
}
IQualifierDeclaration[] qs = bean.getQualifierDeclarations().toArray(new IQualifierDeclaration[0]);
IParametedType type = getDefaultType(bean);
if(type != null) {
String key = createKey(type, bean.getQualifierDeclarations(true));
Set<IBean> linked = defaultBeansByKey.get(key);
if(linked != null) {
for (IBean link: linked) {
if(link.getSourcePath() != null) {
validator.getValidationContext().addLinkedCoreResource(CDICoreValidator.SHORT_ID, key, link.getSourcePath(), true);
}
}
}
Set<IBean> bs2 = cdiProject.getBeans(false, type, qs);
StringBuilder otherDefaultBeans = new StringBuilder();
for (IBean b: bs2) {
try {
if(b != bean && isBeanDefault(b)
&& CDIProject.areMatchingQualifiers(bean.getQualifierDeclarations(), b.getQualifierDeclarations(true))) {
if(otherDefaultBeans.length() > 0) {
otherDefaultBeans.append(", ");
}
otherDefaultBeans.append(b.getElementName());
}
} catch (CoreException e) {
CDISeamSolderCorePlugin.getDefault().logError(e);
}
}
if(otherDefaultBeans.length() > 0) {
String message = NLS.bind(SeamSolderValidationMessages.IDENTICAL_DEFAULT_BEANS, otherDefaultBeans);
validator.addError(message, CDISeamSolderPreferences.IDENTICAL_DEFAULT_BEANS, new String[]{}, a, file);
}
}
}
}
}
public SeverityPreferences getSeverityPreferences() {
return CDISeamSolderPreferences.getInstance();
}
private IParametedType getDefaultType(IBean bean) {
Set<IParametedType> ts = bean.getLegalTypes();
if(ts.size() < 3) {
for (IParametedType t: ts) {
if(!"java.lang.Object".equals(t.getType().getFullyQualifiedName())) {
return t;
}
}
}
return null;
}
@Override
public String getKey(IBean bean) {
if(isBeanDefault(bean)) {
IParametedType type = getDefaultType(bean);
if(type != null) {
return createKey(type, bean.getQualifierDeclarations(true));
}
}
return null;
}
private String createKey(IParametedType type, Set<IQualifierDeclaration> qs) {
Set<String> ss = new TreeSet<String>();
for (IQualifierDeclaration q: qs) {
if(!q.getTypeName().equals(CDIConstants.ANY_QUALIFIER_TYPE_NAME)
&& !q.getTypeName().equals(CDIConstants.DEFAULT_QUALIFIER_TYPE_NAME)) {
ss.add(q.getTypeName());
}
}
StringBuilder sb = new StringBuilder();
sb.append("#DefaultBean_").append(type.getType().getFullyQualifiedName());
for (String s: ss) {
sb.append(':').append(s);
}
return sb.toString();
}
public synchronized void updateCaches(ICDIProject project) {
Map<String, Set<IBean>> map = new HashMap<String, Set<IBean>>();
IBean[] beans = project.getBeans();
for (IBean b: beans) {
String key = getKey(b);
if(key != null) {
Set<IBean> bs = map.get(key);
if(bs == null) {
bs = new HashSet<IBean>();
map.put(key, bs);
}
bs.add(b);
}
}
defaultBeansByKey = map;
}
}
| true | true | public void validateResource(IFile file, CDICoreValidator validator) {
String defaultBeanAnnotationTypeName = getVersion().getDefaultBeanAnnotationTypeName();
ICDIProject cdiProject = CDICorePlugin.getCDIProject(file.getProject(), true);
Set<IBean> bs = cdiProject.getBeans(file.getFullPath());
for (IBean bean: bs) {
if(isBeanDefault(bean)) {
ITextSourceReference a = bean.getAnnotation(defaultBeanAnnotationTypeName);
if(a == null) {
Set<ITypeDeclaration> ds = bean.getAllTypeDeclarations();
if(!ds.isEmpty()) {
IMember e = bean instanceof IJavaReference ? ((IJavaReference)bean).getSourceMember() : bean.getBeanClass();
a = CDIUtil.convertToJavaSourceReference(ds.iterator().next(), e);
} else {
continue;
}
}
if(bean instanceof IProducerField) {
IClassBean cb = ((IProducerField) bean).getClassBean();
IScope scope = cb.getScope();
if(scope != null && scope.isNorlmalScope()) {
validator.addError(SeamSolderValidationMessages.DEFAULT_PRODUCER_FIELD_ON_NORMAL_SCOPED_BEAN,
CDISeamSolderPreferences.DEFAULT_PRODUCER_FIELD_ON_NORMAL_SCOPED_BEAN, new String[]{}, a, file);
}
}
IQualifierDeclaration[] qs = bean.getQualifierDeclarations().toArray(new IQualifierDeclaration[0]);
IParametedType type = getDefaultType(bean);
if(type != null) {
String key = createKey(type, bean.getQualifierDeclarations(true));
Set<IBean> linked = defaultBeansByKey.get(key);
if(linked != null) {
for (IBean link: linked) {
if(link.getSourcePath() != null) {
validator.getValidationContext().addLinkedCoreResource(CDICoreValidator.SHORT_ID, key, link.getSourcePath(), true);
}
}
}
Set<IBean> bs2 = cdiProject.getBeans(false, type, qs);
StringBuilder otherDefaultBeans = new StringBuilder();
for (IBean b: bs2) {
try {
if(b != bean && isBeanDefault(b)
&& CDIProject.areMatchingQualifiers(bean.getQualifierDeclarations(), b.getQualifierDeclarations(true))) {
if(otherDefaultBeans.length() > 0) {
otherDefaultBeans.append(", ");
}
otherDefaultBeans.append(b.getElementName());
}
} catch (CoreException e) {
CDISeamSolderCorePlugin.getDefault().logError(e);
}
}
if(otherDefaultBeans.length() > 0) {
String message = NLS.bind(SeamSolderValidationMessages.IDENTICAL_DEFAULT_BEANS, otherDefaultBeans);
validator.addError(message, CDISeamSolderPreferences.IDENTICAL_DEFAULT_BEANS, new String[]{}, a, file);
}
}
}
}
}
| public void validateResource(IFile file, CDICoreValidator validator) {
String defaultBeanAnnotationTypeName = getVersion().getDefaultBeanAnnotationTypeName();
ICDIProject cdiProject = CDICorePlugin.getCDIProject(file.getProject(), true);
if(cdiProject == null) return;
Set<IBean> bs = cdiProject.getBeans(file.getFullPath());
for (IBean bean: bs) {
if(isBeanDefault(bean)) {
ITextSourceReference a = bean.getAnnotation(defaultBeanAnnotationTypeName);
if(a == null) {
Set<ITypeDeclaration> ds = bean.getAllTypeDeclarations();
if(!ds.isEmpty()) {
IMember e = bean instanceof IJavaReference ? ((IJavaReference)bean).getSourceMember() : bean.getBeanClass();
a = CDIUtil.convertToJavaSourceReference(ds.iterator().next(), e);
} else {
continue;
}
}
if(bean instanceof IProducerField) {
IClassBean cb = ((IProducerField) bean).getClassBean();
IScope scope = cb.getScope();
if(scope != null && scope.isNorlmalScope()) {
validator.addError(SeamSolderValidationMessages.DEFAULT_PRODUCER_FIELD_ON_NORMAL_SCOPED_BEAN,
CDISeamSolderPreferences.DEFAULT_PRODUCER_FIELD_ON_NORMAL_SCOPED_BEAN, new String[]{}, a, file);
}
}
IQualifierDeclaration[] qs = bean.getQualifierDeclarations().toArray(new IQualifierDeclaration[0]);
IParametedType type = getDefaultType(bean);
if(type != null) {
String key = createKey(type, bean.getQualifierDeclarations(true));
Set<IBean> linked = defaultBeansByKey.get(key);
if(linked != null) {
for (IBean link: linked) {
if(link.getSourcePath() != null) {
validator.getValidationContext().addLinkedCoreResource(CDICoreValidator.SHORT_ID, key, link.getSourcePath(), true);
}
}
}
Set<IBean> bs2 = cdiProject.getBeans(false, type, qs);
StringBuilder otherDefaultBeans = new StringBuilder();
for (IBean b: bs2) {
try {
if(b != bean && isBeanDefault(b)
&& CDIProject.areMatchingQualifiers(bean.getQualifierDeclarations(), b.getQualifierDeclarations(true))) {
if(otherDefaultBeans.length() > 0) {
otherDefaultBeans.append(", ");
}
otherDefaultBeans.append(b.getElementName());
}
} catch (CoreException e) {
CDISeamSolderCorePlugin.getDefault().logError(e);
}
}
if(otherDefaultBeans.length() > 0) {
String message = NLS.bind(SeamSolderValidationMessages.IDENTICAL_DEFAULT_BEANS, otherDefaultBeans);
validator.addError(message, CDISeamSolderPreferences.IDENTICAL_DEFAULT_BEANS, new String[]{}, a, file);
}
}
}
}
}
|
diff --git a/net.todd.games.balls.common/src/test/java/net/todd/games/balls/common/BallToStringTest.java b/net.todd.games.balls.common/src/test/java/net/todd/games/balls/common/BallToStringTest.java
index 8dedd72..5c2cf2c 100644
--- a/net.todd.games.balls.common/src/test/java/net/todd/games/balls/common/BallToStringTest.java
+++ b/net.todd.games.balls.common/src/test/java/net/todd/games/balls/common/BallToStringTest.java
@@ -1,30 +1,31 @@
package net.todd.games.balls.common;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BallToStringTest {
@Test
public void testBallToString() {
Ball ball = new Ball();
ball.setId("123");
ball.setColorRed(1);
ball.setColorGreen(2);
ball.setColorBlue(3);
ball.setPositionX(4);
ball.setPositionY(5);
- assertEquals("Ball[123]: Color: {1, 2, 3}, Position: {4, 5}", ball.toString());
+ assertEquals("Ball[123]: Color: {1, 2, 3}, Position: {4.0, 5.0}", ball.toString());
Ball ball2 = new Ball();
ball2.setId("456");
ball2.setColorRed(5);
ball2.setColorGreen(6);
ball2.setColorBlue(7);
ball2.setPositionX(8);
ball2.setPositionY(9);
- assertEquals("Ball[456]: Color: {5, 6, 7}, Position: {8, 9}", ball2.toString());
+ assertEquals("Ball[456]: Color: {5, 6, 7}, Position: {8.0, 9.0}", ball2
+ .toString());
}
}
| false | true | public void testBallToString() {
Ball ball = new Ball();
ball.setId("123");
ball.setColorRed(1);
ball.setColorGreen(2);
ball.setColorBlue(3);
ball.setPositionX(4);
ball.setPositionY(5);
assertEquals("Ball[123]: Color: {1, 2, 3}, Position: {4, 5}", ball.toString());
Ball ball2 = new Ball();
ball2.setId("456");
ball2.setColorRed(5);
ball2.setColorGreen(6);
ball2.setColorBlue(7);
ball2.setPositionX(8);
ball2.setPositionY(9);
assertEquals("Ball[456]: Color: {5, 6, 7}, Position: {8, 9}", ball2.toString());
}
| public void testBallToString() {
Ball ball = new Ball();
ball.setId("123");
ball.setColorRed(1);
ball.setColorGreen(2);
ball.setColorBlue(3);
ball.setPositionX(4);
ball.setPositionY(5);
assertEquals("Ball[123]: Color: {1, 2, 3}, Position: {4.0, 5.0}", ball.toString());
Ball ball2 = new Ball();
ball2.setId("456");
ball2.setColorRed(5);
ball2.setColorGreen(6);
ball2.setColorBlue(7);
ball2.setPositionX(8);
ball2.setPositionY(9);
assertEquals("Ball[456]: Color: {5, 6, 7}, Position: {8.0, 9.0}", ball2
.toString());
}
|
diff --git a/bootstrap/src/main/java/org/soluvas/web/bootstrap/BootstrapPage.java b/bootstrap/src/main/java/org/soluvas/web/bootstrap/BootstrapPage.java
index 0da68617..33619309 100644
--- a/bootstrap/src/main/java/org/soluvas/web/bootstrap/BootstrapPage.java
+++ b/bootstrap/src/main/java/org/soluvas/web/bootstrap/BootstrapPage.java
@@ -1,619 +1,624 @@
package org.soluvas.web.bootstrap;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.devutils.debugbar.DebugBar;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.JavaScriptReferenceHeaderItem;
import org.apache.wicket.markup.html.TransparentWebMarkupContainer;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.CssResourceReference;
import org.apache.wicket.request.resource.UrlResourceReference;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soluvas.commons.AppManifest;
import org.soluvas.commons.WebAddress;
import org.soluvas.commons.tenant.TenantRef;
import org.soluvas.data.repository.CrudRepository;
import org.soluvas.web.nav.PageLink;
import org.soluvas.web.site.AmdJavaScriptSource;
import org.soluvas.web.site.CssLink;
import org.soluvas.web.site.ExtensiblePage;
import org.soluvas.web.site.JavaScriptLink;
import org.soluvas.web.site.JavaScriptMode;
import org.soluvas.web.site.JavaScriptSource;
import org.soluvas.web.site.PageMetaProvider;
import org.soluvas.web.site.PageRequestContext;
import org.soluvas.web.site.RequireManager;
import org.soluvas.web.site.Site;
import org.soluvas.web.site.alexa.AlexaCertify;
import org.soluvas.web.site.alexa.AlexaCertifyScript;
import org.soluvas.web.site.client.AmdDependency;
import org.soluvas.web.site.client.JsSource;
import org.soluvas.web.site.compose.ComposeUtils;
import org.soluvas.web.site.compose.LiveContributor;
import org.soluvas.web.site.pagemeta.PageMeta;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Ordering;
import de.agilecoders.wicket.markup.html.references.BootstrapJavaScriptReference;
/**
* Base page for Twitter Bootstrap-powered Wicket pages.
*
* @author ceefour
*/
public class BootstrapPage extends ExtensiblePage {
private static final long serialVersionUID = 1L;
public static enum SidebarVisibility {
VISIBLE,
HIDDEN
}
public static enum AddedInfoVisibility {
VISIBLE,
HIDDEN
}
public static class MetaTag extends WebMarkupContainer {
/**
* @param id
* @param model
*/
public MetaTag(String id, IModel<String> model) {
super(id, model);
add(new AttributeModifier("content", model));
}
@Override
protected void onConfigure() {
super.onConfigure();
setVisible(!Strings.isNullOrEmpty(getDefaultModelObjectAsString()));
}
}
/**
* Usage:
*
* <pre>
* {
* @code
* final Builder<String, String> dependencies = ImmutableMap.builder();
* new AmdDependencyVisitor(dependencies).component(BootstrapPage.this, null);
* visitChildren(new AmdDependencyVisitor(dependencies));
* final Map<String, String> dependencyMap = dependencies.build();
* log.debug("Page {} has {} AMD dependencies: {}", getClass().getName(),
* dependencyMap.size(), dependencyMap.keySet());
* }
* </pre>
*
* @author ceefour
*/
public static final class AmdDependencyVisitor implements
IVisitor<Component, Void> {
private final Map<String, String> dependencies;
public AmdDependencyVisitor(Map<String, String> dependencyMap) {
this.dependencies = dependencyMap;
}
@Override
public void component(Component component, IVisit<Void> visit) {
final List<AmdDependency> amdDeps = component
.getBehaviors(AmdDependency.class);
for (AmdDependency dep : amdDeps) {
dependencies.put(dep.getPath(), dep.getName());
}
}
}
public static final class JsSourceVisitor implements
IVisitor<Component, Void> {
private final ImmutableList.Builder<String> jsSources;
public JsSourceVisitor(ImmutableList.Builder<String> jsSources) {
this.jsSources = jsSources;
}
@Override
public void component(Component component, IVisit<Void> visit) {
List<JsSource> jsSourceBehaviors = component
.getBehaviors(JsSource.class);
for (JsSource src : jsSourceBehaviors) {
jsSources.add(src.getJsSource());
}
}
}
private static final Logger log = LoggerFactory
.getLogger(BootstrapPage.class);
public static final CssResourceReference BOOTSTRAP_PRINT_CSS = new CssResourceReference(BootstrapPage.class, "bootstrap-print.css");
@SpringBean(name="jacksonMapperFactory")
private Supplier<ObjectMapper> jacksonMapperFactory;
/**
* Should not use {@link Site} directly!
*/
// @Deprecated
// private Site site;
@SpringBean(name="cssLinks")
private List<CssLink> cssLinks;
@SpringBean(name="headJavaScripts")
private List<JavaScriptLink> headJavaScripts;
@SpringBean(name="requireMgr")
protected RequireManager requireMgr;
@SpringBean(name="footerJavaScripts")
private List<JavaScriptLink> footerJavaScripts;
@SpringBean(name="footerJavaScriptSources")
private List<JavaScriptSource> footerJavaScriptSources;
protected final RepeatingView sidebarBlocks;
// @SpringBean(name="pageMetaSupplierFactory")
// private PageMetaSupplierFactory<PageMetaSupplier> pageMetaSupplierFactory;
@SpringBean
private PageMetaProvider pageMetaProvider;
@SpringBean
protected WebAddress webAddress;
@SpringBean(name="appManifest")
protected AppManifest appManifest;
@SpringBean(name="contributorRepo")
private CrudRepository<LiveContributor, Integer> contributors;
@SpringBean(name="alexaCertify")
protected AlexaCertify alexaCertify;
protected Component feedbackPanel;
protected Component contentAddedInfo;
protected TransparentWebMarkupContainer contentColumn;
protected TransparentWebMarkupContainer sidebarColumn;
@SpringBean
private TenantRef tenant;
protected final RepeatingView afterHeader;
protected AddedInfoVisibility addedInfoVisibility;
protected SidebarVisibility sidebarVisibility;
protected Navbar navbar;
private final IModel<List<PageLink>> breadcrumbModel = new LoadableDetachableModel<List<PageLink>>() {
@Override
protected List<PageLink> load() {
final ArrayList<PageLink> pageLinks = new ArrayList<>();
createPageLinksForBreadcrumb(pageLinks);
return pageLinks;
}
};
/**
* @param pageLinks Mutable.
*/
protected void createPageLinksForBreadcrumb(List<PageLink> pageLinks) {
}
// do NOT use AsyncModel here because we need it to load LAST
// (i.e. after all scopes has been attached as page model using
// addModelForPageMeta)
protected final IModel<PageMeta> pageMetaModel = new LoadableDetachableModel<PageMeta>() {
@Override
protected PageMeta load() {
final String currentUri = getRequest().getUrl().toString();
final PageRequestContext context = new PageRequestContext(
tenant.getClientId(), tenant.getTenantId(),
tenant.getTenantEnv(), BootstrapPage.this, currentUri, webAddress,
appManifest);
// final List<PageRule> pageRules = pageRulesSupplier.get();
// final PageMetaSupplier pageSupplier = new
// RulesPageMetaSupplier(pageRules, context);
final PageMeta pageMeta = pageMetaProvider.get(context);
return pageMeta;
}
};
@SuppressWarnings("deprecation")
public String smartPrefixUri(String prefix, String uri) {
if (uri.startsWith("//") || uri.startsWith("https:")
|| uri.startsWith("http:")) {
return uri;
} else {
// cache bust for relative CSS URIs
final String suffix = Strings.isNullOrEmpty(requireMgr
.getCacheBust()) ? "" : "?"
+ URLEncoder.encode(requireMgr.getCacheBust());
return prefix + uri + suffix;
}
}
@Override
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(JavaScriptReferenceHeaderItem
.forReference(getApplication().getJavaScriptLibrarySettings()
.getJQueryReference()));
// TODO: workaround before we have proper wicket-bootstrap integration
response.render(
JavaScriptReferenceHeaderItem.forReference(BootstrapJavaScriptReference.instance()));
// doesn't work, nginx as of 1.3.15 disables Etag if content is gzipped
// if (requireMgr.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT) {
// response.render(JavaScriptReferenceHeaderItem
// .forUrl(webAddress.getJsUri() + "org.soluvas.web.bootstrap/live-soluvas.js"));
// }
final String currentStyle = getStyle();
final List<CssLink> filteredCsses = ImmutableList.copyOf(Collections2
.filter(cssLinks, new Predicate<CssLink>() {
@Override
public boolean apply(@Nullable CssLink input) {
return Strings.isNullOrEmpty(input.getStyle())
|| "*".equals(input.getStyle())
|| Objects.equal(currentStyle, input.getStyle());
}
}));
log.trace("Page {} has {} CSS links (from {} total)", getClass()
.getName(), filteredCsses.size(), cssLinks.size());
final Ordering<CssLink> cssOrdering = Ordering
.from(new Comparator<CssLink>() {
@Override
public int compare(CssLink o1, CssLink o2) {
return o1.getWeight() - o2.getWeight();
};
});
final List<CssLink> sortedCsses = cssOrdering
.immutableSortedCopy(filteredCsses);
for (CssLink css : sortedCsses) {
if (requireMgr.getJavaScriptMode() != JavaScriptMode.DEVELOPMENT
&& css.getMinifiedPath() != null) {
response.render(CssHeaderItem.forUrl(smartPrefixUri(
webAddress.getSkinUri(), css.getMinifiedPath())));
} else {
response.render(CssHeaderItem.forUrl(smartPrefixUri(
webAddress.getSkinUri(), css.getPath())));
}
}
response.render(CssHeaderItem.forReference(BOOTSTRAP_PRINT_CSS, "print"));
log.trace("Page {} has {} head JavaScript links", getClass().getName(),
headJavaScripts.size());
final Ordering<JavaScriptLink> jsOrdering = Ordering
.from(new Comparator<JavaScriptLink>() {
@Override
public int compare(JavaScriptLink o1, JavaScriptLink o2) {
return o1.getWeight() - o2.getWeight();
};
});
final List<JavaScriptLink> sortedJses = jsOrdering
.immutableSortedCopy(headJavaScripts);
for (JavaScriptLink js : sortedJses) {
response.render(JavaScriptHeaderItem.forUrl(js.getSrc()));
}
response.render(JavaScriptHeaderItem.forReference(TinyNavJs.INSTANCE));
response.render(JavaScriptHeaderItem.forReference(ToTopJs.EASING));
response.render(JavaScriptHeaderItem.forReference(ToTopJs.TO_TOP));
}
@Override
protected void renderPlaceholderTag(ComponentTag tag, Response response) {
super.renderPlaceholderTag(tag, response);
}
/**
* Please override this.
*
* @return
*/
protected String getTitle() {
return null;
}
public BootstrapPage() {
this(null, SidebarVisibility.VISIBLE);
}
public BootstrapPage(PageParameters params, SidebarVisibility sidebarVisibility) {
super(params);
this.sidebarVisibility = sidebarVisibility;
this.addedInfoVisibility = AddedInfoVisibility.HIDDEN;
if (getApplication().getDebugSettings().isDevelopmentUtilitiesEnabled()) {
- log.trace("Enabling Wicket development utilities: DebugBar");
- add(new DebugBar("dev"));
+ try {
+ add(new DebugBar("dev"));
+ log.trace("Enabled Wicket development utilities: DebugBar");
+ } catch (NoClassDefFoundError e) {
+ log.debug("Cannot enable DebugBar in development mode, if you want to use it please add 'wicket-devutils' dependency", e);
+ add(new EmptyPanel("dev").setVisible(false));
+ }
} else {
add(new EmptyPanel("dev").setVisible(false));
}
// Use CDN jQuery if we're in production
if (requireMgr.getJavaScriptMode() != JavaScriptMode.DEVELOPMENT) {
getApplication()
.getJavaScriptLibrarySettings()
.setJQueryReference(
new UrlResourceReference(
Url.parse("http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js")));
}
final Ordering<JavaScriptSource> sourceOrdering = Ordering.natural();
final Ordering<JavaScriptLink> linkOrdering = Ordering.natural();
// HTML
add(new TransparentWebMarkupContainer("html")
.add(new AttributeModifier("lang", new PropertyModel<String>(
pageMetaModel, "languageCode"))));
// HEAD
// add(new Label("pageTitle", "Welcome").setRenderBodyOnly(true));
// do NOT use AsyncModel here, because it depends on PageMeta model
// loading last
final IModel<String> titleModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
return Optional
.fromNullable(getTitle())
.or(Optional.fromNullable(pageMetaModel.getObject()
.getTitle())).orNull();
}
};
final IModel<String> titleSuffixModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
return " | " + appManifest.getTitle();
}
};
add(new Label("pageTitle", titleModel).setRenderBodyOnly(true));
add(new Label("pageTitleSuffix", titleSuffixModel)
.setRenderBodyOnly(true));
final WebMarkupContainer faviconLink = new WebMarkupContainer(
"faviconLink");
faviconLink
.add(new AttributeModifier("href",
new PropertyModel<String>(pageMetaModel,
"icon.faviconUri")));
add(faviconLink);
add(new MetaTag("metaDescription", new PropertyModel<String>(pageMetaModel, "description")),
new MetaTag("ogKeywords", new PropertyModel<String>(pageMetaModel, "keywords")),
new MetaTag("ogTitle", new PropertyModel<String>(pageMetaModel, "openGraph.title")),
new MetaTag("ogType", new PropertyModel<String>(pageMetaModel,"openGraph.type")),
new MetaTag("ogUrl", new PropertyModel<String>(pageMetaModel, "openGraph.url")),
new MetaTag("ogImage", new PropertyModel<String>(pageMetaModel,"openGraph.image")));
final String bootstrapCssUri = requireMgr.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ? webAddress
.getSkinUri()
+ "org.soluvas.web.bootstrap/css/bootstrap.css"
: "//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css";
final String bootstrapResponsiveCssUri = requireMgr
.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ? webAddress
.getSkinUri()
+ "org.soluvas.web.bootstrap/css/bootstrap-responsive.css"
: "//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-responsive.min.css";
add(new WebMarkupContainer("bootstrapCss")
.add(new AttributeModifier("href", bootstrapCssUri)));
add(new WebMarkupContainer("bootstrapResponsiveCss")
.add(new AttributeModifier("href",
bootstrapResponsiveCssUri)));
add(new WebMarkupContainer("soluvasCss")
.add(new AttributeModifier(
"href",
webAddress.getSkinUri()
+ "org.soluvas.web.bootstrap/css/soluvas.css")));
// For now we use soluvas's fork of RequireJS.
// See https://github.com/jrburke/requirejs/issues/376 for reasons.
// too bad we can't use "//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.4/require.min.js";
final String requireJsUri = requireMgr.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ?
webAddress .getJsUri() + "org.soluvas.web.bootstrap/require-2.1.5-soluvas.js" :
webAddress.getJsUri() + "org.soluvas.web.bootstrap/require-2.1.5-soluvas.min.js";
add(new WebMarkupContainer("requireJs").add(new AttributeModifier(
"src", requireJsUri)));
// Carousel
add(afterHeader = new RepeatingView("afterHeader"));
navbar = new Navbar("navbar");
add(navbar);
// add(new Label("logoText",
// site.getLogoText()).setRenderBodyOnly(true));
// add(new Label("logoAlt",
// site.getLogoAlt()).setRenderBodyOnly(true));
navbar.add(new BookmarkablePageLink<Page>("homeLink",
getApplication().getHomePage()) {
{
this.setBody(new Model<String>(appManifest.getTitle()));
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
tag.getAttributes().put("title", appManifest.getTitle());
}
});
add(new Header());
final String requireConfigPath = webAddress.getApiPath()
+ "org.soluvas.web.site/requireConfig.js";
add(new WebMarkupContainer("requireConfig")
.add(new AttributeModifier("src", requireConfigPath)));
// ADDED INFO
contentAddedInfo = new WebMarkupContainer("addedInfo");
add(contentAddedInfo);
// SIDEBAR
sidebarColumn = new TransparentWebMarkupContainer("sidebarColumn");
add(sidebarColumn);
sidebarBlocks = new RepeatingView("sidebarBlocks");
sidebarColumn.add(sidebarBlocks);
// CONTENT
contentColumn = new TransparentWebMarkupContainer("contentColumn");
add(contentColumn);
feedbackPanel = new FeedbackPanel("feedback")
.setOutputMarkupId(true);
add(feedbackPanel);
// FOOTER
add(new Footer("© " + new DateTime().toString("yyyy") + " " + appManifest.getTitle()));
// JAVASCRIPT
final RepeatingView beforeFooterJs = new RepeatingView("beforeFooterJs");
add(beforeFooterJs);
log.trace("Page {} has {} footer JavaScript links", getClass()
.getName(), footerJavaScripts.size());
final List<JavaScriptLink> sortedJsLinks = linkOrdering
.immutableSortedCopy(footerJavaScripts);
final RepeatingView footerJavaScriptLinks = new RepeatingView(
"footerJavaScriptLinks");
for (JavaScriptLink js : sortedJsLinks) {
footerJavaScriptLinks.add(new WebMarkupContainer(
footerJavaScriptLinks.newChildId())
.add(new AttributeModifier("src", js.getSrc())));
}
add(footerJavaScriptLinks);
log.trace("Page {} has {} footer JavaScript sources", getClass()
.getName(), footerJavaScriptSources.size());
final List<JavaScriptSource> sortedJsSources = sourceOrdering
.immutableSortedCopy(footerJavaScriptSources);
final RepeatingView footerJavaScriptSources = new RepeatingView(
"footerJavaScriptSources");
for (JavaScriptSource js : sortedJsSources) {
footerJavaScriptSources
.add(new Label(footerJavaScriptSources.newChildId(), js
.getScript()).setEscapeModelStrings(false));
}
add(footerJavaScriptSources);
final IModel<String> pageJavaScriptSourcesModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
// cannot use ImmutableMap, because AMD dependencies can be duplicated
final Map<String, String> dependencyMap = new HashMap<>();
final AmdDependencyVisitor amdDependencyVisitor = new AmdDependencyVisitor(
dependencyMap);
amdDependencyVisitor.component(BootstrapPage.this, null);
visitChildren(amdDependencyVisitor);
log.trace("Page {} has {} AMD dependencies: {}", getClass()
.getName(), dependencyMap.size(), dependencyMap.keySet());
final ImmutableList.Builder<String> pageJsSourcesBuilder = ImmutableList
.builder();
final JsSourceVisitor jsSourceVisitor = new JsSourceVisitor(
pageJsSourcesBuilder);
jsSourceVisitor.component(BootstrapPage.this, null);
visitChildren(jsSourceVisitor);
final List<String> pageJsSources = pageJsSourcesBuilder.build();
log.trace("Page {} has {} page JavaScript sources", getClass()
.getName(), pageJsSources.size());
final String merged = Joiner.on('\n').join(pageJsSources);
JavaScriptSource js = new AmdJavaScriptSource(merged,
dependencyMap);
return js.getScript();
};
};
add(new Label("pageJavaScriptSources", pageJavaScriptSourcesModel)
.setEscapeModelStrings(false));
add(new AlexaCertifyScript("alexaCertifyScript", new Model<>(alexaCertify)));
add(new GrowlBehavior());
}
@Override
protected void onInitialize() {
super.onInitialize();
// sidebar visibility
if (sidebarVisibility == SidebarVisibility.HIDDEN) {
sidebarColumn.setVisible(false);
contentColumn.add(new AttributeModifier("class", "span12"));
}
// compose other components
ComposeUtils.compose(this, contributors.findAll());
if (addedInfoVisibility == AddedInfoVisibility.VISIBLE) {
contentAddedInfo.setVisible(true);
}
}
@Override
protected void onConfigure() {
super.onConfigure();
final List<String> visibleChildren = new ArrayList<>();
for (Component child : sidebarBlocks) {
child.configure();
if (child.isVisible()) {
visibleChildren.add(child.getPageRelativePath());
}
}
log.debug("Visible sidebarBlocks children: {}", visibleChildren);
sidebarColumn.setVisible(!visibleChildren.isEmpty());
}
public IModel<PageMeta> getPageMetaModel() {
return pageMetaModel;
}
public IModel<List<PageLink>> getBreadcrumbModel() {
return breadcrumbModel;
}
@Override
protected void detachModel() {
super.detachModel();
pageMetaModel.detach();
breadcrumbModel.detach();
}
}
| true | true | public BootstrapPage(PageParameters params, SidebarVisibility sidebarVisibility) {
super(params);
this.sidebarVisibility = sidebarVisibility;
this.addedInfoVisibility = AddedInfoVisibility.HIDDEN;
if (getApplication().getDebugSettings().isDevelopmentUtilitiesEnabled()) {
log.trace("Enabling Wicket development utilities: DebugBar");
add(new DebugBar("dev"));
} else {
add(new EmptyPanel("dev").setVisible(false));
}
// Use CDN jQuery if we're in production
if (requireMgr.getJavaScriptMode() != JavaScriptMode.DEVELOPMENT) {
getApplication()
.getJavaScriptLibrarySettings()
.setJQueryReference(
new UrlResourceReference(
Url.parse("http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js")));
}
final Ordering<JavaScriptSource> sourceOrdering = Ordering.natural();
final Ordering<JavaScriptLink> linkOrdering = Ordering.natural();
// HTML
add(new TransparentWebMarkupContainer("html")
.add(new AttributeModifier("lang", new PropertyModel<String>(
pageMetaModel, "languageCode"))));
// HEAD
// add(new Label("pageTitle", "Welcome").setRenderBodyOnly(true));
// do NOT use AsyncModel here, because it depends on PageMeta model
// loading last
final IModel<String> titleModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
return Optional
.fromNullable(getTitle())
.or(Optional.fromNullable(pageMetaModel.getObject()
.getTitle())).orNull();
}
};
final IModel<String> titleSuffixModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
return " | " + appManifest.getTitle();
}
};
add(new Label("pageTitle", titleModel).setRenderBodyOnly(true));
add(new Label("pageTitleSuffix", titleSuffixModel)
.setRenderBodyOnly(true));
final WebMarkupContainer faviconLink = new WebMarkupContainer(
"faviconLink");
faviconLink
.add(new AttributeModifier("href",
new PropertyModel<String>(pageMetaModel,
"icon.faviconUri")));
add(faviconLink);
add(new MetaTag("metaDescription", new PropertyModel<String>(pageMetaModel, "description")),
new MetaTag("ogKeywords", new PropertyModel<String>(pageMetaModel, "keywords")),
new MetaTag("ogTitle", new PropertyModel<String>(pageMetaModel, "openGraph.title")),
new MetaTag("ogType", new PropertyModel<String>(pageMetaModel,"openGraph.type")),
new MetaTag("ogUrl", new PropertyModel<String>(pageMetaModel, "openGraph.url")),
new MetaTag("ogImage", new PropertyModel<String>(pageMetaModel,"openGraph.image")));
final String bootstrapCssUri = requireMgr.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ? webAddress
.getSkinUri()
+ "org.soluvas.web.bootstrap/css/bootstrap.css"
: "//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css";
final String bootstrapResponsiveCssUri = requireMgr
.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ? webAddress
.getSkinUri()
+ "org.soluvas.web.bootstrap/css/bootstrap-responsive.css"
: "//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-responsive.min.css";
add(new WebMarkupContainer("bootstrapCss")
.add(new AttributeModifier("href", bootstrapCssUri)));
add(new WebMarkupContainer("bootstrapResponsiveCss")
.add(new AttributeModifier("href",
bootstrapResponsiveCssUri)));
add(new WebMarkupContainer("soluvasCss")
.add(new AttributeModifier(
"href",
webAddress.getSkinUri()
+ "org.soluvas.web.bootstrap/css/soluvas.css")));
// For now we use soluvas's fork of RequireJS.
// See https://github.com/jrburke/requirejs/issues/376 for reasons.
// too bad we can't use "//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.4/require.min.js";
final String requireJsUri = requireMgr.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ?
webAddress .getJsUri() + "org.soluvas.web.bootstrap/require-2.1.5-soluvas.js" :
webAddress.getJsUri() + "org.soluvas.web.bootstrap/require-2.1.5-soluvas.min.js";
add(new WebMarkupContainer("requireJs").add(new AttributeModifier(
"src", requireJsUri)));
// Carousel
add(afterHeader = new RepeatingView("afterHeader"));
navbar = new Navbar("navbar");
add(navbar);
// add(new Label("logoText",
// site.getLogoText()).setRenderBodyOnly(true));
// add(new Label("logoAlt",
// site.getLogoAlt()).setRenderBodyOnly(true));
navbar.add(new BookmarkablePageLink<Page>("homeLink",
getApplication().getHomePage()) {
{
this.setBody(new Model<String>(appManifest.getTitle()));
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
tag.getAttributes().put("title", appManifest.getTitle());
}
});
add(new Header());
final String requireConfigPath = webAddress.getApiPath()
+ "org.soluvas.web.site/requireConfig.js";
add(new WebMarkupContainer("requireConfig")
.add(new AttributeModifier("src", requireConfigPath)));
// ADDED INFO
contentAddedInfo = new WebMarkupContainer("addedInfo");
add(contentAddedInfo);
// SIDEBAR
sidebarColumn = new TransparentWebMarkupContainer("sidebarColumn");
add(sidebarColumn);
sidebarBlocks = new RepeatingView("sidebarBlocks");
sidebarColumn.add(sidebarBlocks);
// CONTENT
contentColumn = new TransparentWebMarkupContainer("contentColumn");
add(contentColumn);
feedbackPanel = new FeedbackPanel("feedback")
.setOutputMarkupId(true);
add(feedbackPanel);
// FOOTER
add(new Footer("© " + new DateTime().toString("yyyy") + " " + appManifest.getTitle()));
// JAVASCRIPT
final RepeatingView beforeFooterJs = new RepeatingView("beforeFooterJs");
add(beforeFooterJs);
log.trace("Page {} has {} footer JavaScript links", getClass()
.getName(), footerJavaScripts.size());
final List<JavaScriptLink> sortedJsLinks = linkOrdering
.immutableSortedCopy(footerJavaScripts);
final RepeatingView footerJavaScriptLinks = new RepeatingView(
"footerJavaScriptLinks");
for (JavaScriptLink js : sortedJsLinks) {
footerJavaScriptLinks.add(new WebMarkupContainer(
footerJavaScriptLinks.newChildId())
.add(new AttributeModifier("src", js.getSrc())));
}
add(footerJavaScriptLinks);
log.trace("Page {} has {} footer JavaScript sources", getClass()
.getName(), footerJavaScriptSources.size());
final List<JavaScriptSource> sortedJsSources = sourceOrdering
.immutableSortedCopy(footerJavaScriptSources);
final RepeatingView footerJavaScriptSources = new RepeatingView(
"footerJavaScriptSources");
for (JavaScriptSource js : sortedJsSources) {
footerJavaScriptSources
.add(new Label(footerJavaScriptSources.newChildId(), js
.getScript()).setEscapeModelStrings(false));
}
add(footerJavaScriptSources);
final IModel<String> pageJavaScriptSourcesModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
// cannot use ImmutableMap, because AMD dependencies can be duplicated
final Map<String, String> dependencyMap = new HashMap<>();
final AmdDependencyVisitor amdDependencyVisitor = new AmdDependencyVisitor(
dependencyMap);
amdDependencyVisitor.component(BootstrapPage.this, null);
visitChildren(amdDependencyVisitor);
log.trace("Page {} has {} AMD dependencies: {}", getClass()
.getName(), dependencyMap.size(), dependencyMap.keySet());
final ImmutableList.Builder<String> pageJsSourcesBuilder = ImmutableList
.builder();
final JsSourceVisitor jsSourceVisitor = new JsSourceVisitor(
pageJsSourcesBuilder);
jsSourceVisitor.component(BootstrapPage.this, null);
visitChildren(jsSourceVisitor);
final List<String> pageJsSources = pageJsSourcesBuilder.build();
log.trace("Page {} has {} page JavaScript sources", getClass()
.getName(), pageJsSources.size());
final String merged = Joiner.on('\n').join(pageJsSources);
JavaScriptSource js = new AmdJavaScriptSource(merged,
dependencyMap);
return js.getScript();
};
};
add(new Label("pageJavaScriptSources", pageJavaScriptSourcesModel)
.setEscapeModelStrings(false));
add(new AlexaCertifyScript("alexaCertifyScript", new Model<>(alexaCertify)));
add(new GrowlBehavior());
}
| public BootstrapPage(PageParameters params, SidebarVisibility sidebarVisibility) {
super(params);
this.sidebarVisibility = sidebarVisibility;
this.addedInfoVisibility = AddedInfoVisibility.HIDDEN;
if (getApplication().getDebugSettings().isDevelopmentUtilitiesEnabled()) {
try {
add(new DebugBar("dev"));
log.trace("Enabled Wicket development utilities: DebugBar");
} catch (NoClassDefFoundError e) {
log.debug("Cannot enable DebugBar in development mode, if you want to use it please add 'wicket-devutils' dependency", e);
add(new EmptyPanel("dev").setVisible(false));
}
} else {
add(new EmptyPanel("dev").setVisible(false));
}
// Use CDN jQuery if we're in production
if (requireMgr.getJavaScriptMode() != JavaScriptMode.DEVELOPMENT) {
getApplication()
.getJavaScriptLibrarySettings()
.setJQueryReference(
new UrlResourceReference(
Url.parse("http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js")));
}
final Ordering<JavaScriptSource> sourceOrdering = Ordering.natural();
final Ordering<JavaScriptLink> linkOrdering = Ordering.natural();
// HTML
add(new TransparentWebMarkupContainer("html")
.add(new AttributeModifier("lang", new PropertyModel<String>(
pageMetaModel, "languageCode"))));
// HEAD
// add(new Label("pageTitle", "Welcome").setRenderBodyOnly(true));
// do NOT use AsyncModel here, because it depends on PageMeta model
// loading last
final IModel<String> titleModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
return Optional
.fromNullable(getTitle())
.or(Optional.fromNullable(pageMetaModel.getObject()
.getTitle())).orNull();
}
};
final IModel<String> titleSuffixModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
return " | " + appManifest.getTitle();
}
};
add(new Label("pageTitle", titleModel).setRenderBodyOnly(true));
add(new Label("pageTitleSuffix", titleSuffixModel)
.setRenderBodyOnly(true));
final WebMarkupContainer faviconLink = new WebMarkupContainer(
"faviconLink");
faviconLink
.add(new AttributeModifier("href",
new PropertyModel<String>(pageMetaModel,
"icon.faviconUri")));
add(faviconLink);
add(new MetaTag("metaDescription", new PropertyModel<String>(pageMetaModel, "description")),
new MetaTag("ogKeywords", new PropertyModel<String>(pageMetaModel, "keywords")),
new MetaTag("ogTitle", new PropertyModel<String>(pageMetaModel, "openGraph.title")),
new MetaTag("ogType", new PropertyModel<String>(pageMetaModel,"openGraph.type")),
new MetaTag("ogUrl", new PropertyModel<String>(pageMetaModel, "openGraph.url")),
new MetaTag("ogImage", new PropertyModel<String>(pageMetaModel,"openGraph.image")));
final String bootstrapCssUri = requireMgr.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ? webAddress
.getSkinUri()
+ "org.soluvas.web.bootstrap/css/bootstrap.css"
: "//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css";
final String bootstrapResponsiveCssUri = requireMgr
.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ? webAddress
.getSkinUri()
+ "org.soluvas.web.bootstrap/css/bootstrap-responsive.css"
: "//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-responsive.min.css";
add(new WebMarkupContainer("bootstrapCss")
.add(new AttributeModifier("href", bootstrapCssUri)));
add(new WebMarkupContainer("bootstrapResponsiveCss")
.add(new AttributeModifier("href",
bootstrapResponsiveCssUri)));
add(new WebMarkupContainer("soluvasCss")
.add(new AttributeModifier(
"href",
webAddress.getSkinUri()
+ "org.soluvas.web.bootstrap/css/soluvas.css")));
// For now we use soluvas's fork of RequireJS.
// See https://github.com/jrburke/requirejs/issues/376 for reasons.
// too bad we can't use "//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.4/require.min.js";
final String requireJsUri = requireMgr.getJavaScriptMode() == JavaScriptMode.DEVELOPMENT ?
webAddress .getJsUri() + "org.soluvas.web.bootstrap/require-2.1.5-soluvas.js" :
webAddress.getJsUri() + "org.soluvas.web.bootstrap/require-2.1.5-soluvas.min.js";
add(new WebMarkupContainer("requireJs").add(new AttributeModifier(
"src", requireJsUri)));
// Carousel
add(afterHeader = new RepeatingView("afterHeader"));
navbar = new Navbar("navbar");
add(navbar);
// add(new Label("logoText",
// site.getLogoText()).setRenderBodyOnly(true));
// add(new Label("logoAlt",
// site.getLogoAlt()).setRenderBodyOnly(true));
navbar.add(new BookmarkablePageLink<Page>("homeLink",
getApplication().getHomePage()) {
{
this.setBody(new Model<String>(appManifest.getTitle()));
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
tag.getAttributes().put("title", appManifest.getTitle());
}
});
add(new Header());
final String requireConfigPath = webAddress.getApiPath()
+ "org.soluvas.web.site/requireConfig.js";
add(new WebMarkupContainer("requireConfig")
.add(new AttributeModifier("src", requireConfigPath)));
// ADDED INFO
contentAddedInfo = new WebMarkupContainer("addedInfo");
add(contentAddedInfo);
// SIDEBAR
sidebarColumn = new TransparentWebMarkupContainer("sidebarColumn");
add(sidebarColumn);
sidebarBlocks = new RepeatingView("sidebarBlocks");
sidebarColumn.add(sidebarBlocks);
// CONTENT
contentColumn = new TransparentWebMarkupContainer("contentColumn");
add(contentColumn);
feedbackPanel = new FeedbackPanel("feedback")
.setOutputMarkupId(true);
add(feedbackPanel);
// FOOTER
add(new Footer("© " + new DateTime().toString("yyyy") + " " + appManifest.getTitle()));
// JAVASCRIPT
final RepeatingView beforeFooterJs = new RepeatingView("beforeFooterJs");
add(beforeFooterJs);
log.trace("Page {} has {} footer JavaScript links", getClass()
.getName(), footerJavaScripts.size());
final List<JavaScriptLink> sortedJsLinks = linkOrdering
.immutableSortedCopy(footerJavaScripts);
final RepeatingView footerJavaScriptLinks = new RepeatingView(
"footerJavaScriptLinks");
for (JavaScriptLink js : sortedJsLinks) {
footerJavaScriptLinks.add(new WebMarkupContainer(
footerJavaScriptLinks.newChildId())
.add(new AttributeModifier("src", js.getSrc())));
}
add(footerJavaScriptLinks);
log.trace("Page {} has {} footer JavaScript sources", getClass()
.getName(), footerJavaScriptSources.size());
final List<JavaScriptSource> sortedJsSources = sourceOrdering
.immutableSortedCopy(footerJavaScriptSources);
final RepeatingView footerJavaScriptSources = new RepeatingView(
"footerJavaScriptSources");
for (JavaScriptSource js : sortedJsSources) {
footerJavaScriptSources
.add(new Label(footerJavaScriptSources.newChildId(), js
.getScript()).setEscapeModelStrings(false));
}
add(footerJavaScriptSources);
final IModel<String> pageJavaScriptSourcesModel = new LoadableDetachableModel<String>() {
@Override
protected String load() {
// cannot use ImmutableMap, because AMD dependencies can be duplicated
final Map<String, String> dependencyMap = new HashMap<>();
final AmdDependencyVisitor amdDependencyVisitor = new AmdDependencyVisitor(
dependencyMap);
amdDependencyVisitor.component(BootstrapPage.this, null);
visitChildren(amdDependencyVisitor);
log.trace("Page {} has {} AMD dependencies: {}", getClass()
.getName(), dependencyMap.size(), dependencyMap.keySet());
final ImmutableList.Builder<String> pageJsSourcesBuilder = ImmutableList
.builder();
final JsSourceVisitor jsSourceVisitor = new JsSourceVisitor(
pageJsSourcesBuilder);
jsSourceVisitor.component(BootstrapPage.this, null);
visitChildren(jsSourceVisitor);
final List<String> pageJsSources = pageJsSourcesBuilder.build();
log.trace("Page {} has {} page JavaScript sources", getClass()
.getName(), pageJsSources.size());
final String merged = Joiner.on('\n').join(pageJsSources);
JavaScriptSource js = new AmdJavaScriptSource(merged,
dependencyMap);
return js.getScript();
};
};
add(new Label("pageJavaScriptSources", pageJavaScriptSourcesModel)
.setEscapeModelStrings(false));
add(new AlexaCertifyScript("alexaCertifyScript", new Model<>(alexaCertify)));
add(new GrowlBehavior());
}
|
diff --git a/yamj3-jetty/src/main/java/com/yamj/jetty/Start.java b/yamj3-jetty/src/main/java/com/yamj/jetty/Start.java
index 4c2f092e..167b50c3 100644
--- a/yamj3-jetty/src/main/java/com/yamj/jetty/Start.java
+++ b/yamj3-jetty/src/main/java/com/yamj/jetty/Start.java
@@ -1,164 +1,164 @@
package com.yamj.jetty;
import com.yamj.common.cmdline.CmdLineException;
import com.yamj.common.cmdline.CmdLineOption;
import com.yamj.common.cmdline.CmdLineParser;
import com.yamj.common.tools.ClassTools;
import com.yamj.common.type.ExitType;
import static com.yamj.common.type.ExitType.*;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.PropertyConfigurator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Start {
private static final Logger LOG = LoggerFactory.getLogger(Start.class);
private static final String LOG_FILENAME = "yamj-jetty";
private static final String WAR_DIR = "lib/";
private static final String WAR_FILE = "yamj3-core-3.0-SNAPSHOT.war";
private static String yamjHome = ".";
private static int yamjPort = 8888;
private static int yamjShutdownPort = 3000;
private static boolean yamjStopAtShutdown = Boolean.TRUE;
public static void main(String[] args) {
// Create the log file name here, so we can change it later (because it's locked
System.setProperty("file.name", LOG_FILENAME);
PropertyConfigurator.configure("config/log4j.properties");
ClassTools.printHeader(Start.class, LOG);
CmdLineParser parser = getCmdLineParser();
ExitType status;
try {
parser.parse(args);
if (parser.userWantsHelp()) {
help(parser);
status = SUCCESS;
} else {
status = startUp(parser);
}
} catch (CmdLineException ex) {
LOG.error("Failed to parse command line options: {}", ex.getMessage());
help(parser);
status = CMDLINE_ERROR;
}
LOG.info("Exiting with status '{}', return code {}", status.toString(), status.getReturn());
System.exit(status.getReturn());
}
private static ExitType startUp(CmdLineParser parser) {
if (StringUtils.isNotBlank(parser.getParsedOptionValue("h"))) {
yamjHome = parser.getParsedOptionValue("h");
}
yamjPort = convertToInt(parser.getParsedOptionValue("p"), yamjPort);
yamjShutdownPort = convertToInt(parser.getParsedOptionValue("sp"), yamjShutdownPort);
yamjStopAtShutdown = convertToBoolean(parser.getParsedOptionValue("ss"), yamjStopAtShutdown);
String warFilename = FilenameUtils.concat(yamjHome, WAR_DIR + WAR_FILE);
File warFile = new File(warFilename);
if (warFile.exists()) {
try {
// This is a temporary fix until the yamj3.home can be read from the servlet
System.setProperty("yamj3.home", (new File(yamjHome)).getCanonicalPath());
} catch (IOException ex) {
System.setProperty("yamj3.home", yamjHome);
}
LOG.info("YAMJ Home: '{}'", yamjHome);
LOG.info("YAMJ Port: {}", yamjPort);
LOG.info("YAMJ Shudown Port: {}", yamjShutdownPort);
LOG.info("YAMJ {} stop at Shutdown", yamjStopAtShutdown ? "will" : "will not");
LOG.info("Using war file: {}", warFilename);
LOG.info("");
} else {
help(parser);
LOG.info("");
LOG.error("Initialisation error!");
LOG.error("Please ensure that the WAR file is in the '{}' directory", warFile.getParent());
return STARTUP_FAILURE;
}
LOG.info("Starting server...");
Server server = new Server(yamjPort);
server.setGracefulShutdown(yamjShutdownPort);
server.setStopAtShutdown(yamjStopAtShutdown);
try {
WebAppContext webapp = new WebAppContext();
- webapp.setContextPath("/");
+ webapp.setContextPath("/yamj3");
webapp.setWar(warFile.getCanonicalPath());
server.setHandler(webapp);
if (server.getThreadPool() instanceof QueuedThreadPool) {
((QueuedThreadPool) server.getThreadPool()).setMaxIdleTimeMs(2000);
}
server.start();
server.join();
LOG.info("Server run completed.");
LOG.info("Exiting.");
return SUCCESS;
} catch (IOException ex) {
LOG.error("Failed to start server, error: ", ex.getMessage());
return STARTUP_FAILURE;
} catch (InterruptedException ex) {
LOG.error("Server interrupted, error: ", ex.getMessage());
return STARTUP_FAILURE;
} catch (Exception ex) {
LOG.error("General server eror, message: ", ex.getMessage());
return STARTUP_FAILURE;
}
}
/**
* Print the parse descriptions
*
* @param parser
*/
private static void help(CmdLineParser parser) {
LOG.info(parser.getDescriptions());
}
/**
* Create the command line parser
*
* @return
*/
private static CmdLineParser getCmdLineParser() {
CmdLineParser parser = new CmdLineParser();
parser.addOption(new CmdLineOption("h", "home", "the home directory for jetty, default: '" + yamjHome + "'", false, true));
parser.addOption(new CmdLineOption("p", "port", "The port for the core server, default: " + yamjPort, false, true));
parser.addOption(new CmdLineOption("sp", "shutdown port", "The port to shutdown the server, default: " + yamjShutdownPort, false, true));
parser.addOption(new CmdLineOption("ss", "stop shutdown", "Shutdown the server when exiting, default: " + yamjStopAtShutdown, false, false));
return parser;
}
private static int convertToInt(String toConvert, int defaultValue) {
if (StringUtils.isNumeric(toConvert)) {
return Integer.parseInt(toConvert);
} else {
return defaultValue;
}
}
private static boolean convertToBoolean(String toConvert, boolean defaultValue) {
if (StringUtils.isNotBlank(toConvert)) {
return Boolean.parseBoolean(toConvert);
} else {
return defaultValue;
}
}
}
| true | true | private static ExitType startUp(CmdLineParser parser) {
if (StringUtils.isNotBlank(parser.getParsedOptionValue("h"))) {
yamjHome = parser.getParsedOptionValue("h");
}
yamjPort = convertToInt(parser.getParsedOptionValue("p"), yamjPort);
yamjShutdownPort = convertToInt(parser.getParsedOptionValue("sp"), yamjShutdownPort);
yamjStopAtShutdown = convertToBoolean(parser.getParsedOptionValue("ss"), yamjStopAtShutdown);
String warFilename = FilenameUtils.concat(yamjHome, WAR_DIR + WAR_FILE);
File warFile = new File(warFilename);
if (warFile.exists()) {
try {
// This is a temporary fix until the yamj3.home can be read from the servlet
System.setProperty("yamj3.home", (new File(yamjHome)).getCanonicalPath());
} catch (IOException ex) {
System.setProperty("yamj3.home", yamjHome);
}
LOG.info("YAMJ Home: '{}'", yamjHome);
LOG.info("YAMJ Port: {}", yamjPort);
LOG.info("YAMJ Shudown Port: {}", yamjShutdownPort);
LOG.info("YAMJ {} stop at Shutdown", yamjStopAtShutdown ? "will" : "will not");
LOG.info("Using war file: {}", warFilename);
LOG.info("");
} else {
help(parser);
LOG.info("");
LOG.error("Initialisation error!");
LOG.error("Please ensure that the WAR file is in the '{}' directory", warFile.getParent());
return STARTUP_FAILURE;
}
LOG.info("Starting server...");
Server server = new Server(yamjPort);
server.setGracefulShutdown(yamjShutdownPort);
server.setStopAtShutdown(yamjStopAtShutdown);
try {
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/");
webapp.setWar(warFile.getCanonicalPath());
server.setHandler(webapp);
if (server.getThreadPool() instanceof QueuedThreadPool) {
((QueuedThreadPool) server.getThreadPool()).setMaxIdleTimeMs(2000);
}
server.start();
server.join();
LOG.info("Server run completed.");
LOG.info("Exiting.");
return SUCCESS;
} catch (IOException ex) {
LOG.error("Failed to start server, error: ", ex.getMessage());
return STARTUP_FAILURE;
} catch (InterruptedException ex) {
LOG.error("Server interrupted, error: ", ex.getMessage());
return STARTUP_FAILURE;
} catch (Exception ex) {
LOG.error("General server eror, message: ", ex.getMessage());
return STARTUP_FAILURE;
}
}
| private static ExitType startUp(CmdLineParser parser) {
if (StringUtils.isNotBlank(parser.getParsedOptionValue("h"))) {
yamjHome = parser.getParsedOptionValue("h");
}
yamjPort = convertToInt(parser.getParsedOptionValue("p"), yamjPort);
yamjShutdownPort = convertToInt(parser.getParsedOptionValue("sp"), yamjShutdownPort);
yamjStopAtShutdown = convertToBoolean(parser.getParsedOptionValue("ss"), yamjStopAtShutdown);
String warFilename = FilenameUtils.concat(yamjHome, WAR_DIR + WAR_FILE);
File warFile = new File(warFilename);
if (warFile.exists()) {
try {
// This is a temporary fix until the yamj3.home can be read from the servlet
System.setProperty("yamj3.home", (new File(yamjHome)).getCanonicalPath());
} catch (IOException ex) {
System.setProperty("yamj3.home", yamjHome);
}
LOG.info("YAMJ Home: '{}'", yamjHome);
LOG.info("YAMJ Port: {}", yamjPort);
LOG.info("YAMJ Shudown Port: {}", yamjShutdownPort);
LOG.info("YAMJ {} stop at Shutdown", yamjStopAtShutdown ? "will" : "will not");
LOG.info("Using war file: {}", warFilename);
LOG.info("");
} else {
help(parser);
LOG.info("");
LOG.error("Initialisation error!");
LOG.error("Please ensure that the WAR file is in the '{}' directory", warFile.getParent());
return STARTUP_FAILURE;
}
LOG.info("Starting server...");
Server server = new Server(yamjPort);
server.setGracefulShutdown(yamjShutdownPort);
server.setStopAtShutdown(yamjStopAtShutdown);
try {
WebAppContext webapp = new WebAppContext();
webapp.setContextPath("/yamj3");
webapp.setWar(warFile.getCanonicalPath());
server.setHandler(webapp);
if (server.getThreadPool() instanceof QueuedThreadPool) {
((QueuedThreadPool) server.getThreadPool()).setMaxIdleTimeMs(2000);
}
server.start();
server.join();
LOG.info("Server run completed.");
LOG.info("Exiting.");
return SUCCESS;
} catch (IOException ex) {
LOG.error("Failed to start server, error: ", ex.getMessage());
return STARTUP_FAILURE;
} catch (InterruptedException ex) {
LOG.error("Server interrupted, error: ", ex.getMessage());
return STARTUP_FAILURE;
} catch (Exception ex) {
LOG.error("General server eror, message: ", ex.getMessage());
return STARTUP_FAILURE;
}
}
|
diff --git a/cat-consumer-advanced/src/main/java/com/dianping/cat/consumer/cross/CrossAnalyzer.java b/cat-consumer-advanced/src/main/java/com/dianping/cat/consumer/cross/CrossAnalyzer.java
index 585390a9b..323b2503f 100644
--- a/cat-consumer-advanced/src/main/java/com/dianping/cat/consumer/cross/CrossAnalyzer.java
+++ b/cat-consumer-advanced/src/main/java/com/dianping/cat/consumer/cross/CrossAnalyzer.java
@@ -1,278 +1,278 @@
package com.dianping.cat.consumer.cross;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.unidal.lookup.annotation.Inject;
import com.dianping.cat.Cat;
import com.dianping.cat.ServerConfigManager;
import com.dianping.cat.analysis.AbstractMessageAnalyzer;
import com.dianping.cat.consumer.cross.model.entity.CrossReport;
import com.dianping.cat.consumer.cross.model.entity.Local;
import com.dianping.cat.consumer.cross.model.entity.Name;
import com.dianping.cat.consumer.cross.model.entity.Remote;
import com.dianping.cat.consumer.cross.model.entity.Type;
import com.dianping.cat.message.Event;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.internal.MessageId;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.service.DefaultReportManager.StoragePolicy;
import com.dianping.cat.service.ReportManager;
public class CrossAnalyzer extends AbstractMessageAnalyzer<CrossReport> implements LogEnabled {
public static final String ID = "cross";
@Inject(ID)
private ReportManager<CrossReport> m_reportManager;
@Inject
private ServerConfigManager m_serverConfigManager;
private static final String UNKNOWN = "UnknownIp";
private Map<String, String> m_host = new HashMap<String, String>();
@Override
public void doCheckpoint(boolean atEnd) {
if (atEnd && !isLocalMode()) {
m_reportManager.storeHourlyReports(getStartTime(), StoragePolicy.FILE_AND_DB);
} else {
m_reportManager.storeHourlyReports(getStartTime(), StoragePolicy.FILE);
}
}
@Override
public void enableLogging(Logger logger) {
m_logger = logger;
}
@Override
public CrossReport getReport(String domain) {
CrossReport report = m_reportManager.getHourlyReport(getStartTime(), domain, false);
report.getDomainNames().addAll(m_reportManager.getDomains(getStartTime()));
return report;
}
@Override
protected void loadReports() {
m_reportManager.loadHourlyReports(getStartTime(), StoragePolicy.FILE);
}
public CrossInfo parseCorssTransaction(Transaction t, MessageTree tree) {
if (m_serverConfigManager.discardTransaction(t)) {
return null;
} else {
String type = t.getType();
if (m_serverConfigManager.isClientCall(type)) {
return parsePigeonClientTransaction(t, tree);
} else if (m_serverConfigManager.isServerService(type)) {
return parsePigeonServerTransaction(t, tree);
}
return null;
}
}
private CrossInfo parsePigeonClientTransaction(Transaction t, MessageTree tree) {
CrossInfo crossInfo = new CrossInfo();
String localIp = tree.getIpAddress();
List<Message> messages = t.getChildren();
for (Message message : messages) {
if (message instanceof Event) {
if (message.getType().equals("PigeonCall.server")) {
crossInfo.setRemoteAddress(message.getName());
break;
}
}
}
crossInfo.setLocalAddress(localIp);
crossInfo.setRemoteRole("Pigeon.Server");
crossInfo.setDetailType("PigeonCall");
return crossInfo;
}
public String formatIp(String str) {
String result = m_host.get(str);
if (result == null) {
if (isIPAdress(str)) {
result = str;
} else {
try {
InetAddress address = InetAddress.getByName(str);
result = address.getHostAddress();
m_logger.info(String.format("hostname %s to %s", str, result));
} catch (UnknownHostException e) {
Cat.logError(e);
result = "";
}
}
m_host.put(str, result);
}
return result;
}
public boolean isIPAdress(String str) {
Pattern pattern = Pattern
.compile("^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$");
return pattern.matcher(str).matches();
}
private CrossInfo parsePigeonServerTransaction(Transaction t, MessageTree tree) {
CrossInfo crossInfo = new CrossInfo();
String localIp = tree.getIpAddress();
List<Message> messages = t.getChildren();
for (Message message : messages) {
if (message instanceof Event) {
if (message.getType().equals("PigeonService.client")) {
String name = message.getName();
int index = name.indexOf(":");
if (index > 0) {
name = name.substring(0, index);
}
String formatIp = formatIp(name);
if (formatIp != null && formatIp.length() > 0) {
- crossInfo.setRemoteAddress(name);
+ crossInfo.setRemoteAddress(formatIp);
}
break;
}
}
}
if (crossInfo.getRemoteAddress().equals(UNKNOWN)) {
MessageId id = MessageId.parse(tree.getMessageId());
String remoteIp = id.getIpAddress();
crossInfo.setRemoteAddress(remoteIp);
}
crossInfo.setLocalAddress(localIp);
crossInfo.setRemoteRole("Pigeon.Client");
crossInfo.setDetailType("PigeonService");
return crossInfo;
}
@Override
public void process(MessageTree tree) {
String domain = tree.getDomain();
CrossReport report = m_reportManager.getHourlyReport(getStartTime(), domain, true);
Message message = tree.getMessage();
report.addIp(tree.getIpAddress());
if (message instanceof Transaction) {
processTransaction(report, tree, (Transaction) message);
}
}
private void processTransaction(CrossReport report, MessageTree tree, Transaction t) {
CrossInfo info = parseCorssTransaction(t, tree);
if (info != null) {
updateCrossReport(report, t, info);
}
List<Message> children = t.getChildren();
for (Message child : children) {
if (child instanceof Transaction) {
processTransaction(report, tree, (Transaction) child);
}
}
}
private void updateCrossReport(CrossReport report, Transaction t, CrossInfo info) {
String localIp = info.getLocalAddress();
String remoteIp = info.getRemoteAddress();
String role = info.getRemoteRole();
String transactionName = t.getName();
Local client = report.findOrCreateLocal(localIp);
Remote server = client.findOrCreateRemote(remoteIp);
server.setRole(role);
Type type = server.getType();
if (type == null) {
type = new Type();
type.setId(info.getDetailType());
server.setType(type);
}
Name name = type.findOrCreateName(transactionName);
type.incTotalCount();
name.incTotalCount();
if (!t.isSuccess()) {
type.incFailCount();
name.incFailCount();
}
double duration = t.getDurationInMicros() / 1000d;
name.setSum(name.getSum() + duration);
type.setSum(type.getSum() + duration);
}
public static class CrossInfo {
private String m_remoteRole = UNKNOWN;
private String m_LocalAddress = UNKNOWN;
private String m_RemoteAddress = UNKNOWN;
private String m_detailType = UNKNOWN;
public String getDetailType() {
return m_detailType;
}
public String getLocalAddress() {
return m_LocalAddress;
}
public String getRemoteAddress() {
return m_RemoteAddress;
}
public String getRemoteRole() {
return m_remoteRole;
}
public void setDetailType(String detailType) {
m_detailType = detailType;
}
public void setLocalAddress(String localAddress) {
m_LocalAddress = localAddress;
}
public void setRemoteAddress(String remoteAddress) {
m_RemoteAddress = remoteAddress;
}
public void setRemoteRole(String remoteRole) {
m_remoteRole = remoteRole;
}
}
public void setServerConfigManager(ServerConfigManager serverConfigManager) {
m_serverConfigManager = serverConfigManager;
}
}
| true | true | private CrossInfo parsePigeonServerTransaction(Transaction t, MessageTree tree) {
CrossInfo crossInfo = new CrossInfo();
String localIp = tree.getIpAddress();
List<Message> messages = t.getChildren();
for (Message message : messages) {
if (message instanceof Event) {
if (message.getType().equals("PigeonService.client")) {
String name = message.getName();
int index = name.indexOf(":");
if (index > 0) {
name = name.substring(0, index);
}
String formatIp = formatIp(name);
if (formatIp != null && formatIp.length() > 0) {
crossInfo.setRemoteAddress(name);
}
break;
}
}
}
if (crossInfo.getRemoteAddress().equals(UNKNOWN)) {
MessageId id = MessageId.parse(tree.getMessageId());
String remoteIp = id.getIpAddress();
crossInfo.setRemoteAddress(remoteIp);
}
crossInfo.setLocalAddress(localIp);
crossInfo.setRemoteRole("Pigeon.Client");
crossInfo.setDetailType("PigeonService");
return crossInfo;
}
| private CrossInfo parsePigeonServerTransaction(Transaction t, MessageTree tree) {
CrossInfo crossInfo = new CrossInfo();
String localIp = tree.getIpAddress();
List<Message> messages = t.getChildren();
for (Message message : messages) {
if (message instanceof Event) {
if (message.getType().equals("PigeonService.client")) {
String name = message.getName();
int index = name.indexOf(":");
if (index > 0) {
name = name.substring(0, index);
}
String formatIp = formatIp(name);
if (formatIp != null && formatIp.length() > 0) {
crossInfo.setRemoteAddress(formatIp);
}
break;
}
}
}
if (crossInfo.getRemoteAddress().equals(UNKNOWN)) {
MessageId id = MessageId.parse(tree.getMessageId());
String remoteIp = id.getIpAddress();
crossInfo.setRemoteAddress(remoteIp);
}
crossInfo.setLocalAddress(localIp);
crossInfo.setRemoteRole("Pigeon.Client");
crossInfo.setDetailType("PigeonService");
return crossInfo;
}
|
diff --git a/TitoCC/src/titocc/compiler/elements/BinaryExpression.java b/TitoCC/src/titocc/compiler/elements/BinaryExpression.java
index 79cb5a2..2cc9764 100644
--- a/TitoCC/src/titocc/compiler/elements/BinaryExpression.java
+++ b/TitoCC/src/titocc/compiler/elements/BinaryExpression.java
@@ -1,230 +1,230 @@
package titocc.compiler.elements;
import java.io.IOException;
import java.util.Arrays;
import java.util.Stack;
import titocc.compiler.Assembler;
import titocc.compiler.InternalCompilerException;
import titocc.compiler.Register;
import titocc.compiler.Scope;
import titocc.tokenizer.SyntaxException;
import titocc.tokenizer.TokenStream;
public class BinaryExpression extends Expression
{
static final String[][] binaryOperators = {
{"||"},
{"&&"},
{"|"},
{"^"},
{"&"},
{"=="},
{"!="},
{"<", "<=", ">", ">="},
{"<<", ">>"},
{"+", "-"},
{"*", "/", "%"}
};
private String operator;
private Expression left, right;
public BinaryExpression(String operator, Expression left, Expression right,
int line, int column)
{
super(line, column);
this.operator = operator;
this.left = left;
this.right = right;
}
public String getOperator()
{
return operator;
}
public Expression getLeft()
{
return left;
}
public Expression getRight()
{
return right;
}
@Override
public void compile(Assembler asm, Scope scope, Stack<Register> registers)
throws IOException, SyntaxException
{
Register pushedRegister = pushRegister(asm, registers);
// Evaluate left expression and store it in the first available register.
left.compile(asm, scope, registers);
Register leftRegister = registers.pop();
// Evaluate right expression and store it in the next register.
right.compile(asm, scope, registers);
// Evaluate the operation and store the result in the left register.
compileOperator(asm, scope, leftRegister, registers.peek());
registers.push(leftRegister);
// Pop registers.
popRegister(asm, registers, pushedRegister);
}
private void compileOperator(Assembler asm, Scope scope, Register left, Register right)
throws IOException, SyntaxException
{
String jumpLabel, jumpLabel2;
switch (operator) {
//TODO short circuit && and ||
case "||":
jumpLabel = scope.makeGloballyUniqueName("lbl");
jumpLabel2 = scope.makeGloballyUniqueName("lbl");
asm.emit("", "jnzer", left.toString(), jumpLabel);
asm.emit("", "jnzer", right.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit("", "jump", left.toString(), jumpLabel2);
asm.emit(jumpLabel, "load", left.toString(), "=1");
asm.emit(jumpLabel2, "nop", "");
break;
case "&&":
jumpLabel = scope.makeGloballyUniqueName("lbl");
jumpLabel2 = scope.makeGloballyUniqueName("lbl");
asm.emit("", "jzer", left.toString(), jumpLabel);
asm.emit("", "jzer", right.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jump", left.toString(), jumpLabel2);
asm.emit(jumpLabel, "load", left.toString(), "=0");
asm.emit(jumpLabel2, "nop", "");
break;
case "|":
asm.emit("or", operator, operator);
break;
case "^":
asm.emit("xor", operator, operator);
break;
case "&":
asm.emit("and", operator, operator);
break;
case "==":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
- asm.emit("", "jeq", left.toString(), jumpLabel);
+ asm.emit("", "jequ", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "!=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
- asm.emit("", "jneq", left.toString(), jumpLabel);
+ asm.emit("", "jnequ", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jles", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jngre", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case ">":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jgre", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case ">=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jnles", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<<":
asm.emit("", "shl", left.toString(), right.toString());
break;
case ">>":
asm.emit("", "shr", left.toString(), right.toString());
break;
case "+":
asm.emit("", "add", left.toString(), right.toString());
break;
case "-":
asm.emit("", "sub", left.toString(), right.toString());
break;
case "*":
asm.emit("", "mul", left.toString(), right.toString());
break;
case "/":
asm.emit("", "div", left.toString(), right.toString());
break;
case "%":
asm.emit("", "mod", left.toString(), right.toString());
break;
default:
throw new InternalCompilerException("Invalid operator in BinaryExpression.");
}
}
@Override
public Integer getCompileTimeValue()
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String toString()
{
return "(BIN_EXPR " + operator + " " + left + " " + right + ")";
}
public static Expression parse(TokenStream tokens)
{
return parseImpl(tokens, 0);
}
private static Expression parseImpl(TokenStream tokens, int priority)
{
if (priority == binaryOperators.length)
return PrefixExpression.parse(tokens);
int line = tokens.getLine(), column = tokens.getColumn();
tokens.pushMark();
Expression expr = parseImpl(tokens, priority + 1);
if (expr != null)
while (true) {
tokens.pushMark();
Expression right = null;
String op = tokens.read().toString();
if (Arrays.asList(binaryOperators[priority]).contains(op))
right = parseImpl(tokens, priority + 1);
tokens.popMark(right == null);
if (right != null)
expr = new BinaryExpression(op, expr, right, line, column);
else
break;
}
tokens.popMark(expr == null);
return expr;
}
}
| false | true | private void compileOperator(Assembler asm, Scope scope, Register left, Register right)
throws IOException, SyntaxException
{
String jumpLabel, jumpLabel2;
switch (operator) {
//TODO short circuit && and ||
case "||":
jumpLabel = scope.makeGloballyUniqueName("lbl");
jumpLabel2 = scope.makeGloballyUniqueName("lbl");
asm.emit("", "jnzer", left.toString(), jumpLabel);
asm.emit("", "jnzer", right.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit("", "jump", left.toString(), jumpLabel2);
asm.emit(jumpLabel, "load", left.toString(), "=1");
asm.emit(jumpLabel2, "nop", "");
break;
case "&&":
jumpLabel = scope.makeGloballyUniqueName("lbl");
jumpLabel2 = scope.makeGloballyUniqueName("lbl");
asm.emit("", "jzer", left.toString(), jumpLabel);
asm.emit("", "jzer", right.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jump", left.toString(), jumpLabel2);
asm.emit(jumpLabel, "load", left.toString(), "=0");
asm.emit(jumpLabel2, "nop", "");
break;
case "|":
asm.emit("or", operator, operator);
break;
case "^":
asm.emit("xor", operator, operator);
break;
case "&":
asm.emit("and", operator, operator);
break;
case "==":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jeq", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "!=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jneq", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jles", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jngre", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case ">":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jgre", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case ">=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jnles", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<<":
asm.emit("", "shl", left.toString(), right.toString());
break;
case ">>":
asm.emit("", "shr", left.toString(), right.toString());
break;
case "+":
asm.emit("", "add", left.toString(), right.toString());
break;
case "-":
asm.emit("", "sub", left.toString(), right.toString());
break;
case "*":
asm.emit("", "mul", left.toString(), right.toString());
break;
case "/":
asm.emit("", "div", left.toString(), right.toString());
break;
case "%":
asm.emit("", "mod", left.toString(), right.toString());
break;
default:
throw new InternalCompilerException("Invalid operator in BinaryExpression.");
}
}
| private void compileOperator(Assembler asm, Scope scope, Register left, Register right)
throws IOException, SyntaxException
{
String jumpLabel, jumpLabel2;
switch (operator) {
//TODO short circuit && and ||
case "||":
jumpLabel = scope.makeGloballyUniqueName("lbl");
jumpLabel2 = scope.makeGloballyUniqueName("lbl");
asm.emit("", "jnzer", left.toString(), jumpLabel);
asm.emit("", "jnzer", right.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit("", "jump", left.toString(), jumpLabel2);
asm.emit(jumpLabel, "load", left.toString(), "=1");
asm.emit(jumpLabel2, "nop", "");
break;
case "&&":
jumpLabel = scope.makeGloballyUniqueName("lbl");
jumpLabel2 = scope.makeGloballyUniqueName("lbl");
asm.emit("", "jzer", left.toString(), jumpLabel);
asm.emit("", "jzer", right.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jump", left.toString(), jumpLabel2);
asm.emit(jumpLabel, "load", left.toString(), "=0");
asm.emit(jumpLabel2, "nop", "");
break;
case "|":
asm.emit("or", operator, operator);
break;
case "^":
asm.emit("xor", operator, operator);
break;
case "&":
asm.emit("and", operator, operator);
break;
case "==":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jequ", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "!=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jnequ", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jles", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jngre", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case ">":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jgre", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case ">=":
jumpLabel = scope.makeGloballyUniqueName("lbl");
asm.emit("", "comp", left.toString(), right.toString());
asm.emit("", "load", left.toString(), "=1");
asm.emit("", "jnles", left.toString(), jumpLabel);
asm.emit("", "load", left.toString(), "=0");
asm.emit(jumpLabel, "nop", "");
break;
case "<<":
asm.emit("", "shl", left.toString(), right.toString());
break;
case ">>":
asm.emit("", "shr", left.toString(), right.toString());
break;
case "+":
asm.emit("", "add", left.toString(), right.toString());
break;
case "-":
asm.emit("", "sub", left.toString(), right.toString());
break;
case "*":
asm.emit("", "mul", left.toString(), right.toString());
break;
case "/":
asm.emit("", "div", left.toString(), right.toString());
break;
case "%":
asm.emit("", "mod", left.toString(), right.toString());
break;
default:
throw new InternalCompilerException("Invalid operator in BinaryExpression.");
}
}
|
diff --git a/src/main/java/org/clojure/maven/ClojureEvalMojo.java b/src/main/java/org/clojure/maven/ClojureEvalMojo.java
index fc2dc93..6a6cb37 100644
--- a/src/main/java/org/clojure/maven/ClojureEvalMojo.java
+++ b/src/main/java/org/clojure/maven/ClojureEvalMojo.java
@@ -1,63 +1,63 @@
package org.clojure.maven;
import java.io.File;
import java.net.URLClassLoader;
import java.util.Arrays;
import org.apache.maven.plugin.MojoExecutionException;
/**
* Evaluate Clojure source code
*
* @goal eval
*/
public class ClojureEvalMojo extends AbstractClojureMojo {
/**
* Clojure code to be evaluated
* @parameter expression="${clojure.eval}"
* @required
*/
private String eval;
/**
* Classpath scope: one of 'compile', 'test', or
* 'runtime'. Defaults to 'test'.
* @parameter expression="${clojure.scope}" default-value="test"
* @required
*/
private String scope;
public void execute() throws MojoExecutionException {
Classpath classpath;
int classpathScope = getClasspathScope();
try {
classpath = new Classpath(project, classpathScope, null);
} catch (Exception e) {
throw new MojoExecutionException("Classpath initialization failed", e);
}
IsolatedThreadRunner runner =
new IsolatedThreadRunner(getLog(), classpath,
new ClojureEvalTask(getLog(), eval));
runner.run();
Throwable t = runner.getUncaught();
if (t != null) {
- throw new MojoExecutionException("Clojure compilation failed", t);
+ throw new MojoExecutionException("Clojure evaluation failed", t);
}
}
private int getClasspathScope() throws MojoExecutionException {
if ("compile".equals(scope)) {
return Classpath.COMPILE_CLASSPATH | Classpath.COMPILE_SOURCES;
} else if ("test".equals(scope)) {
return Classpath.COMPILE_CLASSPATH | Classpath.COMPILE_SOURCES |
Classpath.TEST_CLASSPATH | Classpath.TEST_SOURCES |
Classpath.RUNTIME_CLASSPATH;
} else if ("runtime".equals(scope)) {
return Classpath.COMPILE_CLASSPATH | Classpath.COMPILE_SOURCES |
Classpath.RUNTIME_CLASSPATH;
} else {
throw new MojoExecutionException("Invalid classpath scope: " + scope);
}
}
}
| true | true | public void execute() throws MojoExecutionException {
Classpath classpath;
int classpathScope = getClasspathScope();
try {
classpath = new Classpath(project, classpathScope, null);
} catch (Exception e) {
throw new MojoExecutionException("Classpath initialization failed", e);
}
IsolatedThreadRunner runner =
new IsolatedThreadRunner(getLog(), classpath,
new ClojureEvalTask(getLog(), eval));
runner.run();
Throwable t = runner.getUncaught();
if (t != null) {
throw new MojoExecutionException("Clojure compilation failed", t);
}
}
| public void execute() throws MojoExecutionException {
Classpath classpath;
int classpathScope = getClasspathScope();
try {
classpath = new Classpath(project, classpathScope, null);
} catch (Exception e) {
throw new MojoExecutionException("Classpath initialization failed", e);
}
IsolatedThreadRunner runner =
new IsolatedThreadRunner(getLog(), classpath,
new ClojureEvalTask(getLog(), eval));
runner.run();
Throwable t = runner.getUncaught();
if (t != null) {
throw new MojoExecutionException("Clojure evaluation failed", t);
}
}
|
diff --git a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/api/JavaSettings.java b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/api/JavaSettings.java
index 9b08d8b96..8c463ea1c 100644
--- a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/api/JavaSettings.java
+++ b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/api/JavaSettings.java
@@ -1,61 +1,61 @@
/*
* SonarQube Java
* Copyright (C) 2012 SonarSource
* [email protected]
*
* This program 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 3 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.java.api;
import org.sonar.api.BatchExtension;
import org.sonar.api.ServerExtension;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.Settings;
import org.sonar.api.resources.Qualifiers;
public class JavaSettings implements BatchExtension, ServerExtension {
private static final String PROPERTY_COVERAGE_PLUGIN = "sonar.java.coveragePlugin";
private final Settings settings;
public JavaSettings(Settings settings) {
this.settings = settings;
}
/**
* @since 1.1
*/
public String getEnabledCoveragePlugin() {
// backward-compatibility with the property that has been deprecated in sonar 3.4.
String[] keys = settings.getStringArray("sonar.core.codeCoveragePlugin");
if (keys.length > 0) {
return keys[0];
}
return settings.getString(PROPERTY_COVERAGE_PLUGIN);
}
public static PropertyDefinition property() {
- return PropertyDefinition.builder("sonar.java.coveragePlugin")
+ return PropertyDefinition.builder(PROPERTY_COVERAGE_PLUGIN)
.defaultValue("jacoco")
.category("java")
.subCategory("General")
.name("Code coverage plugin")
.description("Key of the code coverage plugin to use for unit tests.")
.onQualifiers(Qualifiers.PROJECT)
.build();
}
}
| true | true | public static PropertyDefinition property() {
return PropertyDefinition.builder("sonar.java.coveragePlugin")
.defaultValue("jacoco")
.category("java")
.subCategory("General")
.name("Code coverage plugin")
.description("Key of the code coverage plugin to use for unit tests.")
.onQualifiers(Qualifiers.PROJECT)
.build();
}
| public static PropertyDefinition property() {
return PropertyDefinition.builder(PROPERTY_COVERAGE_PLUGIN)
.defaultValue("jacoco")
.category("java")
.subCategory("General")
.name("Code coverage plugin")
.description("Key of the code coverage plugin to use for unit tests.")
.onQualifiers(Qualifiers.PROJECT)
.build();
}
|
diff --git a/org.spoofax.modelware.emf/src/org/spoofax/modelware/emf/utils/Subobject2Subterm.java b/org.spoofax.modelware.emf/src/org/spoofax/modelware/emf/utils/Subobject2Subterm.java
index c729cf2..0f96438 100644
--- a/org.spoofax.modelware.emf/src/org/spoofax/modelware/emf/utils/Subobject2Subterm.java
+++ b/org.spoofax.modelware.emf/src/org/spoofax/modelware/emf/utils/Subobject2Subterm.java
@@ -1,58 +1,61 @@
package org.spoofax.modelware.emf.utils;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.spoofax.interpreter.terms.IStrategoList;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.strategoxt.imp.runtime.stratego.StrategoTermPath;
import org.strategoxt.lang.Context;
/**
* Given an EObject contained by some root object (i.e. "the model"), find the corresponding StrategoTerm contained by some root term (i.e.
* "the AST"). Calculation is done based on the containment hierarchy.
*
* @author Oskar van Rest
*/
public class Subobject2Subterm {
private static Context context = new Context();
public static IStrategoTerm object2subterm(EObject eObject, EObject root, IStrategoTerm AST) {
List<Integer> path = object2path(eObject, root, new LinkedList<Integer>());
if (path != null) {
IStrategoList strategoTermPath = StrategoTermPath.toStrategoPath(path);
return StrategoTermPath.getTermAtPath(context, AST, strategoTermPath);
}
return null;
}
public static List<Integer> object2path(EObject eObject, EObject root, List<Integer> result) {
if (eObject == root) {
+ result.add(0, 0); // M(_)
return result;
}
else if (eObject.eContainer() == null) {
return null;
}
else {
int position = Utils.feature2index(eObject.eContainer().eClass(), eObject.eContainingFeature());
if (eObject.eContainingFeature().getLowerBound() == 0 && eObject.eContainingFeature().getUpperBound() == 1) {
- result.add(0, 0);
+ result.add(0, 0); // some
}
if (eObject.eContainingFeature().getUpperBound() == -1) {
EList<?> list = (EList<?>) eObject.eContainer().eGet(eObject.eContainingFeature());
int positionInList = list.indexOf(eObject);
result.add(0, positionInList);
}
+ result.add(0, 0);
result.add(0, position);
+ result.add(0, 2);
return object2path(eObject.eContainer(), root, result);
}
}
}
| false | true | public static List<Integer> object2path(EObject eObject, EObject root, List<Integer> result) {
if (eObject == root) {
return result;
}
else if (eObject.eContainer() == null) {
return null;
}
else {
int position = Utils.feature2index(eObject.eContainer().eClass(), eObject.eContainingFeature());
if (eObject.eContainingFeature().getLowerBound() == 0 && eObject.eContainingFeature().getUpperBound() == 1) {
result.add(0, 0);
}
if (eObject.eContainingFeature().getUpperBound() == -1) {
EList<?> list = (EList<?>) eObject.eContainer().eGet(eObject.eContainingFeature());
int positionInList = list.indexOf(eObject);
result.add(0, positionInList);
}
result.add(0, position);
return object2path(eObject.eContainer(), root, result);
}
}
| public static List<Integer> object2path(EObject eObject, EObject root, List<Integer> result) {
if (eObject == root) {
result.add(0, 0); // M(_)
return result;
}
else if (eObject.eContainer() == null) {
return null;
}
else {
int position = Utils.feature2index(eObject.eContainer().eClass(), eObject.eContainingFeature());
if (eObject.eContainingFeature().getLowerBound() == 0 && eObject.eContainingFeature().getUpperBound() == 1) {
result.add(0, 0); // some
}
if (eObject.eContainingFeature().getUpperBound() == -1) {
EList<?> list = (EList<?>) eObject.eContainer().eGet(eObject.eContainingFeature());
int positionInList = list.indexOf(eObject);
result.add(0, positionInList);
}
result.add(0, 0);
result.add(0, position);
result.add(0, 2);
return object2path(eObject.eContainer(), root, result);
}
}
|
diff --git a/src/di/kdd/smartmonitor/protocol/PeerNode.java b/src/di/kdd/smartmonitor/protocol/PeerNode.java
index 9a51841..a4f08c0 100644
--- a/src/di/kdd/smartmonitor/protocol/PeerNode.java
+++ b/src/di/kdd/smartmonitor/protocol/PeerNode.java
@@ -1,161 +1,161 @@
package di.kdd.smartmonitor.protocol;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.util.Log;
import di.kdd.smartmonitor.middleware.TimeSynchronization;
import di.kdd.smartmonitor.protocol.ISmartMonitor.Tag;
public final class PeerNode extends DistributedSystemNode implements Runnable {
private Socket joinSocket;
private ServerSocket commandsServerSocket;
private TimeSynchronization timeSync = new TimeSynchronization();
private static final String TAG = "peer";
/***
* Sends a JOIN message to the Master node and if it gets accepted,
* starts a thread that accepts commands from the Master
* @param joinSocket The connected to the Master node socket
*/
public PeerNode(Socket joinSocket) {
this.joinSocket = joinSocket;
/* Start command-serving thread */
new Thread(this).start();
}
/***
* Accepts a socket connection on the COMMAND_PORT and waits for commands from the Master
*/
@Override
public void run() {
Message message;
Socket masterSocket;
android.os.Debug.waitForDebugger();
try {
commandsServerSocket = new ServerSocket(ISmartMonitor.COMMAND_PORT);
commandsServerSocket.setReuseAddress(true);
}
catch(IOException e) {
- Log.e(TAG, "Failed to accept command socket");
+ Log.e(TAG, "Failed to bind command server socket");
e.printStackTrace();
return;
}
Log.i(TAG, "Joining the system");
try {
/* The Master node was found, send the JOIN message */
message = new Message(Tag.JOIN);
send(joinSocket, message);
/* Receive PEER_DATA */
message = receive(joinSocket, Tag.PEER_DATA);
/* Receive TIME_SYNC */
message = receive(joinSocket, Tag.SYNC);
}
catch(Exception e) {
Log.e(TAG, "Failed to join the system: " + e.getMessage());
return;
}
finally {
try {
joinSocket.close();
}
catch(Exception e) {
}
}
Log.i(TAG, "Starting serving commands");
try {
masterSocket = commandsServerSocket.accept();
}
catch(IOException e) {
Log.e(TAG, "Failed to accept socket for command serving");
return;
}
Log.i(TAG, "Accepted command socket from " + masterSocket.getInetAddress().toString());
/* Listen on MasterSocket for incoming commands from the Master */
Log.i(TAG, "Listening for commands from the Master node");
while(!this.isInterrupted()) {
try {
message = receive(masterSocket);
switch(message.getTag()) {
case PEER_DATA:
Log.i(TAG, "Received PEER_DATA command");
peerData.addPeersFromMessage(message);
break;
case SYNC:
Log.i(TAG, "Received SYNC command");
timeSync.timeReference(Long.parseLong(message.getPayload()));
break;
case NEW_PEER:
Log.i(TAG, "Received NEW_PEER command");
peerData.addPeerIP(message.getPayload());
break;
case START_SAMPLING:
Log.i(TAG, "Received START_SAMPLING command");
break;
case STOP_SAMPLING:
Log.i(TAG, "Received STOP_SAMPLING command");
break;
case SEND_PEAKS:
Log.i(TAG, "Received SEND_PEAKS command");
break;
default:
Log.e(TAG, "Not implemented Tag handling: " + message.getTag().toString());
break;
}
}
catch(IOException e) {
Log.e(TAG, "Error while listening to commands from Master node");
e.printStackTrace();
}
catch(ClassNotFoundException e) {
Log.e(TAG, "Error while receiving data");
e.printStackTrace();
}
}
}
@Override
public void disconnect() {
this.interrupt();
try {
commandsServerSocket.close();
}
catch(IOException e) {
}
}
@Override
public boolean isMaster() {
return false;
}
}
| true | true | public void run() {
Message message;
Socket masterSocket;
android.os.Debug.waitForDebugger();
try {
commandsServerSocket = new ServerSocket(ISmartMonitor.COMMAND_PORT);
commandsServerSocket.setReuseAddress(true);
}
catch(IOException e) {
Log.e(TAG, "Failed to accept command socket");
e.printStackTrace();
return;
}
Log.i(TAG, "Joining the system");
try {
/* The Master node was found, send the JOIN message */
message = new Message(Tag.JOIN);
send(joinSocket, message);
/* Receive PEER_DATA */
message = receive(joinSocket, Tag.PEER_DATA);
/* Receive TIME_SYNC */
message = receive(joinSocket, Tag.SYNC);
}
catch(Exception e) {
Log.e(TAG, "Failed to join the system: " + e.getMessage());
return;
}
finally {
try {
joinSocket.close();
}
catch(Exception e) {
}
}
Log.i(TAG, "Starting serving commands");
try {
masterSocket = commandsServerSocket.accept();
}
catch(IOException e) {
Log.e(TAG, "Failed to accept socket for command serving");
return;
}
Log.i(TAG, "Accepted command socket from " + masterSocket.getInetAddress().toString());
/* Listen on MasterSocket for incoming commands from the Master */
Log.i(TAG, "Listening for commands from the Master node");
while(!this.isInterrupted()) {
try {
message = receive(masterSocket);
switch(message.getTag()) {
case PEER_DATA:
Log.i(TAG, "Received PEER_DATA command");
peerData.addPeersFromMessage(message);
break;
case SYNC:
Log.i(TAG, "Received SYNC command");
timeSync.timeReference(Long.parseLong(message.getPayload()));
break;
case NEW_PEER:
Log.i(TAG, "Received NEW_PEER command");
peerData.addPeerIP(message.getPayload());
break;
case START_SAMPLING:
Log.i(TAG, "Received START_SAMPLING command");
break;
case STOP_SAMPLING:
Log.i(TAG, "Received STOP_SAMPLING command");
break;
case SEND_PEAKS:
Log.i(TAG, "Received SEND_PEAKS command");
break;
default:
Log.e(TAG, "Not implemented Tag handling: " + message.getTag().toString());
break;
}
}
catch(IOException e) {
Log.e(TAG, "Error while listening to commands from Master node");
e.printStackTrace();
}
catch(ClassNotFoundException e) {
Log.e(TAG, "Error while receiving data");
e.printStackTrace();
}
}
}
| public void run() {
Message message;
Socket masterSocket;
android.os.Debug.waitForDebugger();
try {
commandsServerSocket = new ServerSocket(ISmartMonitor.COMMAND_PORT);
commandsServerSocket.setReuseAddress(true);
}
catch(IOException e) {
Log.e(TAG, "Failed to bind command server socket");
e.printStackTrace();
return;
}
Log.i(TAG, "Joining the system");
try {
/* The Master node was found, send the JOIN message */
message = new Message(Tag.JOIN);
send(joinSocket, message);
/* Receive PEER_DATA */
message = receive(joinSocket, Tag.PEER_DATA);
/* Receive TIME_SYNC */
message = receive(joinSocket, Tag.SYNC);
}
catch(Exception e) {
Log.e(TAG, "Failed to join the system: " + e.getMessage());
return;
}
finally {
try {
joinSocket.close();
}
catch(Exception e) {
}
}
Log.i(TAG, "Starting serving commands");
try {
masterSocket = commandsServerSocket.accept();
}
catch(IOException e) {
Log.e(TAG, "Failed to accept socket for command serving");
return;
}
Log.i(TAG, "Accepted command socket from " + masterSocket.getInetAddress().toString());
/* Listen on MasterSocket for incoming commands from the Master */
Log.i(TAG, "Listening for commands from the Master node");
while(!this.isInterrupted()) {
try {
message = receive(masterSocket);
switch(message.getTag()) {
case PEER_DATA:
Log.i(TAG, "Received PEER_DATA command");
peerData.addPeersFromMessage(message);
break;
case SYNC:
Log.i(TAG, "Received SYNC command");
timeSync.timeReference(Long.parseLong(message.getPayload()));
break;
case NEW_PEER:
Log.i(TAG, "Received NEW_PEER command");
peerData.addPeerIP(message.getPayload());
break;
case START_SAMPLING:
Log.i(TAG, "Received START_SAMPLING command");
break;
case STOP_SAMPLING:
Log.i(TAG, "Received STOP_SAMPLING command");
break;
case SEND_PEAKS:
Log.i(TAG, "Received SEND_PEAKS command");
break;
default:
Log.e(TAG, "Not implemented Tag handling: " + message.getTag().toString());
break;
}
}
catch(IOException e) {
Log.e(TAG, "Error while listening to commands from Master node");
e.printStackTrace();
}
catch(ClassNotFoundException e) {
Log.e(TAG, "Error while receiving data");
e.printStackTrace();
}
}
}
|
diff --git a/htroot/Status.java b/htroot/Status.java
index 64da94883..982d59686 100644
--- a/htroot/Status.java
+++ b/htroot/Status.java
@@ -1,324 +1,324 @@
// Status.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// 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 Status.java
// if the shell's current path is HTROOT
import java.util.Date;
import de.anomic.http.httpHeader;
import de.anomic.http.httpd;
import de.anomic.http.httpdByteCountInputStream;
import de.anomic.http.httpdByteCountOutputStream;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverCore;
import de.anomic.server.serverDate;
import de.anomic.server.serverDomains;
import de.anomic.server.serverMemory;
import de.anomic.server.serverObjects;
import de.anomic.server.serverProcessor;
import de.anomic.server.serverSwitch;
import de.anomic.tools.yFormatter;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacyVersion;
public class Status {
private static final String SEEDSERVER = "seedServer";
private static final String PEERSTATUS = "peerStatus";
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
if (post != null) {
if (sb.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE","admin log-in");
return prop;
}
boolean redirect = false;
if (post.containsKey("login")) {
prop.put("LOCATION","");
return prop;
} else if (post.containsKey("pauseCrawlJob")) {
String jobType = (String) post.get("jobType");
if (jobType.equals("localCrawl"))
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
else if (jobType.equals("remoteTriggeredCrawl"))
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
redirect = true;
} else if (post.containsKey("continueCrawlJob")) {
String jobType = (String) post.get("jobType");
if (jobType.equals("localCrawl"))
sb.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
else if (jobType.equals("remoteTriggeredCrawl"))
sb.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
redirect = true;
} else if (post.containsKey("ResetTraffic")) {
httpdByteCountInputStream.resetCount();
httpdByteCountOutputStream.resetCount();
redirect = true;
} else if (post.containsKey("popup")) {
String trigger_enabled = (String) post.get("popup");
if (trigger_enabled.equals("false")) {
sb.setConfig("browserPopUpTrigger", "false");
} else if (trigger_enabled.equals("true")){
sb.setConfig("browserPopUpTrigger", "true");
}
redirect = true;
}
if (redirect) {
prop.put("LOCATION","");
return prop;
}
}
// update seed info
yacyCore.peerActions.updateMySeed();
boolean adminaccess = sb.adminAuthenticated(header) >= 2;
if (adminaccess) {
prop.put("showPrivateTable", "1");
prop.put("privateStatusTable", "Status_p.inc");
} else {
prop.put("showPrivateTable", "0");
prop.put("privateStatusTable", "");
}
// password protection
- if (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() == 0) {
+ if ((sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() == 0) && (!sb.getConfigBool("adminAccountForLocalhost", false))) {
prop.put("protection", "0"); // not protected
prop.put("urgentSetPassword", "1");
} else {
prop.put("protection", "1"); // protected
}
// version information
String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
prop.put("versionpp", versionstring);
double thisVersion = Double.parseDouble(sb.getConfig("version","0.1"));
// cut off the SVN Rev in the Version
try {thisVersion = Math.round(thisVersion*1000.0)/1000.0;} catch (NumberFormatException e) {}
// place some more hints
if ((adminaccess) && (sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount() == 0) && (sb.getThread(plasmaSwitchboard.INDEXER).getJobCount() == 0)) {
prop.put("hintCrawlStart", "1");
}
if ((adminaccess) && (sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount() > 500)) {
prop.put("hintCrawlMonitor", "1");
}
// hostname and port
String extendedPortString = sb.getConfig("port", "8080");
int pos = extendedPortString.indexOf(":");
prop.put("port",serverCore.getPortNr(extendedPortString));
if (pos!=-1) {
prop.put("extPortFormat", "1");
prop.put("extPortFormat_extPort",extendedPortString);
} else {
prop.put("extPortFormat", "0");
}
prop.put("host", serverDomains.myPublicLocalIP().getHostAddress());
// ssl support
prop.put("sslSupport",sb.getConfig("keyStore", "").length() == 0 ? "0" : "1");
if (sb.getConfig("remoteProxyUse", "false").equals("true")) {
prop.put("remoteProxy", "1");
prop.putHTML("remoteProxy_host", sb.getConfig("remoteProxyHost", "<unknown>"), true);
prop.putHTML("remoteProxy_port", sb.getConfig("remoteProxyPort", "<unknown>"), true);
prop.put("remoteProxy_4Yacy", sb.getConfig("remoteProxyUse4Yacy", "true").equalsIgnoreCase("true") ? "0" : "1");
} else {
prop.put("remoteProxy", "0"); // not used
}
// peer information
String thisHash = "";
final String thisName = sb.getConfig("peerName", "<nameless>");
if (sb.webIndex.seedDB.mySeed() == null) {
thisHash = "not assigned";
prop.put("peerAddress", "0"); // not assigned
prop.put("peerStatistics", "0"); // unknown
} else {
final long uptime = 60000 * Long.parseLong(sb.webIndex.seedDB.mySeed().get(yacySeed.UPTIME, "0"));
prop.put("peerStatistics", "1");
prop.put("peerStatistics_uptime", serverDate.formatInterval(uptime));
prop.putNum("peerStatistics_pagesperminute", sb.webIndex.seedDB.mySeed().getPPM());
prop.putNum("peerStatistics_queriesperhour", Math.round(6000d * sb.webIndex.seedDB.mySeed().getQPM()) / 100d);
prop.putNum("peerStatistics_links", sb.webIndex.seedDB.mySeed().getLinkCount());
prop.put("peerStatistics_words", yFormatter.number(sb.webIndex.seedDB.mySeed().get(yacySeed.ICOUNT, "0")));
prop.putNum("peerStatistics_juniorConnects", yacyCore.peerActions.juniorConnects);
prop.putNum("peerStatistics_seniorConnects", yacyCore.peerActions.seniorConnects);
prop.putNum("peerStatistics_principalConnects", yacyCore.peerActions.principalConnects);
prop.putNum("peerStatistics_disconnects", yacyCore.peerActions.disconnects);
prop.put("peerStatistics_connects", yFormatter.number(sb.webIndex.seedDB.mySeed().get(yacySeed.CCOUNT, "0")));
if (sb.webIndex.seedDB.mySeed().getPublicAddress() == null) {
thisHash = sb.webIndex.seedDB.mySeed().hash;
prop.put("peerAddress", "0"); // not assigned + instructions
prop.put("warningGoOnline", "1");
} else {
thisHash = sb.webIndex.seedDB.mySeed().hash;
prop.put("peerAddress", "1"); // Address
prop.put("peerAddress_address", sb.webIndex.seedDB.mySeed().getPublicAddress());
prop.putHTML("peerAddress_peername", sb.getConfig("peerName", "<nameless>").toLowerCase(), true);
}
}
final String peerStatus = ((sb.webIndex.seedDB.mySeed() == null) ? yacySeed.PEERTYPE_VIRGIN : sb.webIndex.seedDB.mySeed().get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_VIRGIN));
if (peerStatus.equals(yacySeed.PEERTYPE_VIRGIN)) {
prop.put(PEERSTATUS, "0");
prop.put("urgentStatusVirgin", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_JUNIOR)) {
prop.put(PEERSTATUS, "1");
prop.put("warningStatusJunior", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_SENIOR)) {
prop.put(PEERSTATUS, "2");
prop.put("hintStatusSenior", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_PRINCIPAL)) {
prop.put(PEERSTATUS, "3");
prop.put("hintStatusPrincipal", "1");
prop.put("hintStatusPrincipal_seedURL", sb.webIndex.seedDB.mySeed().get("seedURL", "?"));
}
prop.putHTML("peerName", thisName);
prop.put("hash", thisHash);
final String seedUploadMethod = sb.getConfig("seedUploadMethod", "");
if (!seedUploadMethod.equalsIgnoreCase("none") ||
(seedUploadMethod.equals("") && sb.getConfig("seedFTPPassword", "").length() > 0) ||
(seedUploadMethod.equals("") && sb.getConfig("seedFilePath", "").length() > 0)) {
if (seedUploadMethod.equals("")) {
if (sb.getConfig("seedFTPPassword", "").length() > 0) {
sb.setConfig("seedUploadMethod","Ftp");
}
if (sb.getConfig("seedFilePath", "").length() > 0) {
sb.setConfig("seedUploadMethod","File");
}
}
if (seedUploadMethod.equalsIgnoreCase("ftp")) {
prop.put(SEEDSERVER, "1"); // enabled
prop.put("seedServer_seedServer", sb.getConfig("seedFTPServer", ""));
} else if (seedUploadMethod.equalsIgnoreCase("scp")) {
prop.put(SEEDSERVER, "1"); // enabled
prop.put("seedServer_seedServer", sb.getConfig("seedScpServer", ""));
} else if (seedUploadMethod.equalsIgnoreCase("file")) {
prop.put(SEEDSERVER, "2"); // enabled
prop.put("seedServer_seedFile", sb.getConfig("seedFilePath", ""));
}
prop.put("seedServer_lastUpload",
serverDate.formatInterval(System.currentTimeMillis() - sb.webIndex.seedDB.lastSeedUpload_timeStamp));
} else {
prop.put(SEEDSERVER, "0"); // disabled
}
if (sb.webIndex.seedDB != null && sb.webIndex.seedDB.sizeConnected() > 0){
prop.put("otherPeers", "1");
prop.putNum("otherPeers_num", sb.webIndex.seedDB.sizeConnected());
}else{
prop.put("otherPeers", "0"); // not online
}
if (sb.getConfig("browserPopUpTrigger", "false").equals("false")) {
prop.put("popup", "0");
} else {
prop.put("popup", "1");
}
if (sb.getConfig("onlineMode", "1").equals("0")) {
prop.put("omode", "0");
} else if (sb.getConfig("onlineMode", "1").equals("1")) {
prop.put("omode", "1");
} else {
prop.put("omode", "2");
}
// memory usage and system attributes
prop.put("freeMemory", serverMemory.bytesToString(serverMemory.free()));
prop.put("totalMemory", serverMemory.bytesToString(serverMemory.total()));
prop.put("maxMemory", serverMemory.bytesToString(serverMemory.max()));
prop.put("processors", serverProcessor.availableCPU);
// proxy traffic
//prop.put("trafficIn",bytesToString(httpdByteCountInputStream.getGlobalCount()));
prop.put("trafficProxy", serverMemory.bytesToString(httpdByteCountOutputStream.getAccountCount("PROXY")));
prop.put("trafficCrawler", serverMemory.bytesToString(httpdByteCountInputStream.getAccountCount("CRAWLER")));
// connection information
serverCore httpd = (serverCore) sb.getThread("10_httpd");
prop.putNum("connectionsActive", httpd.getJobCount());
prop.putNum("connectionsMax", httpd.getMaxSessionCount());
// Queue information
int indexingJobCount = sb.getThread("80_indexing").getJobCount() + sb.webIndex.queuePreStack.getActiveQueueSize();
int indexingMaxCount = (int) sb.getConfigLong(plasmaSwitchboard.INDEXER_SLOTS, 30);
int indexingPercent = (indexingMaxCount==0)?0:indexingJobCount*100/indexingMaxCount;
prop.putNum("indexingQueueSize", indexingJobCount);
prop.putNum("indexingQueueMax", indexingMaxCount);
prop.put("indexingQueuePercent",(indexingPercent>100) ? 100 : indexingPercent);
int loaderJobCount = sb.crawlQueues.size();
int loaderMaxCount = Integer.parseInt(sb.getConfig(plasmaSwitchboard.CRAWLER_THREADS_ACTIVE_MAX, "10"));
int loaderPercent = (loaderMaxCount==0)?0:loaderJobCount*100/loaderMaxCount;
prop.putNum("loaderQueueSize", loaderJobCount);
prop.putNum("loaderQueueMax", loaderMaxCount);
prop.put("loaderQueuePercent", (loaderPercent>100) ? 100 : loaderPercent);
prop.putNum("localCrawlQueueSize", sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount());
prop.put("localCrawlPaused",sb.crawlJobIsPaused(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL) ? "1" : "0");
prop.putNum("remoteTriggeredCrawlQueueSize", sb.getThread(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL).getJobCount());
prop.put("remoteTriggeredCrawlPaused",sb.crawlJobIsPaused(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL) ? "1" : "0");
prop.putNum("stackCrawlQueueSize", sb.crawlStacker.size());
// return rewrite properties
prop.put("date",(new Date()).toString());
return prop;
}
}
| true | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
if (post != null) {
if (sb.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE","admin log-in");
return prop;
}
boolean redirect = false;
if (post.containsKey("login")) {
prop.put("LOCATION","");
return prop;
} else if (post.containsKey("pauseCrawlJob")) {
String jobType = (String) post.get("jobType");
if (jobType.equals("localCrawl"))
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
else if (jobType.equals("remoteTriggeredCrawl"))
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
redirect = true;
} else if (post.containsKey("continueCrawlJob")) {
String jobType = (String) post.get("jobType");
if (jobType.equals("localCrawl"))
sb.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
else if (jobType.equals("remoteTriggeredCrawl"))
sb.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
redirect = true;
} else if (post.containsKey("ResetTraffic")) {
httpdByteCountInputStream.resetCount();
httpdByteCountOutputStream.resetCount();
redirect = true;
} else if (post.containsKey("popup")) {
String trigger_enabled = (String) post.get("popup");
if (trigger_enabled.equals("false")) {
sb.setConfig("browserPopUpTrigger", "false");
} else if (trigger_enabled.equals("true")){
sb.setConfig("browserPopUpTrigger", "true");
}
redirect = true;
}
if (redirect) {
prop.put("LOCATION","");
return prop;
}
}
// update seed info
yacyCore.peerActions.updateMySeed();
boolean adminaccess = sb.adminAuthenticated(header) >= 2;
if (adminaccess) {
prop.put("showPrivateTable", "1");
prop.put("privateStatusTable", "Status_p.inc");
} else {
prop.put("showPrivateTable", "0");
prop.put("privateStatusTable", "");
}
// password protection
if (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() == 0) {
prop.put("protection", "0"); // not protected
prop.put("urgentSetPassword", "1");
} else {
prop.put("protection", "1"); // protected
}
// version information
String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
prop.put("versionpp", versionstring);
double thisVersion = Double.parseDouble(sb.getConfig("version","0.1"));
// cut off the SVN Rev in the Version
try {thisVersion = Math.round(thisVersion*1000.0)/1000.0;} catch (NumberFormatException e) {}
// place some more hints
if ((adminaccess) && (sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount() == 0) && (sb.getThread(plasmaSwitchboard.INDEXER).getJobCount() == 0)) {
prop.put("hintCrawlStart", "1");
}
if ((adminaccess) && (sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount() > 500)) {
prop.put("hintCrawlMonitor", "1");
}
// hostname and port
String extendedPortString = sb.getConfig("port", "8080");
int pos = extendedPortString.indexOf(":");
prop.put("port",serverCore.getPortNr(extendedPortString));
if (pos!=-1) {
prop.put("extPortFormat", "1");
prop.put("extPortFormat_extPort",extendedPortString);
} else {
prop.put("extPortFormat", "0");
}
prop.put("host", serverDomains.myPublicLocalIP().getHostAddress());
// ssl support
prop.put("sslSupport",sb.getConfig("keyStore", "").length() == 0 ? "0" : "1");
if (sb.getConfig("remoteProxyUse", "false").equals("true")) {
prop.put("remoteProxy", "1");
prop.putHTML("remoteProxy_host", sb.getConfig("remoteProxyHost", "<unknown>"), true);
prop.putHTML("remoteProxy_port", sb.getConfig("remoteProxyPort", "<unknown>"), true);
prop.put("remoteProxy_4Yacy", sb.getConfig("remoteProxyUse4Yacy", "true").equalsIgnoreCase("true") ? "0" : "1");
} else {
prop.put("remoteProxy", "0"); // not used
}
// peer information
String thisHash = "";
final String thisName = sb.getConfig("peerName", "<nameless>");
if (sb.webIndex.seedDB.mySeed() == null) {
thisHash = "not assigned";
prop.put("peerAddress", "0"); // not assigned
prop.put("peerStatistics", "0"); // unknown
} else {
final long uptime = 60000 * Long.parseLong(sb.webIndex.seedDB.mySeed().get(yacySeed.UPTIME, "0"));
prop.put("peerStatistics", "1");
prop.put("peerStatistics_uptime", serverDate.formatInterval(uptime));
prop.putNum("peerStatistics_pagesperminute", sb.webIndex.seedDB.mySeed().getPPM());
prop.putNum("peerStatistics_queriesperhour", Math.round(6000d * sb.webIndex.seedDB.mySeed().getQPM()) / 100d);
prop.putNum("peerStatistics_links", sb.webIndex.seedDB.mySeed().getLinkCount());
prop.put("peerStatistics_words", yFormatter.number(sb.webIndex.seedDB.mySeed().get(yacySeed.ICOUNT, "0")));
prop.putNum("peerStatistics_juniorConnects", yacyCore.peerActions.juniorConnects);
prop.putNum("peerStatistics_seniorConnects", yacyCore.peerActions.seniorConnects);
prop.putNum("peerStatistics_principalConnects", yacyCore.peerActions.principalConnects);
prop.putNum("peerStatistics_disconnects", yacyCore.peerActions.disconnects);
prop.put("peerStatistics_connects", yFormatter.number(sb.webIndex.seedDB.mySeed().get(yacySeed.CCOUNT, "0")));
if (sb.webIndex.seedDB.mySeed().getPublicAddress() == null) {
thisHash = sb.webIndex.seedDB.mySeed().hash;
prop.put("peerAddress", "0"); // not assigned + instructions
prop.put("warningGoOnline", "1");
} else {
thisHash = sb.webIndex.seedDB.mySeed().hash;
prop.put("peerAddress", "1"); // Address
prop.put("peerAddress_address", sb.webIndex.seedDB.mySeed().getPublicAddress());
prop.putHTML("peerAddress_peername", sb.getConfig("peerName", "<nameless>").toLowerCase(), true);
}
}
final String peerStatus = ((sb.webIndex.seedDB.mySeed() == null) ? yacySeed.PEERTYPE_VIRGIN : sb.webIndex.seedDB.mySeed().get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_VIRGIN));
if (peerStatus.equals(yacySeed.PEERTYPE_VIRGIN)) {
prop.put(PEERSTATUS, "0");
prop.put("urgentStatusVirgin", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_JUNIOR)) {
prop.put(PEERSTATUS, "1");
prop.put("warningStatusJunior", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_SENIOR)) {
prop.put(PEERSTATUS, "2");
prop.put("hintStatusSenior", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_PRINCIPAL)) {
prop.put(PEERSTATUS, "3");
prop.put("hintStatusPrincipal", "1");
prop.put("hintStatusPrincipal_seedURL", sb.webIndex.seedDB.mySeed().get("seedURL", "?"));
}
prop.putHTML("peerName", thisName);
prop.put("hash", thisHash);
final String seedUploadMethod = sb.getConfig("seedUploadMethod", "");
if (!seedUploadMethod.equalsIgnoreCase("none") ||
(seedUploadMethod.equals("") && sb.getConfig("seedFTPPassword", "").length() > 0) ||
(seedUploadMethod.equals("") && sb.getConfig("seedFilePath", "").length() > 0)) {
if (seedUploadMethod.equals("")) {
if (sb.getConfig("seedFTPPassword", "").length() > 0) {
sb.setConfig("seedUploadMethod","Ftp");
}
if (sb.getConfig("seedFilePath", "").length() > 0) {
sb.setConfig("seedUploadMethod","File");
}
}
if (seedUploadMethod.equalsIgnoreCase("ftp")) {
prop.put(SEEDSERVER, "1"); // enabled
prop.put("seedServer_seedServer", sb.getConfig("seedFTPServer", ""));
} else if (seedUploadMethod.equalsIgnoreCase("scp")) {
prop.put(SEEDSERVER, "1"); // enabled
prop.put("seedServer_seedServer", sb.getConfig("seedScpServer", ""));
} else if (seedUploadMethod.equalsIgnoreCase("file")) {
prop.put(SEEDSERVER, "2"); // enabled
prop.put("seedServer_seedFile", sb.getConfig("seedFilePath", ""));
}
prop.put("seedServer_lastUpload",
serverDate.formatInterval(System.currentTimeMillis() - sb.webIndex.seedDB.lastSeedUpload_timeStamp));
} else {
prop.put(SEEDSERVER, "0"); // disabled
}
if (sb.webIndex.seedDB != null && sb.webIndex.seedDB.sizeConnected() > 0){
prop.put("otherPeers", "1");
prop.putNum("otherPeers_num", sb.webIndex.seedDB.sizeConnected());
}else{
prop.put("otherPeers", "0"); // not online
}
if (sb.getConfig("browserPopUpTrigger", "false").equals("false")) {
prop.put("popup", "0");
} else {
prop.put("popup", "1");
}
if (sb.getConfig("onlineMode", "1").equals("0")) {
prop.put("omode", "0");
} else if (sb.getConfig("onlineMode", "1").equals("1")) {
prop.put("omode", "1");
} else {
prop.put("omode", "2");
}
// memory usage and system attributes
prop.put("freeMemory", serverMemory.bytesToString(serverMemory.free()));
prop.put("totalMemory", serverMemory.bytesToString(serverMemory.total()));
prop.put("maxMemory", serverMemory.bytesToString(serverMemory.max()));
prop.put("processors", serverProcessor.availableCPU);
// proxy traffic
//prop.put("trafficIn",bytesToString(httpdByteCountInputStream.getGlobalCount()));
prop.put("trafficProxy", serverMemory.bytesToString(httpdByteCountOutputStream.getAccountCount("PROXY")));
prop.put("trafficCrawler", serverMemory.bytesToString(httpdByteCountInputStream.getAccountCount("CRAWLER")));
// connection information
serverCore httpd = (serverCore) sb.getThread("10_httpd");
prop.putNum("connectionsActive", httpd.getJobCount());
prop.putNum("connectionsMax", httpd.getMaxSessionCount());
// Queue information
int indexingJobCount = sb.getThread("80_indexing").getJobCount() + sb.webIndex.queuePreStack.getActiveQueueSize();
int indexingMaxCount = (int) sb.getConfigLong(plasmaSwitchboard.INDEXER_SLOTS, 30);
int indexingPercent = (indexingMaxCount==0)?0:indexingJobCount*100/indexingMaxCount;
prop.putNum("indexingQueueSize", indexingJobCount);
prop.putNum("indexingQueueMax", indexingMaxCount);
prop.put("indexingQueuePercent",(indexingPercent>100) ? 100 : indexingPercent);
int loaderJobCount = sb.crawlQueues.size();
int loaderMaxCount = Integer.parseInt(sb.getConfig(plasmaSwitchboard.CRAWLER_THREADS_ACTIVE_MAX, "10"));
int loaderPercent = (loaderMaxCount==0)?0:loaderJobCount*100/loaderMaxCount;
prop.putNum("loaderQueueSize", loaderJobCount);
prop.putNum("loaderQueueMax", loaderMaxCount);
prop.put("loaderQueuePercent", (loaderPercent>100) ? 100 : loaderPercent);
prop.putNum("localCrawlQueueSize", sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount());
prop.put("localCrawlPaused",sb.crawlJobIsPaused(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL) ? "1" : "0");
prop.putNum("remoteTriggeredCrawlQueueSize", sb.getThread(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL).getJobCount());
prop.put("remoteTriggeredCrawlPaused",sb.crawlJobIsPaused(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL) ? "1" : "0");
prop.putNum("stackCrawlQueueSize", sb.crawlStacker.size());
// return rewrite properties
prop.put("date",(new Date()).toString());
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch<?> env) {
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
if (post != null) {
if (sb.adminAuthenticated(header) < 2) {
prop.put("AUTHENTICATE","admin log-in");
return prop;
}
boolean redirect = false;
if (post.containsKey("login")) {
prop.put("LOCATION","");
return prop;
} else if (post.containsKey("pauseCrawlJob")) {
String jobType = (String) post.get("jobType");
if (jobType.equals("localCrawl"))
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
else if (jobType.equals("remoteTriggeredCrawl"))
sb.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
redirect = true;
} else if (post.containsKey("continueCrawlJob")) {
String jobType = (String) post.get("jobType");
if (jobType.equals("localCrawl"))
sb.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
else if (jobType.equals("remoteTriggeredCrawl"))
sb.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL);
redirect = true;
} else if (post.containsKey("ResetTraffic")) {
httpdByteCountInputStream.resetCount();
httpdByteCountOutputStream.resetCount();
redirect = true;
} else if (post.containsKey("popup")) {
String trigger_enabled = (String) post.get("popup");
if (trigger_enabled.equals("false")) {
sb.setConfig("browserPopUpTrigger", "false");
} else if (trigger_enabled.equals("true")){
sb.setConfig("browserPopUpTrigger", "true");
}
redirect = true;
}
if (redirect) {
prop.put("LOCATION","");
return prop;
}
}
// update seed info
yacyCore.peerActions.updateMySeed();
boolean adminaccess = sb.adminAuthenticated(header) >= 2;
if (adminaccess) {
prop.put("showPrivateTable", "1");
prop.put("privateStatusTable", "Status_p.inc");
} else {
prop.put("showPrivateTable", "0");
prop.put("privateStatusTable", "");
}
// password protection
if ((sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() == 0) && (!sb.getConfigBool("adminAccountForLocalhost", false))) {
prop.put("protection", "0"); // not protected
prop.put("urgentSetPassword", "1");
} else {
prop.put("protection", "1"); // protected
}
// version information
String versionstring = yacyVersion.combined2prettyVersion(sb.getConfig("version","0.1"));
prop.put("versionpp", versionstring);
double thisVersion = Double.parseDouble(sb.getConfig("version","0.1"));
// cut off the SVN Rev in the Version
try {thisVersion = Math.round(thisVersion*1000.0)/1000.0;} catch (NumberFormatException e) {}
// place some more hints
if ((adminaccess) && (sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount() == 0) && (sb.getThread(plasmaSwitchboard.INDEXER).getJobCount() == 0)) {
prop.put("hintCrawlStart", "1");
}
if ((adminaccess) && (sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount() > 500)) {
prop.put("hintCrawlMonitor", "1");
}
// hostname and port
String extendedPortString = sb.getConfig("port", "8080");
int pos = extendedPortString.indexOf(":");
prop.put("port",serverCore.getPortNr(extendedPortString));
if (pos!=-1) {
prop.put("extPortFormat", "1");
prop.put("extPortFormat_extPort",extendedPortString);
} else {
prop.put("extPortFormat", "0");
}
prop.put("host", serverDomains.myPublicLocalIP().getHostAddress());
// ssl support
prop.put("sslSupport",sb.getConfig("keyStore", "").length() == 0 ? "0" : "1");
if (sb.getConfig("remoteProxyUse", "false").equals("true")) {
prop.put("remoteProxy", "1");
prop.putHTML("remoteProxy_host", sb.getConfig("remoteProxyHost", "<unknown>"), true);
prop.putHTML("remoteProxy_port", sb.getConfig("remoteProxyPort", "<unknown>"), true);
prop.put("remoteProxy_4Yacy", sb.getConfig("remoteProxyUse4Yacy", "true").equalsIgnoreCase("true") ? "0" : "1");
} else {
prop.put("remoteProxy", "0"); // not used
}
// peer information
String thisHash = "";
final String thisName = sb.getConfig("peerName", "<nameless>");
if (sb.webIndex.seedDB.mySeed() == null) {
thisHash = "not assigned";
prop.put("peerAddress", "0"); // not assigned
prop.put("peerStatistics", "0"); // unknown
} else {
final long uptime = 60000 * Long.parseLong(sb.webIndex.seedDB.mySeed().get(yacySeed.UPTIME, "0"));
prop.put("peerStatistics", "1");
prop.put("peerStatistics_uptime", serverDate.formatInterval(uptime));
prop.putNum("peerStatistics_pagesperminute", sb.webIndex.seedDB.mySeed().getPPM());
prop.putNum("peerStatistics_queriesperhour", Math.round(6000d * sb.webIndex.seedDB.mySeed().getQPM()) / 100d);
prop.putNum("peerStatistics_links", sb.webIndex.seedDB.mySeed().getLinkCount());
prop.put("peerStatistics_words", yFormatter.number(sb.webIndex.seedDB.mySeed().get(yacySeed.ICOUNT, "0")));
prop.putNum("peerStatistics_juniorConnects", yacyCore.peerActions.juniorConnects);
prop.putNum("peerStatistics_seniorConnects", yacyCore.peerActions.seniorConnects);
prop.putNum("peerStatistics_principalConnects", yacyCore.peerActions.principalConnects);
prop.putNum("peerStatistics_disconnects", yacyCore.peerActions.disconnects);
prop.put("peerStatistics_connects", yFormatter.number(sb.webIndex.seedDB.mySeed().get(yacySeed.CCOUNT, "0")));
if (sb.webIndex.seedDB.mySeed().getPublicAddress() == null) {
thisHash = sb.webIndex.seedDB.mySeed().hash;
prop.put("peerAddress", "0"); // not assigned + instructions
prop.put("warningGoOnline", "1");
} else {
thisHash = sb.webIndex.seedDB.mySeed().hash;
prop.put("peerAddress", "1"); // Address
prop.put("peerAddress_address", sb.webIndex.seedDB.mySeed().getPublicAddress());
prop.putHTML("peerAddress_peername", sb.getConfig("peerName", "<nameless>").toLowerCase(), true);
}
}
final String peerStatus = ((sb.webIndex.seedDB.mySeed() == null) ? yacySeed.PEERTYPE_VIRGIN : sb.webIndex.seedDB.mySeed().get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_VIRGIN));
if (peerStatus.equals(yacySeed.PEERTYPE_VIRGIN)) {
prop.put(PEERSTATUS, "0");
prop.put("urgentStatusVirgin", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_JUNIOR)) {
prop.put(PEERSTATUS, "1");
prop.put("warningStatusJunior", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_SENIOR)) {
prop.put(PEERSTATUS, "2");
prop.put("hintStatusSenior", "1");
} else if (peerStatus.equals(yacySeed.PEERTYPE_PRINCIPAL)) {
prop.put(PEERSTATUS, "3");
prop.put("hintStatusPrincipal", "1");
prop.put("hintStatusPrincipal_seedURL", sb.webIndex.seedDB.mySeed().get("seedURL", "?"));
}
prop.putHTML("peerName", thisName);
prop.put("hash", thisHash);
final String seedUploadMethod = sb.getConfig("seedUploadMethod", "");
if (!seedUploadMethod.equalsIgnoreCase("none") ||
(seedUploadMethod.equals("") && sb.getConfig("seedFTPPassword", "").length() > 0) ||
(seedUploadMethod.equals("") && sb.getConfig("seedFilePath", "").length() > 0)) {
if (seedUploadMethod.equals("")) {
if (sb.getConfig("seedFTPPassword", "").length() > 0) {
sb.setConfig("seedUploadMethod","Ftp");
}
if (sb.getConfig("seedFilePath", "").length() > 0) {
sb.setConfig("seedUploadMethod","File");
}
}
if (seedUploadMethod.equalsIgnoreCase("ftp")) {
prop.put(SEEDSERVER, "1"); // enabled
prop.put("seedServer_seedServer", sb.getConfig("seedFTPServer", ""));
} else if (seedUploadMethod.equalsIgnoreCase("scp")) {
prop.put(SEEDSERVER, "1"); // enabled
prop.put("seedServer_seedServer", sb.getConfig("seedScpServer", ""));
} else if (seedUploadMethod.equalsIgnoreCase("file")) {
prop.put(SEEDSERVER, "2"); // enabled
prop.put("seedServer_seedFile", sb.getConfig("seedFilePath", ""));
}
prop.put("seedServer_lastUpload",
serverDate.formatInterval(System.currentTimeMillis() - sb.webIndex.seedDB.lastSeedUpload_timeStamp));
} else {
prop.put(SEEDSERVER, "0"); // disabled
}
if (sb.webIndex.seedDB != null && sb.webIndex.seedDB.sizeConnected() > 0){
prop.put("otherPeers", "1");
prop.putNum("otherPeers_num", sb.webIndex.seedDB.sizeConnected());
}else{
prop.put("otherPeers", "0"); // not online
}
if (sb.getConfig("browserPopUpTrigger", "false").equals("false")) {
prop.put("popup", "0");
} else {
prop.put("popup", "1");
}
if (sb.getConfig("onlineMode", "1").equals("0")) {
prop.put("omode", "0");
} else if (sb.getConfig("onlineMode", "1").equals("1")) {
prop.put("omode", "1");
} else {
prop.put("omode", "2");
}
// memory usage and system attributes
prop.put("freeMemory", serverMemory.bytesToString(serverMemory.free()));
prop.put("totalMemory", serverMemory.bytesToString(serverMemory.total()));
prop.put("maxMemory", serverMemory.bytesToString(serverMemory.max()));
prop.put("processors", serverProcessor.availableCPU);
// proxy traffic
//prop.put("trafficIn",bytesToString(httpdByteCountInputStream.getGlobalCount()));
prop.put("trafficProxy", serverMemory.bytesToString(httpdByteCountOutputStream.getAccountCount("PROXY")));
prop.put("trafficCrawler", serverMemory.bytesToString(httpdByteCountInputStream.getAccountCount("CRAWLER")));
// connection information
serverCore httpd = (serverCore) sb.getThread("10_httpd");
prop.putNum("connectionsActive", httpd.getJobCount());
prop.putNum("connectionsMax", httpd.getMaxSessionCount());
// Queue information
int indexingJobCount = sb.getThread("80_indexing").getJobCount() + sb.webIndex.queuePreStack.getActiveQueueSize();
int indexingMaxCount = (int) sb.getConfigLong(plasmaSwitchboard.INDEXER_SLOTS, 30);
int indexingPercent = (indexingMaxCount==0)?0:indexingJobCount*100/indexingMaxCount;
prop.putNum("indexingQueueSize", indexingJobCount);
prop.putNum("indexingQueueMax", indexingMaxCount);
prop.put("indexingQueuePercent",(indexingPercent>100) ? 100 : indexingPercent);
int loaderJobCount = sb.crawlQueues.size();
int loaderMaxCount = Integer.parseInt(sb.getConfig(plasmaSwitchboard.CRAWLER_THREADS_ACTIVE_MAX, "10"));
int loaderPercent = (loaderMaxCount==0)?0:loaderJobCount*100/loaderMaxCount;
prop.putNum("loaderQueueSize", loaderJobCount);
prop.putNum("loaderQueueMax", loaderMaxCount);
prop.put("loaderQueuePercent", (loaderPercent>100) ? 100 : loaderPercent);
prop.putNum("localCrawlQueueSize", sb.getThread(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL).getJobCount());
prop.put("localCrawlPaused",sb.crawlJobIsPaused(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL) ? "1" : "0");
prop.putNum("remoteTriggeredCrawlQueueSize", sb.getThread(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL).getJobCount());
prop.put("remoteTriggeredCrawlPaused",sb.crawlJobIsPaused(plasmaSwitchboard.CRAWLJOB_REMOTE_TRIGGERED_CRAWL) ? "1" : "0");
prop.putNum("stackCrawlQueueSize", sb.crawlStacker.size());
// return rewrite properties
prop.put("date",(new Date()).toString());
return prop;
}
|
diff --git a/site-manage-impl/impl/src/java/org/sakaiproject/sitemanage/impl/ETSUserNotificationProviderImpl.java b/site-manage-impl/impl/src/java/org/sakaiproject/sitemanage/impl/ETSUserNotificationProviderImpl.java
index 6339dbdf..d9516079 100644
--- a/site-manage-impl/impl/src/java/org/sakaiproject/sitemanage/impl/ETSUserNotificationProviderImpl.java
+++ b/site-manage-impl/impl/src/java/org/sakaiproject/sitemanage/impl/ETSUserNotificationProviderImpl.java
@@ -1,314 +1,315 @@
package org.sakaiproject.sitemanage.impl;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.email.api.EmailService;
import org.sakaiproject.emailtemplateservice.model.EmailTemplate;
import org.sakaiproject.emailtemplateservice.model.RenderedTemplate;
import org.sakaiproject.emailtemplateservice.service.EmailTemplateService;
import org.sakaiproject.sitemanage.api.UserNotificationProvider;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.util.ResourceLoader;
//import org.w3c.dom.Document;
//import org.w3c.dom.Element;
//import org.w3c.dom.Node;
//import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import sun.util.logging.resources.logging;
import com.sun.org.apache.xerces.internal.util.DOMUtil;
public class ETSUserNotificationProviderImpl implements UserNotificationProvider {
private static Log M_log = LogFactory.getLog(ETSUserNotificationProviderImpl.class);
private static String NOTIFY_ADDED_PARTICIPANT ="sitemange.notifyAddedParticipant";
private static String NOTIFY_NEW_USER ="sitemanage.notifyNewUserEmail";
private EmailService emailService;
public void setEmailService(EmailService es) {
emailService = es;
}
private ServerConfigurationService serverConfigurationService;
public void setServerConfigurationService(ServerConfigurationService scs) {
serverConfigurationService = scs;
}
private UserDirectoryService userDirectoryService;
public void setUserDirectoryService(UserDirectoryService uds) {
userDirectoryService = uds;
}
private EmailTemplateService emailTemplateService;
public void setEmailTemplateService(EmailTemplateService ets) {
emailTemplateService = ets;
}
public void init() {
//nothing realy to do
M_log.info("init()");
//do we need to load data?
Map<String, String> replacementValues = new HashMap<String, String>();
if (emailTemplateService.getRenderedTemplateForUser(this.NOTIFY_ADDED_PARTICIPANT, "/user/admin", replacementValues) == null)
loadAddedParticipantMail();
else
M_log.info("templates for " + NOTIFY_ADDED_PARTICIPANT + " exist");
if (serverConfigurationService.getBoolean("auto.ddl", false)) {
if (emailTemplateService.getRenderedTemplateForUser(NOTIFY_NEW_USER, "/user/admin", replacementValues) == null)
loadNewUserMail();
else
M_log.info("templates for " + NOTIFY_NEW_USER + " exist");
if (emailTemplateService.getRenderedTemplateForUser(this.NOTIFY_ADDED_PARTICIPANT, "/user/admin", replacementValues) == null)
loadAddedParticipantMail();
else
M_log.info("templates for " + NOTIFY_NEW_USER + " exist");
}
}
public void notifyAddedParticipant(boolean newNonOfficialAccount,
User user, String siteTitle) {
String from = getSetupRequestEmailAddress();
//we need to get the template
if (from != null) {
String productionSiteName = serverConfigurationService.getString(
"ui.service", "");
String productionSiteUrl = serverConfigurationService
.getPortalUrl();
String nonOfficialAccountUrl = serverConfigurationService.getString(
"nonOfficialAccount.url", null);
String emailId = user.getEmail();
String to = emailId;
String headerTo = emailId;
String replyTo = emailId;
Map<String, String> rv = new HashMap<String, String>();
rv.put("productionSiteName", productionSiteName);
String content = "";
/*
* $userName
* $localSakaiName
* $currentUserName
* $localSakaiUrl
*/
Map<String, String> replacementValues = new HashMap<String, String>();
replacementValues.put("userName", user.getDisplayName());
replacementValues.put("userEid", user.getEid());
replacementValues.put("localSakaiName",serverConfigurationService.getString(
"ui.service", ""));
replacementValues.put("currentUserName",userDirectoryService.getCurrentUser().getDisplayName());
replacementValues.put("localSakaiUrl", serverConfigurationService.getPortalUrl());
replacementValues.put("siteName", siteTitle);
replacementValues.put("productionSiteName", productionSiteName);
+ replacementValues.put("newNonOfficialAccount", new Boolean(newNonOfficialAccount).toString());
M_log.debug("getting template: sitemange.notifyAddedParticipant");
RenderedTemplate template = null;
try {
template = emailTemplateService.getRenderedTemplateForUser(NOTIFY_ADDED_PARTICIPANT, user.getReference(), replacementValues);
if (template == null)
return;
}
catch (Exception e) {
e.printStackTrace();
}
List headers = new ArrayList();
headers.add("Precedence: bulk");
content = template.getRenderedMessage();
emailService.send(from, to, template.getRenderedSubject(), content, headerTo,
replyTo, headers);
} // if
}
public void notifyNewUserEmail(User user, String newUserPassword,
String siteTitle) {
String from = getSetupRequestEmailAddress();
String productionSiteName = serverConfigurationService.getString(
"ui.service", "");
String productionSiteUrl = serverConfigurationService.getPortalUrl();
String newUserEmail = user.getEmail();
String to = newUserEmail;
String headerTo = newUserEmail;
String replyTo = newUserEmail;
String content = "";
if (from != null && newUserEmail != null) {
/*
* $userName
* $localSakaiName
* $currentUserName
* $localSakaiUrl
*/
Map<String, String> replacementValues = new HashMap<String, String>();
replacementValues.put("userName", user.getDisplayName());
replacementValues.put("localSakaiName",serverConfigurationService.getString(
"ui.service", ""));
replacementValues.put("currentUserName",userDirectoryService.getCurrentUser().getDisplayName());
replacementValues.put("localSakaiUrl", serverConfigurationService.getPortalUrl());
replacementValues.put("newPassword",newUserPassword);
replacementValues.put("siteName", siteTitle);
replacementValues.put("productionSiteName", productionSiteName);
RenderedTemplate template = emailTemplateService.getRenderedTemplateForUser(this.NOTIFY_NEW_USER, user.getReference(), replacementValues);
if (template == null)
return;
content = template.getRenderedMessage();
String message_subject = template.getRenderedSubject();
List headers = new ArrayList();
headers.add("Precedence: bulk");
emailService.send(from, to, message_subject, content, headerTo,
replyTo, headers);
}
}
/*
* Private methods
*/
private String getSetupRequestEmailAddress() {
String from = serverConfigurationService.getString("setup.request",
null);
if (from == null) {
M_log.warn(this + " - no 'setup.request' in configuration");
from = "postmaster@".concat(serverConfigurationService
.getServerName());
}
return from;
}
private void loadAddedParticipantMail() {
try {
InputStream in = ETSUserNotificationProviderImpl.class.getClassLoader().getResourceAsStream("notifyAddedParticipants.xml");
Document document = new SAXBuilder( ).build(in);
List it = document.getRootElement().getChildren("emailTemplate");
for (int i =0; i < it.size(); i++) {
Element xmlTemplate = (Element)it.get(i);
xmlToTemplate(xmlTemplate, this.NOTIFY_ADDED_PARTICIPANT);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void loadNewUserMail() {
try {
InputStream in = ETSUserNotificationProviderImpl.class.getClassLoader().getResourceAsStream("notifyNewuser.xml");
Document document = new SAXBuilder( ).build(in);
List it = document.getRootElement().getChildren("emailTemplate");
for (int i =0; i < it.size(); i++) {
Element xmlTemplate = (Element)it.get(i);
xmlToTemplate(xmlTemplate, this.NOTIFY_NEW_USER);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void xmlToTemplate(Element xmlTemplate, String key) {
String subject = xmlTemplate.getChildText("subject");
String body = xmlTemplate.getChildText("message");
String locale = xmlTemplate.getChildText("locale");
M_log.info("subject: " + subject);
EmailTemplate template = new EmailTemplate();
template.setSubject(subject);
template.setMessage(body);
template.setLocale(locale);
template.setKey(key);
template.setOwner("admin");
template.setLastModified(new Date());
this.emailTemplateService.saveTemplate(template);
}
}
| true | true | public void notifyAddedParticipant(boolean newNonOfficialAccount,
User user, String siteTitle) {
String from = getSetupRequestEmailAddress();
//we need to get the template
if (from != null) {
String productionSiteName = serverConfigurationService.getString(
"ui.service", "");
String productionSiteUrl = serverConfigurationService
.getPortalUrl();
String nonOfficialAccountUrl = serverConfigurationService.getString(
"nonOfficialAccount.url", null);
String emailId = user.getEmail();
String to = emailId;
String headerTo = emailId;
String replyTo = emailId;
Map<String, String> rv = new HashMap<String, String>();
rv.put("productionSiteName", productionSiteName);
String content = "";
/*
* $userName
* $localSakaiName
* $currentUserName
* $localSakaiUrl
*/
Map<String, String> replacementValues = new HashMap<String, String>();
replacementValues.put("userName", user.getDisplayName());
replacementValues.put("userEid", user.getEid());
replacementValues.put("localSakaiName",serverConfigurationService.getString(
"ui.service", ""));
replacementValues.put("currentUserName",userDirectoryService.getCurrentUser().getDisplayName());
replacementValues.put("localSakaiUrl", serverConfigurationService.getPortalUrl());
replacementValues.put("siteName", siteTitle);
replacementValues.put("productionSiteName", productionSiteName);
M_log.debug("getting template: sitemange.notifyAddedParticipant");
RenderedTemplate template = null;
try {
template = emailTemplateService.getRenderedTemplateForUser(NOTIFY_ADDED_PARTICIPANT, user.getReference(), replacementValues);
if (template == null)
return;
}
catch (Exception e) {
e.printStackTrace();
}
List headers = new ArrayList();
headers.add("Precedence: bulk");
content = template.getRenderedMessage();
emailService.send(from, to, template.getRenderedSubject(), content, headerTo,
replyTo, headers);
} // if
}
| public void notifyAddedParticipant(boolean newNonOfficialAccount,
User user, String siteTitle) {
String from = getSetupRequestEmailAddress();
//we need to get the template
if (from != null) {
String productionSiteName = serverConfigurationService.getString(
"ui.service", "");
String productionSiteUrl = serverConfigurationService
.getPortalUrl();
String nonOfficialAccountUrl = serverConfigurationService.getString(
"nonOfficialAccount.url", null);
String emailId = user.getEmail();
String to = emailId;
String headerTo = emailId;
String replyTo = emailId;
Map<String, String> rv = new HashMap<String, String>();
rv.put("productionSiteName", productionSiteName);
String content = "";
/*
* $userName
* $localSakaiName
* $currentUserName
* $localSakaiUrl
*/
Map<String, String> replacementValues = new HashMap<String, String>();
replacementValues.put("userName", user.getDisplayName());
replacementValues.put("userEid", user.getEid());
replacementValues.put("localSakaiName",serverConfigurationService.getString(
"ui.service", ""));
replacementValues.put("currentUserName",userDirectoryService.getCurrentUser().getDisplayName());
replacementValues.put("localSakaiUrl", serverConfigurationService.getPortalUrl());
replacementValues.put("siteName", siteTitle);
replacementValues.put("productionSiteName", productionSiteName);
replacementValues.put("newNonOfficialAccount", new Boolean(newNonOfficialAccount).toString());
M_log.debug("getting template: sitemange.notifyAddedParticipant");
RenderedTemplate template = null;
try {
template = emailTemplateService.getRenderedTemplateForUser(NOTIFY_ADDED_PARTICIPANT, user.getReference(), replacementValues);
if (template == null)
return;
}
catch (Exception e) {
e.printStackTrace();
}
List headers = new ArrayList();
headers.add("Precedence: bulk");
content = template.getRenderedMessage();
emailService.send(from, to, template.getRenderedSubject(), content, headerTo,
replyTo, headers);
} // if
}
|
diff --git a/utilities/maven/Jaxb2SimpleXMLplugin/src/main/java/org/societies/maven/Jaxb2Simple.java b/utilities/maven/Jaxb2SimpleXMLplugin/src/main/java/org/societies/maven/Jaxb2Simple.java
index bb0ffc1c9..b54791460 100644
--- a/utilities/maven/Jaxb2SimpleXMLplugin/src/main/java/org/societies/maven/Jaxb2Simple.java
+++ b/utilities/maven/Jaxb2SimpleXMLplugin/src/main/java/org/societies/maven/Jaxb2Simple.java
@@ -1,597 +1,597 @@
/**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE 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.
*/
package org.societies.maven;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
/**
* @phase process-sources
* @goal convert
*/
public class Jaxb2Simple extends AbstractMojo
{
private final String FOLDER_PATH = "src/main/java"; //"target/generated-sources/xjc/"
private final String TO_STRING_CODE = " }\n\n @Override\n public String toString() {\n return this.value();\n }\n}\n";
/**
* Output directory for schemas
*
* @parameter default-value="src/main/resources/"
*/
private String folderOutputDirectory;
/**
* Input directory for schemas
*
* @parameter default-value="${project.build.directory}/generated-sources/"
*/
private String folderInputDirectory = FOLDER_PATH;
private Map<String, Set<String>> newClassesOnPackage = new HashMap<String, Set<String>>();
private Map<String, String> namespaceForPackage = new HashMap<String, String>();
public void execute() throws MojoExecutionException
{
// Init
initParameters();
File startingDirectory= new File(folderInputDirectory);
getLog().info("Source Directory: " + folderInputDirectory);
List<File> files = null;
try {
files = FileListing.getFileListing(startingDirectory);
// First process ObjectFactories and package-infos
for (File javaFile : files) {
if (javaFile.isFile() && javaFile.getName().equals("ObjectFactory.java")) {
getLog().debug("Processing: " + javaFile.getAbsolutePath());
processObjectFactory(javaFile);
}
if (javaFile.isFile() && javaFile.getName().equals("package-info.java")) {
getLog().debug("Processing: " + javaFile.getAbsolutePath());
processPackageInfo(javaFile);
}
}
// Process all java files now and delete unwanted ones
for (File javaFile : files) {
if (javaFile.isFile()) { //IGNORE DIRECTORIES
if (javaFile.getName().equals("ObjectFactory.java") || javaFile.getName().equals("package-info.java")) {
getLog().debug("Deleting: " + javaFile.getAbsolutePath());
javaFile.delete();
}
else {
if (javaFile.getName().endsWith(".java")) {
getLog().debug("Processing: " + javaFile.getAbsolutePath());
String newSchemaContent = processCodeFile(javaFile);
FileWriter newFile = new FileWriter(javaFile.getAbsolutePath());
newFile.write(newSchemaContent);
newFile.close();
}
}
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String processCodeFile(File javaFile) throws FileNotFoundException {
Scanner scanner = null;
String newSchemaContent = new String();
// READ THE ORIGINAL .java FILE
scanner = new Scanner(javaFile);
StringBuffer schemaContent = new StringBuffer();
while (scanner.hasNextLine()) {
schemaContent.append(scanner.nextLine()+"\n");
}
// Main Annotations Replacement
newSchemaContent = findReplacePatterns(schemaContent);
// Empty Elements Processing
Matcher m = packagePattern.matcher(newSchemaContent);
m.find();
String pkgName = m.group(1);
Map<String,String> fieldClasses = detectFields(newSchemaContent, newClassesOnPackage.get(pkgName));
for (String fieldName : fieldClasses.keySet()) {
String className = fieldClasses.get(fieldName);
getLog().debug("Changing class of field '"+fieldName+"' to class '"+className+"'");
newSchemaContent = replaceFieldAndAccessors(newSchemaContent, fieldName, className);
}
//ENUM NEEDS TO BE SERIALIZED WITH "VALUE", NOT "NAME"
if (newSchemaContent.indexOf("public enum ") > 0) {
String textToFind = ".*}\n\n}\n";
String textToReplace = TO_STRING_CODE;
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
}
//ADD IMPORT ElementList
if (newSchemaContent.indexOf("@ElementList") > 0) {
String textToFind = "(import org.simpleframework.xml.Element;)";
String textToReplace = "$1\nimport org.simpleframework.xml.ElementList;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
}
return newSchemaContent;
}
private static String replaceFieldAndAccessors(String newSchemaContent, String fieldName, String className) {
String textToFind = "protected String "+fieldName+";\n";
String textToReplace = "protected "+className+" "+fieldName+";\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
String capitalizedfieldName = Character.toUpperCase(fieldName.charAt(0))+fieldName.substring(1);;
textToFind = "public String get"+capitalizedfieldName+"\\(\\) \\{\n";
textToReplace = "public "+className+" get"+capitalizedfieldName+"() {\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
textToFind = "public void set"+capitalizedfieldName+"\\(String value\\) \\{\n";
textToReplace = "public void set"+capitalizedfieldName+"("+className+" value) {\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
return newSchemaContent;
}
private static final Pattern packagePattern = Pattern.compile("package ([\\d\\w.-]*);");
private static final Pattern fieldPattern = Pattern.compile("\\s*protected String (\\w*);\\s*");
private Map<String,String> detectFields(String newSchemaContent, Set<String> newClasses) {
Map<String,String> fieldClasses = new HashMap<String, String>();
Matcher matcher = fieldPattern.matcher(newSchemaContent);
while (matcher.find()) {
String fieldName = matcher.group(1);
for (String cl : newClasses) {
if (cl.equalsIgnoreCase(fieldName)) {
fieldClasses.put(fieldName,cl);
//System.out.println("replace 'protected String "+fieldName+";' with 'protected "+cl+" "+fieldName+";'");
break;
}
}
}
return fieldClasses;
}
private String findReplacePatterns(StringBuffer schemaContent) {
String newSchemaContent; String textToFind; String textToReplace;
newSchemaContent = schemaContent.toString();
//import javax.xml.bind.annotation.* -> import org.simpleframework.xml.*
//textToFind = "import javax.xml.bind.annotation.*import javax.xml.bind.annotation.\\w*;";
//textToReplace = "import org.simpleframework.xml.*;";
//newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//import javax\.xml\.bind\.annotation\.XmlAccessType/import org.simpleframework.xml.DefaultType
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAccessType;";
textToReplace = "import org.simpleframework.xml.DefaultType;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAccessorType/import org.simpleframework.xml.Default/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAccessorType;\n";
//textToReplace = "import org.simpleframework.xml.Default;";
textToReplace = ""; //PubSub has a class called Default also! Need to refer to xml.default by FQ name
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAttribute;/import org.simpleframework.xml.Attribute;
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAttribute;";
textToReplace = "import org.simpleframework.xml.Attribute;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlElement;/import org.simpleframework.xml.Element;/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlElement;";
- textToReplace = "import org.simpleframework.xml.Element;";
+ textToReplace = "import org.simpleframework.xml.Element;\nimport org.simpleframework.xml.Namespace;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlType;/import org.simpleframework.xml.Element;\nimport org.simpleframework.xml.Order;/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlType;";
textToReplace = "import org.simpleframework.xml.Order;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlRootElement/import org.simpleframework.xml.Root/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlRootElement;";
textToReplace = "import org.simpleframework.xml.Root;\nimport org.simpleframework.xml.Namespace;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlValue/import org.simpleframework.xml.Text
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlValue;";
textToReplace = "import org.simpleframework.xml.Text;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlElements/import org.simpleframework.xml.ElementList
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlElements;";
textToReplace = "import org.simpleframework.xml.ElementList;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter -> import org.simpleframework.xml.convert.Convert;
textToFind = "import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;";
textToReplace = "import org.simpleframework.xml.convert.Convert;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import org.w3._2001.xmlschema.Adapter1; -> import org.societies.maven.converters.URIConverter;
textToFind = "import org.w3._2001.xmlschema.Adapter1;";
textToReplace = "import org.societies.maven.converters.URIConverter;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -> import org.societies.maven.converters.CollapsedStringAdapter;
textToFind = "import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;";
textToReplace = "import org.societies.maven.converters.CollapsedStringAdapter;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlJavaTypeAdapter(Adapter1 .class) -> @Convert(URIConverter.class)
textToFind = "@XmlJavaTypeAdapter\\(Adapter1.*\\.class?\\)";
textToReplace = "@Convert(URIConverter.class)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlJavaTypeAdapter(CollapsedStringAdapter.class) -> @Convert(CollapsedStringAdapter.class)
textToFind = "@XmlJavaTypeAdapter\\(CollapsedStringAdapter.class?\\)";
textToReplace = "@Convert(CollapsedStringAdapter.class)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//REMOVE namespace FROM XmlElement ANNOTATION @XmlElement(namespace = "jabber:x:data")
//s/\(@XmlElement(name = ".*"\), namespace\( = ".*"\))/\1, required = false)\n @Namespace(reference\2)/
textToFind = "(@XmlElement\\(.*)namespace( = \".*\")\\)";
textToReplace = "$1required = false)\n @Namespace(reference$2)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(name = "Activity", namespace = "http://societies.org/api/schema/activity", required = true)
textToFind = "(@XmlElement\\(.*)namespace( = \".*\"),(.*)\\)";
textToReplace = "$1$3)\n @Namespace(reference$2)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlElement with List -> @XmlElementList @XmlElement(nillable = true) -> @ElementList(inline=true, entry="Service")
// @XmlElement(name[ ]*=\(.*\)).*\(\n.*List\<.*\>.*;\)/@ElementList(inline=true, entry=\1)\2/
textToFind = "@XmlElement\\(.*?\\)(\n.*?List\\<(.*?)\\>.*?;)";
//textToReplace = "@ElementList(inline=true, entry=\"$2\")$1";
textToReplace = "$1";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//@XmlElement -> @Element
//1) if "required = true|false" is missing then add "required=false" else do nothing
//2) remove nillable=true|false
//@XmlElement(required = true, type = Integer.class, nillable = true)
//textToFind = "(@XmlElement\\(.*)nillable = true|false\\)";
textToFind = ", nillable = (true|false)";
textToReplace = ""; //"$1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(required = true, type = Integer.class, nillable = true)
textToFind = "@XmlElement\\(nillable = true\\)";
textToReplace = "@Element(required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(\(.*required.*\))/@Element(\1)/ @XmlElement(required = true)
//textToFind = "@XmlElement(\\(.*required.*\\))";
textToFind = "@XmlElement\\((.*required.*?)\\)";
textToReplace = "@Element($1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(\(.*\))/@Element(required=false,\1)/
textToFind = "@XmlElement\\((.*?)\\)";
textToReplace = "@Element($1, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//NAMESPACE
Pattern patternNS = Pattern.compile("package (.*);", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
Matcher matcherNS = patternNS.matcher(newSchemaContent);
String ns = "";
if (matcherNS.find()) {
String pkgTmp = matcherNS.group();
String pkgFinal = pkgTmp.substring(8, pkgTmp.indexOf(";"));
// String[] nsArr = pkgFinal.split("\\.");
// ns = "@Namespace(reference=\"http://" + nsArr[1] + "." + nsArr[0];
// for(int i=2; i<nsArr.length; i++)
// ns+="/" + nsArr[i];
// ns += "\")\n";
ns = "@Namespace(reference=\""+namespaceForPackage.get(pkgFinal)+"\")\n"; // fix for non-default namespaces (eg pubsub#event) issue
}
// @XmlRootElement -> @Root + @Namespace(reference="http://...)
// s/@XmlRootElement(\(.*\))/@Root(\1, strict=false)/
//textToFind = "@XmlRootElement(\\(.*)\\)\n";
textToFind = "@XmlRootElement(\\(.*?)\\)\n";
textToReplace = "@Root$1, strict=false)\n" + ns;
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlType(.*propOrder[ ]*\(=.*\)/@Order(elements\1/
// textToFind = "@XmlType\\(.*propOrder";
// textToReplace = "@Order(elements";
// newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// TODO discarding element order information instead of placing @Order annotations
textToFind = "@XmlType\\([^\\)]*\\)";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\)[ ]*,[ ]*propOrder[ ]*\(=.*\)/@Default(DefaultType.\1)\n@Order(elements\3/
textToFind = "@XmlAccessorType\\(XmlAccessType.FIELD\\)";
textToReplace = "@org.simpleframework.xml.Default(value=DefaultType.FIELD, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\))/@Default(DefaultType.\1)\n@Root(\2, strict=false
//Pattern patternAccessor1 = Pattern.compile("@XmlAccessorType([ ]*XmlAccessType\\.\\(.*\\))\\n@XmlType(\\(.*\\))", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//Matcher matcherAccessor1 = patternAccessor1.matcher(newSchemaContent);
//newSchemaContent = matcherAccessor1.replaceAll("@Default(DefaultType.$1)\n@Root($2, strict=false");
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\)[ ]*,[ ]*propOrder[ ]*\(=.*\)/@Default(DefaultType.\1)\n@Order(elements\3/
//Pattern patternAccessor2 = Pattern.compile("@XmlAccessorType([ ]*XmlAccessType\\.\\(.*\\))\\n@XmlType(\\(.*\\)[ ]*,[ ]*propOrder[ ]*\\(=.*\\)", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//Matcher matcherAccessor2 = patternAccessor2.matcher(newSchemaContent);
//newSchemaContent = matcherAccessor.replaceAll("@Default(DefaultType.$1)\n@Order(elements$3");
// @XmlAttribute -> @Attribute
//if "required = true|false" is missing then add "required=false" else do nothing
textToFind = "@XmlAttribute\\((.*, required = true|false)\\)";
textToReplace = "@Attribute($1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//ADD required=false IF MISSING
textToFind = "@XmlAttribute\\((.*?(?!required = true|false))\\)";
textToReplace = "@Attribute($1, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlAttribute/@Attribute(required=false)/
textToFind = "@XmlAttribute\n";
textToReplace = "@Attribute(required=false)\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlValue -> @Text
textToFind = "@XmlValue";
textToReplace = "@Text(required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//REMOVE @XmlSchemaType(name = "anyURI")
textToFind = "@XmlSchemaType\\(name = \".*\"\\)\n ";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//ENUMERATOR FILE - REMOVE ALL ANNOTATIONS
textToFind = "@XmlEnum.*?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlType(name = "methodType")
textToFind = "@XmlType\\(name = \".*?\"\\)?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlSeeAlso/,/})
textToFind = "@XmlSeeAlso.*?}\\)\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
// @XmlAnyElement.*
textToFind = "@XmlAnyElement.*?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAnyElement;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAnyElement;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAnyAttribute;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAnyAttribute;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlSeeAlso;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlSeeAlso;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlSchemaType;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlSchemaType;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlEnum;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlEnum;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlEnumValue;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlEnumValue;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// /@XmlSchemaType.*/d
// /@XmlAnyAttribute.*/d
return newSchemaContent;
}
/**Replaces a regular expression with a specified string
* @param schemaContent The string to check
* @param textToFind Text to find
* @param textToReplace Text to replace
* @return Updated String with changes
*/
private static String findReplacePattern(String schemaContent, String textToFind, String textToReplace, int flags) {
Pattern patternImport = Pattern.compile(textToFind, flags);
Matcher matcherImport = patternImport.matcher(schemaContent);
int i = matcherImport.groupCount();
return matcherImport.replaceAll(textToReplace);
}
private static String findReplacePattern(String schemaContent, String textToFind, String textToReplace) {
return findReplacePattern(schemaContent, textToFind, textToReplace, Pattern.CASE_INSENSITIVE);
}
/**
* Init parameters
*/
private void initParameters() {
if (!folderOutputDirectory.equals(".") && !folderOutputDirectory.endsWith("/")) {
folderOutputDirectory += "/";
}
if (!folderInputDirectory.equals(".") && !folderInputDirectory.endsWith("/")) {
folderInputDirectory += "/";
}
}
// Object factory processing code
private static final Pattern elementDeclPattern = Pattern.compile("\\s*@XmlElementDecl\\(([^\\)]*)\\)");
private static final Pattern namespacePattern = Pattern.compile(".*namespace\\s*=\\s*\"([^\"]*)\".*");
private static final Pattern elementNamePattern = Pattern.compile(".*name\\s*=\\s*\"([^\"]*)\".*");
private static final String pkgDecl = "package ";
private static final String COMMENT = "// This is a file generated by some gorgeous code in Jaxb2Simple.processObjectFactory(File objectFactoryFile) :(";
private static final String IMPORT_NS = "import org.simpleframework.xml.Namespace;";
private static final String IMPORT_ROOT = "import org.simpleframework.xml.Root;";
private static final String ROOT_ANNOT = "@Root(name=\"";
private static final String NS_ANNOT = "@Namespace(reference=\"";
private static final String ANNOT_END = "\")";
private void processObjectFactory(File objectFactoryFile) throws IOException {
HashSet<String> newClasses = new HashSet<String>();
File parentDirectory = objectFactoryFile.getParentFile();
String pkgName = null;
BufferedReader br = new BufferedReader(new FileReader(objectFactoryFile));
while (true) {
String line = br.readLine();
if (line==null)
break;
//getLog().debug("Going to match: '"+line+"'");
if (pkgName==null && line.startsWith(pkgDecl)) {
pkgName = line.substring(pkgDecl.length(),line.length()-1);
getLog().debug("Got package: '"+pkgName+"'");
}
else {
Matcher edm = elementDeclPattern.matcher(line);
if (edm.matches()) {
//getLog().debug("Found XmlElementDecl - parsing namespace and elementName of '"+edm.group(1)+"'");
Matcher nm = namespacePattern.matcher(edm.group(1));
if (nm.matches()) {
Matcher enm = elementNamePattern.matcher(edm.group(1));
if (enm.matches()) {
//getLog().debug("Bulding empty bean for {"+nm.group(1)+"}"+enm.group(1));
String newC = buildEmptySimpleXmlBean(parentDirectory, pkgName, nm.group(1), enm.group(1));
newClasses.add(newC);
}
}
}
}
}
newClassesOnPackage.put(pkgName,newClasses);
br.close();
}
private String buildEmptySimpleXmlBean(File directory, String pkgName,
String namespace, String elementName) throws IOException {
String className = classifyName(elementName);
getLog().debug("Creating empty SimpleXML bean '"+pkgName+"."+className+" for element {'"+namespace+"}"+elementName+" in directory "+directory.getAbsolutePath()+"...");
File newBeanFile = new File(directory, className+".java");
newBeanFile.createNewFile(); // TODO check if className already exists
PrintWriter filePw = new PrintWriter(new FileOutputStream(newBeanFile));
filePw.println(COMMENT);
filePw.println();
filePw.println(pkgDecl+pkgName+";");
filePw.println();
filePw.println(IMPORT_NS);
filePw.println(IMPORT_ROOT);
filePw.println();
filePw.println(NS_ANNOT+namespace+ANNOT_END);
filePw.println(ROOT_ANNOT+elementName+ANNOT_END);
filePw.println("public class "+className+" {");
filePw.println("\tpublic "+className+"() {}");
filePw.println("}");
filePw.flush();
filePw.close();
return className;
}
private static String classifyName(String elementName) {
// TODO properly, using com.sun.codemodel.JCodeModel and so on
String[] parts = elementName.split("-|_");
StringBuilder sb = new StringBuilder();
for (int i=0; i<parts.length; i++) {
sb.append(Character.toUpperCase(parts[i].charAt(0)));
sb.append(parts[i].substring(1));
}
return sb.toString();
}
private void processPackageInfo(File javaFile) throws IOException {
String pkgName = null;
String ns = null;
BufferedReader br = new BufferedReader(new FileReader(javaFile));
while (true) {
String line = br.readLine();
if (line==null)
break;
if (pkgName==null && line.startsWith(pkgDecl)) {
pkgName = line.substring(pkgDecl.length(),line.length()-1);
getLog().debug("Got package: '"+pkgName+"'");
}
if (ns==null) {
Matcher nm = namespacePattern.matcher(line);
if (nm.matches())
ns = nm.group(1);
}
if (pkgName!=null && ns!=null) {
namespaceForPackage.put(pkgName, ns);
return;
}
}
}
}
| true | true | private String findReplacePatterns(StringBuffer schemaContent) {
String newSchemaContent; String textToFind; String textToReplace;
newSchemaContent = schemaContent.toString();
//import javax.xml.bind.annotation.* -> import org.simpleframework.xml.*
//textToFind = "import javax.xml.bind.annotation.*import javax.xml.bind.annotation.\\w*;";
//textToReplace = "import org.simpleframework.xml.*;";
//newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//import javax\.xml\.bind\.annotation\.XmlAccessType/import org.simpleframework.xml.DefaultType
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAccessType;";
textToReplace = "import org.simpleframework.xml.DefaultType;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAccessorType/import org.simpleframework.xml.Default/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAccessorType;\n";
//textToReplace = "import org.simpleframework.xml.Default;";
textToReplace = ""; //PubSub has a class called Default also! Need to refer to xml.default by FQ name
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAttribute;/import org.simpleframework.xml.Attribute;
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAttribute;";
textToReplace = "import org.simpleframework.xml.Attribute;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlElement;/import org.simpleframework.xml.Element;/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlElement;";
textToReplace = "import org.simpleframework.xml.Element;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlType;/import org.simpleframework.xml.Element;\nimport org.simpleframework.xml.Order;/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlType;";
textToReplace = "import org.simpleframework.xml.Order;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlRootElement/import org.simpleframework.xml.Root/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlRootElement;";
textToReplace = "import org.simpleframework.xml.Root;\nimport org.simpleframework.xml.Namespace;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlValue/import org.simpleframework.xml.Text
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlValue;";
textToReplace = "import org.simpleframework.xml.Text;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlElements/import org.simpleframework.xml.ElementList
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlElements;";
textToReplace = "import org.simpleframework.xml.ElementList;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter -> import org.simpleframework.xml.convert.Convert;
textToFind = "import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;";
textToReplace = "import org.simpleframework.xml.convert.Convert;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import org.w3._2001.xmlschema.Adapter1; -> import org.societies.maven.converters.URIConverter;
textToFind = "import org.w3._2001.xmlschema.Adapter1;";
textToReplace = "import org.societies.maven.converters.URIConverter;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -> import org.societies.maven.converters.CollapsedStringAdapter;
textToFind = "import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;";
textToReplace = "import org.societies.maven.converters.CollapsedStringAdapter;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlJavaTypeAdapter(Adapter1 .class) -> @Convert(URIConverter.class)
textToFind = "@XmlJavaTypeAdapter\\(Adapter1.*\\.class?\\)";
textToReplace = "@Convert(URIConverter.class)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlJavaTypeAdapter(CollapsedStringAdapter.class) -> @Convert(CollapsedStringAdapter.class)
textToFind = "@XmlJavaTypeAdapter\\(CollapsedStringAdapter.class?\\)";
textToReplace = "@Convert(CollapsedStringAdapter.class)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//REMOVE namespace FROM XmlElement ANNOTATION @XmlElement(namespace = "jabber:x:data")
//s/\(@XmlElement(name = ".*"\), namespace\( = ".*"\))/\1, required = false)\n @Namespace(reference\2)/
textToFind = "(@XmlElement\\(.*)namespace( = \".*\")\\)";
textToReplace = "$1required = false)\n @Namespace(reference$2)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(name = "Activity", namespace = "http://societies.org/api/schema/activity", required = true)
textToFind = "(@XmlElement\\(.*)namespace( = \".*\"),(.*)\\)";
textToReplace = "$1$3)\n @Namespace(reference$2)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlElement with List -> @XmlElementList @XmlElement(nillable = true) -> @ElementList(inline=true, entry="Service")
// @XmlElement(name[ ]*=\(.*\)).*\(\n.*List\<.*\>.*;\)/@ElementList(inline=true, entry=\1)\2/
textToFind = "@XmlElement\\(.*?\\)(\n.*?List\\<(.*?)\\>.*?;)";
//textToReplace = "@ElementList(inline=true, entry=\"$2\")$1";
textToReplace = "$1";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//@XmlElement -> @Element
//1) if "required = true|false" is missing then add "required=false" else do nothing
//2) remove nillable=true|false
//@XmlElement(required = true, type = Integer.class, nillable = true)
//textToFind = "(@XmlElement\\(.*)nillable = true|false\\)";
textToFind = ", nillable = (true|false)";
textToReplace = ""; //"$1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(required = true, type = Integer.class, nillable = true)
textToFind = "@XmlElement\\(nillable = true\\)";
textToReplace = "@Element(required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(\(.*required.*\))/@Element(\1)/ @XmlElement(required = true)
//textToFind = "@XmlElement(\\(.*required.*\\))";
textToFind = "@XmlElement\\((.*required.*?)\\)";
textToReplace = "@Element($1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(\(.*\))/@Element(required=false,\1)/
textToFind = "@XmlElement\\((.*?)\\)";
textToReplace = "@Element($1, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//NAMESPACE
Pattern patternNS = Pattern.compile("package (.*);", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
Matcher matcherNS = patternNS.matcher(newSchemaContent);
String ns = "";
if (matcherNS.find()) {
String pkgTmp = matcherNS.group();
String pkgFinal = pkgTmp.substring(8, pkgTmp.indexOf(";"));
// String[] nsArr = pkgFinal.split("\\.");
// ns = "@Namespace(reference=\"http://" + nsArr[1] + "." + nsArr[0];
// for(int i=2; i<nsArr.length; i++)
// ns+="/" + nsArr[i];
// ns += "\")\n";
ns = "@Namespace(reference=\""+namespaceForPackage.get(pkgFinal)+"\")\n"; // fix for non-default namespaces (eg pubsub#event) issue
}
// @XmlRootElement -> @Root + @Namespace(reference="http://...)
// s/@XmlRootElement(\(.*\))/@Root(\1, strict=false)/
//textToFind = "@XmlRootElement(\\(.*)\\)\n";
textToFind = "@XmlRootElement(\\(.*?)\\)\n";
textToReplace = "@Root$1, strict=false)\n" + ns;
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlType(.*propOrder[ ]*\(=.*\)/@Order(elements\1/
// textToFind = "@XmlType\\(.*propOrder";
// textToReplace = "@Order(elements";
// newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// TODO discarding element order information instead of placing @Order annotations
textToFind = "@XmlType\\([^\\)]*\\)";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\)[ ]*,[ ]*propOrder[ ]*\(=.*\)/@Default(DefaultType.\1)\n@Order(elements\3/
textToFind = "@XmlAccessorType\\(XmlAccessType.FIELD\\)";
textToReplace = "@org.simpleframework.xml.Default(value=DefaultType.FIELD, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\))/@Default(DefaultType.\1)\n@Root(\2, strict=false
//Pattern patternAccessor1 = Pattern.compile("@XmlAccessorType([ ]*XmlAccessType\\.\\(.*\\))\\n@XmlType(\\(.*\\))", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//Matcher matcherAccessor1 = patternAccessor1.matcher(newSchemaContent);
//newSchemaContent = matcherAccessor1.replaceAll("@Default(DefaultType.$1)\n@Root($2, strict=false");
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\)[ ]*,[ ]*propOrder[ ]*\(=.*\)/@Default(DefaultType.\1)\n@Order(elements\3/
//Pattern patternAccessor2 = Pattern.compile("@XmlAccessorType([ ]*XmlAccessType\\.\\(.*\\))\\n@XmlType(\\(.*\\)[ ]*,[ ]*propOrder[ ]*\\(=.*\\)", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//Matcher matcherAccessor2 = patternAccessor2.matcher(newSchemaContent);
//newSchemaContent = matcherAccessor.replaceAll("@Default(DefaultType.$1)\n@Order(elements$3");
// @XmlAttribute -> @Attribute
//if "required = true|false" is missing then add "required=false" else do nothing
textToFind = "@XmlAttribute\\((.*, required = true|false)\\)";
textToReplace = "@Attribute($1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//ADD required=false IF MISSING
textToFind = "@XmlAttribute\\((.*?(?!required = true|false))\\)";
textToReplace = "@Attribute($1, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlAttribute/@Attribute(required=false)/
textToFind = "@XmlAttribute\n";
textToReplace = "@Attribute(required=false)\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlValue -> @Text
textToFind = "@XmlValue";
textToReplace = "@Text(required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//REMOVE @XmlSchemaType(name = "anyURI")
textToFind = "@XmlSchemaType\\(name = \".*\"\\)\n ";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//ENUMERATOR FILE - REMOVE ALL ANNOTATIONS
textToFind = "@XmlEnum.*?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlType(name = "methodType")
textToFind = "@XmlType\\(name = \".*?\"\\)?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlSeeAlso/,/})
textToFind = "@XmlSeeAlso.*?}\\)\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
// @XmlAnyElement.*
textToFind = "@XmlAnyElement.*?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAnyElement;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAnyElement;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAnyAttribute;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAnyAttribute;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlSeeAlso;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlSeeAlso;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlSchemaType;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlSchemaType;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlEnum;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlEnum;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlEnumValue;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlEnumValue;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// /@XmlSchemaType.*/d
// /@XmlAnyAttribute.*/d
return newSchemaContent;
}
| private String findReplacePatterns(StringBuffer schemaContent) {
String newSchemaContent; String textToFind; String textToReplace;
newSchemaContent = schemaContent.toString();
//import javax.xml.bind.annotation.* -> import org.simpleframework.xml.*
//textToFind = "import javax.xml.bind.annotation.*import javax.xml.bind.annotation.\\w*;";
//textToReplace = "import org.simpleframework.xml.*;";
//newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//import javax\.xml\.bind\.annotation\.XmlAccessType/import org.simpleframework.xml.DefaultType
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAccessType;";
textToReplace = "import org.simpleframework.xml.DefaultType;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAccessorType/import org.simpleframework.xml.Default/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAccessorType;\n";
//textToReplace = "import org.simpleframework.xml.Default;";
textToReplace = ""; //PubSub has a class called Default also! Need to refer to xml.default by FQ name
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAttribute;/import org.simpleframework.xml.Attribute;
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAttribute;";
textToReplace = "import org.simpleframework.xml.Attribute;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlElement;/import org.simpleframework.xml.Element;/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlElement;";
textToReplace = "import org.simpleframework.xml.Element;\nimport org.simpleframework.xml.Namespace;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlType;/import org.simpleframework.xml.Element;\nimport org.simpleframework.xml.Order;/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlType;";
textToReplace = "import org.simpleframework.xml.Order;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlRootElement/import org.simpleframework.xml.Root/
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlRootElement;";
textToReplace = "import org.simpleframework.xml.Root;\nimport org.simpleframework.xml.Namespace;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlValue/import org.simpleframework.xml.Text
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlValue;";
textToReplace = "import org.simpleframework.xml.Text;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlElements/import org.simpleframework.xml.ElementList
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlElements;";
textToReplace = "import org.simpleframework.xml.ElementList;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter -> import org.simpleframework.xml.convert.Convert;
textToFind = "import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;";
textToReplace = "import org.simpleframework.xml.convert.Convert;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import org.w3._2001.xmlschema.Adapter1; -> import org.societies.maven.converters.URIConverter;
textToFind = "import org.w3._2001.xmlschema.Adapter1;";
textToReplace = "import org.societies.maven.converters.URIConverter;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; -> import org.societies.maven.converters.CollapsedStringAdapter;
textToFind = "import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;";
textToReplace = "import org.societies.maven.converters.CollapsedStringAdapter;";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlJavaTypeAdapter(Adapter1 .class) -> @Convert(URIConverter.class)
textToFind = "@XmlJavaTypeAdapter\\(Adapter1.*\\.class?\\)";
textToReplace = "@Convert(URIConverter.class)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlJavaTypeAdapter(CollapsedStringAdapter.class) -> @Convert(CollapsedStringAdapter.class)
textToFind = "@XmlJavaTypeAdapter\\(CollapsedStringAdapter.class?\\)";
textToReplace = "@Convert(CollapsedStringAdapter.class)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//REMOVE namespace FROM XmlElement ANNOTATION @XmlElement(namespace = "jabber:x:data")
//s/\(@XmlElement(name = ".*"\), namespace\( = ".*"\))/\1, required = false)\n @Namespace(reference\2)/
textToFind = "(@XmlElement\\(.*)namespace( = \".*\")\\)";
textToReplace = "$1required = false)\n @Namespace(reference$2)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(name = "Activity", namespace = "http://societies.org/api/schema/activity", required = true)
textToFind = "(@XmlElement\\(.*)namespace( = \".*\"),(.*)\\)";
textToReplace = "$1$3)\n @Namespace(reference$2)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlElement with List -> @XmlElementList @XmlElement(nillable = true) -> @ElementList(inline=true, entry="Service")
// @XmlElement(name[ ]*=\(.*\)).*\(\n.*List\<.*\>.*;\)/@ElementList(inline=true, entry=\1)\2/
textToFind = "@XmlElement\\(.*?\\)(\n.*?List\\<(.*?)\\>.*?;)";
//textToReplace = "@ElementList(inline=true, entry=\"$2\")$1";
textToReplace = "$1";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//@XmlElement -> @Element
//1) if "required = true|false" is missing then add "required=false" else do nothing
//2) remove nillable=true|false
//@XmlElement(required = true, type = Integer.class, nillable = true)
//textToFind = "(@XmlElement\\(.*)nillable = true|false\\)";
textToFind = ", nillable = (true|false)";
textToReplace = ""; //"$1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(required = true, type = Integer.class, nillable = true)
textToFind = "@XmlElement\\(nillable = true\\)";
textToReplace = "@Element(required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(\(.*required.*\))/@Element(\1)/ @XmlElement(required = true)
//textToFind = "@XmlElement(\\(.*required.*\\))";
textToFind = "@XmlElement\\((.*required.*?)\\)";
textToReplace = "@Element($1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlElement(\(.*\))/@Element(required=false,\1)/
textToFind = "@XmlElement\\((.*?)\\)";
textToReplace = "@Element($1, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//NAMESPACE
Pattern patternNS = Pattern.compile("package (.*);", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
Matcher matcherNS = patternNS.matcher(newSchemaContent);
String ns = "";
if (matcherNS.find()) {
String pkgTmp = matcherNS.group();
String pkgFinal = pkgTmp.substring(8, pkgTmp.indexOf(";"));
// String[] nsArr = pkgFinal.split("\\.");
// ns = "@Namespace(reference=\"http://" + nsArr[1] + "." + nsArr[0];
// for(int i=2; i<nsArr.length; i++)
// ns+="/" + nsArr[i];
// ns += "\")\n";
ns = "@Namespace(reference=\""+namespaceForPackage.get(pkgFinal)+"\")\n"; // fix for non-default namespaces (eg pubsub#event) issue
}
// @XmlRootElement -> @Root + @Namespace(reference="http://...)
// s/@XmlRootElement(\(.*\))/@Root(\1, strict=false)/
//textToFind = "@XmlRootElement(\\(.*)\\)\n";
textToFind = "@XmlRootElement(\\(.*?)\\)\n";
textToReplace = "@Root$1, strict=false)\n" + ns;
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlType(.*propOrder[ ]*\(=.*\)/@Order(elements\1/
// textToFind = "@XmlType\\(.*propOrder";
// textToReplace = "@Order(elements";
// newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// TODO discarding element order information instead of placing @Order annotations
textToFind = "@XmlType\\([^\\)]*\\)";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\)[ ]*,[ ]*propOrder[ ]*\(=.*\)/@Default(DefaultType.\1)\n@Order(elements\3/
textToFind = "@XmlAccessorType\\(XmlAccessType.FIELD\\)";
textToReplace = "@org.simpleframework.xml.Default(value=DefaultType.FIELD, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\))/@Default(DefaultType.\1)\n@Root(\2, strict=false
//Pattern patternAccessor1 = Pattern.compile("@XmlAccessorType([ ]*XmlAccessType\\.\\(.*\\))\\n@XmlType(\\(.*\\))", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//Matcher matcherAccessor1 = patternAccessor1.matcher(newSchemaContent);
//newSchemaContent = matcherAccessor1.replaceAll("@Default(DefaultType.$1)\n@Root($2, strict=false");
// @XmlAccessorType([ ]*XmlAccessType\.\(.*\))\n@XmlType(\(.*\)[ ]*,[ ]*propOrder[ ]*\(=.*\)/@Default(DefaultType.\1)\n@Order(elements\3/
//Pattern patternAccessor2 = Pattern.compile("@XmlAccessorType([ ]*XmlAccessType\\.\\(.*\\))\\n@XmlType(\\(.*\\)[ ]*,[ ]*propOrder[ ]*\\(=.*\\)", Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
//Matcher matcherAccessor2 = patternAccessor2.matcher(newSchemaContent);
//newSchemaContent = matcherAccessor.replaceAll("@Default(DefaultType.$1)\n@Order(elements$3");
// @XmlAttribute -> @Attribute
//if "required = true|false" is missing then add "required=false" else do nothing
textToFind = "@XmlAttribute\\((.*, required = true|false)\\)";
textToReplace = "@Attribute($1)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//ADD required=false IF MISSING
textToFind = "@XmlAttribute\\((.*?(?!required = true|false))\\)";
textToReplace = "@Attribute($1, required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlAttribute/@Attribute(required=false)/
textToFind = "@XmlAttribute\n";
textToReplace = "@Attribute(required=false)\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlValue -> @Text
textToFind = "@XmlValue";
textToReplace = "@Text(required=false)";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//REMOVE @XmlSchemaType(name = "anyURI")
textToFind = "@XmlSchemaType\\(name = \".*\"\\)\n ";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//ENUMERATOR FILE - REMOVE ALL ANNOTATIONS
textToFind = "@XmlEnum.*?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlType(name = "methodType")
textToFind = "@XmlType\\(name = \".*?\"\\)?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//@XmlSeeAlso/,/})
textToFind = "@XmlSeeAlso.*?}\\)\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace, Pattern.DOTALL|Pattern.CASE_INSENSITIVE);
// @XmlAnyElement.*
textToFind = "@XmlAnyElement.*?\n";
textToReplace = "";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAnyElement;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAnyElement;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlAnyAttribute;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlAnyAttribute;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlSeeAlso;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlSeeAlso;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlSchemaType;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlSchemaType;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlEnum;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlEnum;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
//import javax\.xml\.bind\.annotation\.XmlEnumValue;/d
textToFind = "import javax\\.xml\\.bind\\.annotation\\.XmlEnumValue;";
textToReplace = "\n";
newSchemaContent = findReplacePattern(newSchemaContent, textToFind, textToReplace);
// /@XmlSchemaType.*/d
// /@XmlAnyAttribute.*/d
return newSchemaContent;
}
|
diff --git a/src/objects/Goal.java b/src/objects/Goal.java
index 2822026..786458a 100755
--- a/src/objects/Goal.java
+++ b/src/objects/Goal.java
@@ -1,54 +1,54 @@
package objects;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.particles.ConfigurableEmitter;
public class Goal extends GameObject {
public static final float scale = 0.15f;
private ConfigurableEmitter emitter;
private Image goal;
public Goal(Shape s, Color c){
super(s, c);
try {
- goal = new Image("data/redspiral.png");
+ goal = new Image("data/image/redspiral.png");
} catch (SlickException e) {
e.printStackTrace();
}
this.flag.add(OBJECT_FLAG_MAPONLY);
this.flag.add(OBJECT_FLAG_GHOST);
this.flag.add(OBJECT_FLAG_GOAL);
}
public void onInit(Room r){
emitter = new ConfigurableEmitter("data/test_emitter.xml");
emitter.setPosition(x, y);
r.particleSystem.addEmitter(emitter);
System.out.println("Particle system");
}
public void onRender(Graphics g){
this.shape.setCenterX(this.x);
this.shape.setCenterY(this.y);
goal.draw(x-goal.getWidth()/2*scale,y-goal.getHeight()/2*scale,scale);
goal.rotate(5);
}
public void setX(float x) {
this.x = x;
emitter.setPosition(x, y);
}
public void setY(float y) {
this.y = y;
emitter.setPosition(x, y);
}
}
| true | true | public Goal(Shape s, Color c){
super(s, c);
try {
goal = new Image("data/redspiral.png");
} catch (SlickException e) {
e.printStackTrace();
}
this.flag.add(OBJECT_FLAG_MAPONLY);
this.flag.add(OBJECT_FLAG_GHOST);
this.flag.add(OBJECT_FLAG_GOAL);
}
| public Goal(Shape s, Color c){
super(s, c);
try {
goal = new Image("data/image/redspiral.png");
} catch (SlickException e) {
e.printStackTrace();
}
this.flag.add(OBJECT_FLAG_MAPONLY);
this.flag.add(OBJECT_FLAG_GHOST);
this.flag.add(OBJECT_FLAG_GOAL);
}
|
diff --git a/src/ar/com/stomalab/souyaban/model/EscenarioLoader.java b/src/ar/com/stomalab/souyaban/model/EscenarioLoader.java
index a1a7830..cb32b76 100644
--- a/src/ar/com/stomalab/souyaban/model/EscenarioLoader.java
+++ b/src/ar/com/stomalab/souyaban/model/EscenarioLoader.java
@@ -1,162 +1,162 @@
package ar.com.stomalab.souyaban.model;
import java.util.ArrayList;
public class EscenarioLoader {
public EscenarioLoader(){}
public Escenario cargarEscenario(ArrayList<String> lineas){
Escenario escenario = new Escenario();
int fila = 0;
for (String linea : lineas){
- for (int columna = 0; columna < linea.length(); columna++){
- char c = linea.charAt(columna);
+ fila++;
+ for (int columna = 1; columna <= linea.length(); columna++){
+ char c = linea.charAt(columna - 1);
switch (c){
case '#':
{
Pared pared = new Pared();
pared.setPosicion(columna, fila);
escenario.agregarPared(pared);
break;
}
case '.':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
break;
}
case '$':
{
Caja caja = new Caja();
caja.setPosicion(columna, fila);
escenario.agregarCaja(caja);
break;
}
case '@':
{
Persona persona = new Persona();
persona.setPosicion(columna, fila);
escenario.agregarPersona(persona);
break;
}
case '*':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
Caja caja = new Caja();
caja.setPosicion(columna, fila);
escenario.agregarCaja(caja);
break;
}
case '+':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
Persona persona = new Persona();
persona.setPosicion(columna, fila);
escenario.agregarPersona(persona);
break;
}
}
}
- fila++;
}
return escenario;
}
/*
def cargar_escenario lineas
escenario = Escenario.new
fila = 0
min_fila = 1000000
min_col = 1000000
lineas.each do |linea|
linea = strip_comentarios linea
if !linea_en_blanco?(linea)
fila = fila + 1
(1..linea.length).each do |columna|
# puts linea[columna - 1]
case linea[columna - 1]
when '#'
pared = Pared.new
pared.set_posicion(columna, fila)
escenario.agregar_pared(pared)
min_col = columna if columna < min_col
min_fila = fila if fila < min_fila
when '.'
target = Destino.new
target.set_posicion(columna, fila)
escenario.agregar_destino(target)
min_col = columna if columna < min_col
min_fila = fila if fila < min_fila
when '$'
caja = Caja.new
caja.set_posicion(columna, fila)
caja.set_escenario(escenario)
escenario.agregar_caja(caja)
min_col = columna if columna < min_col
min_fila = fila if fila < min_fila
when '@'
persona = Persona.new
persona.set_posicion(columna, fila)
persona.set_escenario(escenario)
escenario.agregar_persona(persona)
min_col = columna if columna < min_col
min_fila = fila if fila < min_fila
when '*'
target = Destino.new
target.set_posicion(columna, fila)
escenario.agregar_destino(target)
caja = Caja.new
caja.set_posicion(columna, fila)
caja.set_escenario(escenario)
escenario.agregar_caja(caja)
min_col = columna if columna < min_col
min_fila = fila if fila < min_fila
when '+'
target = Destino.new
target.set_posicion(columna, fila)
escenario.agregar_destino(target)
persona = Persona.new
persona.set_posicion(columna, fila)
persona.set_escenario(escenario)
escenario.agregar_persona(persona)
min_col = columna if columna < min_col
min_fila = fila if fila < min_fila
end
end
end
end
shift_escenario escenario, min_fila, min_col
escenario
end
private
def linea_en_blanco? linea
(linea.strip).empty?
end
def strip_comentarios linea
linea = linea.split(';')[0]
linea
end
*/
}
| false | true | public Escenario cargarEscenario(ArrayList<String> lineas){
Escenario escenario = new Escenario();
int fila = 0;
for (String linea : lineas){
for (int columna = 0; columna < linea.length(); columna++){
char c = linea.charAt(columna);
switch (c){
case '#':
{
Pared pared = new Pared();
pared.setPosicion(columna, fila);
escenario.agregarPared(pared);
break;
}
case '.':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
break;
}
case '$':
{
Caja caja = new Caja();
caja.setPosicion(columna, fila);
escenario.agregarCaja(caja);
break;
}
case '@':
{
Persona persona = new Persona();
persona.setPosicion(columna, fila);
escenario.agregarPersona(persona);
break;
}
case '*':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
Caja caja = new Caja();
caja.setPosicion(columna, fila);
escenario.agregarCaja(caja);
break;
}
case '+':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
Persona persona = new Persona();
persona.setPosicion(columna, fila);
escenario.agregarPersona(persona);
break;
}
}
}
fila++;
}
return escenario;
}
| public Escenario cargarEscenario(ArrayList<String> lineas){
Escenario escenario = new Escenario();
int fila = 0;
for (String linea : lineas){
fila++;
for (int columna = 1; columna <= linea.length(); columna++){
char c = linea.charAt(columna - 1);
switch (c){
case '#':
{
Pared pared = new Pared();
pared.setPosicion(columna, fila);
escenario.agregarPared(pared);
break;
}
case '.':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
break;
}
case '$':
{
Caja caja = new Caja();
caja.setPosicion(columna, fila);
escenario.agregarCaja(caja);
break;
}
case '@':
{
Persona persona = new Persona();
persona.setPosicion(columna, fila);
escenario.agregarPersona(persona);
break;
}
case '*':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
Caja caja = new Caja();
caja.setPosicion(columna, fila);
escenario.agregarCaja(caja);
break;
}
case '+':
{
Destino destino = new Destino();
destino.setPosicion(columna, fila);
escenario.agregarDestino(destino);
Persona persona = new Persona();
persona.setPosicion(columna, fila);
escenario.agregarPersona(persona);
break;
}
}
}
}
return escenario;
}
|
diff --git a/src/share/classes/com/sun/tools/javafx/antlr/JavafxSyntacticAnalysis.java b/src/share/classes/com/sun/tools/javafx/antlr/JavafxSyntacticAnalysis.java
index 23f5db2cf..5415ba223 100644
--- a/src/share/classes/com/sun/tools/javafx/antlr/JavafxSyntacticAnalysis.java
+++ b/src/share/classes/com/sun/tools/javafx/antlr/JavafxSyntacticAnalysis.java
@@ -1,115 +1,115 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.sun.tools.javafx.antlr;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javafx.tree.JFXUnit;
/**
*
* @author Robert Field
*/
public class JavafxSyntacticAnalysis {
/** The context key for the parser. */
protected static final Context.Key<JavafxSyntacticAnalysis> syntaxKey =
new Context.Key<JavafxSyntacticAnalysis>();
protected Context context;
/** Command line options
*/
protected Options options;
/** The name table.
*/
protected Name.Table names;
/** The log to be used for error reporting.
*/
public Log log;
public static JavafxSyntacticAnalysis instance(Context context) {
JavafxSyntacticAnalysis instance = context.get(syntaxKey);
if (instance == null)
instance = new JavafxSyntacticAnalysis(context);
return instance;
}
protected JavafxSyntacticAnalysis(final Context context) {
this.context = context;
context.put(syntaxKey, this);
names = Name.Table.instance(context);
options = Options.instance(context);
log = Log.instance(context);
}
public JFXUnit parse(CharSequence content, String fileName) {
JFXUnit unit = null;
String parserChoice = options.get("parser");
if (parserChoice == null) {
parserChoice = "v3"; // default
}
{
try {
// Create input stream from standard input
ANTLRStringStream input = new ANTLRStringStream(content.toString());
// Create a lexer attached to that input stream
v3Lexer lexer = new v3Lexer(context, input);
// Create a stream of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Create a parser attached to the token stream
v3Parser parser = new v3Parser(tokens);
// Set the context
parser.initialize(context);
- // Invoke the module rule in get return value
- v3Parser.module_return comReturn = parser.module();
+ // Invoke the script rule in get return value
+ v3Parser.script_return comReturn = parser.script();
CommonTree comTree = (CommonTree) comReturn.getTree();
// System.out.println(comTree.toStringTree());
if ( (System.getenv("NETBEAN_EDITOR") != null) ||
(errorCount() == 0) ) {
// Walk resulting tree; create treenode stream first
CommonTreeNodeStream nodes = new CommonTreeNodeStream(comTree);
// AST nodes have payloads that point into token stream
nodes.setTokenStream(tokens);
// Create a tree Walker attached to the nodes stream
v3Walker walker = new v3Walker(nodes);
// Set the context
walker.initialize(context);
- // Invoke the start symbol, rule module
- unit = walker.module();
+ // Invoke the start symbol, rule script
+ unit = walker.script();
}
String treeChoice = options.get("tree");
if (treeChoice != null) {
printTree(comTree, "---");
}
} catch (Throwable thr) {
System.err.println("Error in syntactic analysis in " + fileName + ":");
thr.printStackTrace(System.err);
}
}
return unit;
}
/** The number of errors reported so far.
*/
public int errorCount() {
return log.nerrors;
}
private void printTree(Tree tree, String prefix) {
CommonToken token = (CommonToken)((CommonTree)tree).getToken();
System.out.println(prefix + tree + " (" + token.getStartIndex() + ")" + token.getLine());
int n = tree.getChildCount();
String nextPrefix = prefix + " ";
for (int i = 0; i < n; ++i) {
printTree(tree.getChild(i), nextPrefix);
}
}
}
| false | true | public JFXUnit parse(CharSequence content, String fileName) {
JFXUnit unit = null;
String parserChoice = options.get("parser");
if (parserChoice == null) {
parserChoice = "v3"; // default
}
{
try {
// Create input stream from standard input
ANTLRStringStream input = new ANTLRStringStream(content.toString());
// Create a lexer attached to that input stream
v3Lexer lexer = new v3Lexer(context, input);
// Create a stream of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Create a parser attached to the token stream
v3Parser parser = new v3Parser(tokens);
// Set the context
parser.initialize(context);
// Invoke the module rule in get return value
v3Parser.module_return comReturn = parser.module();
CommonTree comTree = (CommonTree) comReturn.getTree();
// System.out.println(comTree.toStringTree());
if ( (System.getenv("NETBEAN_EDITOR") != null) ||
(errorCount() == 0) ) {
// Walk resulting tree; create treenode stream first
CommonTreeNodeStream nodes = new CommonTreeNodeStream(comTree);
// AST nodes have payloads that point into token stream
nodes.setTokenStream(tokens);
// Create a tree Walker attached to the nodes stream
v3Walker walker = new v3Walker(nodes);
// Set the context
walker.initialize(context);
// Invoke the start symbol, rule module
unit = walker.module();
}
String treeChoice = options.get("tree");
if (treeChoice != null) {
printTree(comTree, "---");
}
} catch (Throwable thr) {
System.err.println("Error in syntactic analysis in " + fileName + ":");
thr.printStackTrace(System.err);
}
}
return unit;
}
| public JFXUnit parse(CharSequence content, String fileName) {
JFXUnit unit = null;
String parserChoice = options.get("parser");
if (parserChoice == null) {
parserChoice = "v3"; // default
}
{
try {
// Create input stream from standard input
ANTLRStringStream input = new ANTLRStringStream(content.toString());
// Create a lexer attached to that input stream
v3Lexer lexer = new v3Lexer(context, input);
// Create a stream of tokens pulled from the lexer
CommonTokenStream tokens = new CommonTokenStream(lexer);
// Create a parser attached to the token stream
v3Parser parser = new v3Parser(tokens);
// Set the context
parser.initialize(context);
// Invoke the script rule in get return value
v3Parser.script_return comReturn = parser.script();
CommonTree comTree = (CommonTree) comReturn.getTree();
// System.out.println(comTree.toStringTree());
if ( (System.getenv("NETBEAN_EDITOR") != null) ||
(errorCount() == 0) ) {
// Walk resulting tree; create treenode stream first
CommonTreeNodeStream nodes = new CommonTreeNodeStream(comTree);
// AST nodes have payloads that point into token stream
nodes.setTokenStream(tokens);
// Create a tree Walker attached to the nodes stream
v3Walker walker = new v3Walker(nodes);
// Set the context
walker.initialize(context);
// Invoke the start symbol, rule script
unit = walker.script();
}
String treeChoice = options.get("tree");
if (treeChoice != null) {
printTree(comTree, "---");
}
} catch (Throwable thr) {
System.err.println("Error in syntactic analysis in " + fileName + ":");
thr.printStackTrace(System.err);
}
}
return unit;
}
|
diff --git a/src/main/java/com/gitblit/authority/GitblitAuthority.java b/src/main/java/com/gitblit/authority/GitblitAuthority.java
index 1a1f96db..1c0c142f 100644
--- a/src/main/java/com/gitblit/authority/GitblitAuthority.java
+++ b/src/main/java/com/gitblit/authority/GitblitAuthority.java
@@ -1,921 +1,921 @@
/*
* Copyright 2012 gitblit.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 com.gitblit.authority;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URI;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.swing.ImageIcon;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.RowFilter;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.slf4j.LoggerFactory;
import com.gitblit.ConfigUserService;
import com.gitblit.Constants;
import com.gitblit.FileSettings;
import com.gitblit.IStoredSettings;
import com.gitblit.IUserService;
import com.gitblit.Keys;
import com.gitblit.MailExecutor;
import com.gitblit.client.HeaderPanel;
import com.gitblit.client.Translation;
import com.gitblit.models.UserModel;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.FileUtils;
import com.gitblit.utils.StringUtils;
import com.gitblit.utils.TimeUtils;
import com.gitblit.utils.X509Utils;
import com.gitblit.utils.X509Utils.RevocationReason;
import com.gitblit.utils.X509Utils.X509Log;
import com.gitblit.utils.X509Utils.X509Metadata;
/**
* Simple GUI tool for administering Gitblit client certificates.
*
* @author James Moger
*
*/
public class GitblitAuthority extends JFrame implements X509Log {
private static final long serialVersionUID = 1L;
private final UserCertificateTableModel tableModel;
private UserCertificatePanel userCertificatePanel;
private File folder;
private IStoredSettings gitblitSettings;
private IUserService userService;
private String caKeystorePassword;
private JTable table;
private int defaultDuration;
private TableRowSorter<UserCertificateTableModel> defaultSorter;
private MailExecutor mail;
private JButton certificateDefaultsButton;
private JButton newSSLCertificate;
public static void main(String... args) {
// filter out the baseFolder parameter
String folder = "data";
for (int i = 0; i< args.length; i++) {
String arg = args[i];
if (arg.equals("--baseFolder")) {
if (i + 1 == args.length) {
System.out.println("Invalid --baseFolder parameter!");
System.exit(-1);
} else if (args[i + 1] != ".") {
folder = args[i+1];
}
break;
}
}
final String baseFolder = folder;
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
GitblitAuthority authority = new GitblitAuthority();
authority.initialize(baseFolder);
authority.setLocationRelativeTo(null);
authority.setVisible(true);
}
});
}
public GitblitAuthority() {
super();
tableModel = new UserCertificateTableModel();
defaultSorter = new TableRowSorter<UserCertificateTableModel>(tableModel);
}
public void initialize(String baseFolder) {
setIconImage(new ImageIcon(getClass().getResource("/gitblt-favicon.png")).getImage());
setTitle("Gitblit Certificate Authority v" + Constants.getVersion() + " (" + Constants.getBuildDate() + ")");
setContentPane(getUI());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
saveSizeAndPosition();
}
@Override
public void windowOpened(WindowEvent event) {
}
});
File folder = new File(baseFolder).getAbsoluteFile();
load(folder);
setSizeAndPosition();
}
private void setSizeAndPosition() {
String sz = null;
String pos = null;
try {
StoredConfig config = getConfig();
sz = config.getString("ui", null, "size");
pos = config.getString("ui", null, "position");
defaultDuration = config.getInt("new", "duration", 365);
} catch (Throwable t) {
t.printStackTrace();
}
// try to restore saved window size
if (StringUtils.isEmpty(sz)) {
setSize(900, 600);
} else {
String[] chunks = sz.split("x");
int width = Integer.parseInt(chunks[0]);
int height = Integer.parseInt(chunks[1]);
setSize(width, height);
}
// try to restore saved window position
if (StringUtils.isEmpty(pos)) {
setLocationRelativeTo(null);
} else {
String[] chunks = pos.split(",");
int x = Integer.parseInt(chunks[0]);
int y = Integer.parseInt(chunks[1]);
setLocation(x, y);
}
}
private void saveSizeAndPosition() {
try {
// save window size and position
StoredConfig config = getConfig();
Dimension sz = GitblitAuthority.this.getSize();
config.setString("ui", null, "size",
MessageFormat.format("{0,number,0}x{1,number,0}", sz.width, sz.height));
Point pos = GitblitAuthority.this.getLocationOnScreen();
config.setString("ui", null, "position",
MessageFormat.format("{0,number,0},{1,number,0}", pos.x, pos.y));
config.save();
} catch (Throwable t) {
Utils.showException(GitblitAuthority.this, t);
}
}
private StoredConfig getConfig() throws IOException, ConfigInvalidException {
File configFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(configFile, FS.detect());
config.load();
return config;
}
private IUserService loadUsers(File folder) {
File file = new File(folder, "gitblit.properties");
if (!file.exists()) {
return null;
}
gitblitSettings = new FileSettings(file.getAbsolutePath());
mail = new MailExecutor(gitblitSettings);
String us = gitblitSettings.getString(Keys.realm.userService, "${baseFolder}/users.conf");
String ext = us.substring(us.lastIndexOf(".") + 1).toLowerCase();
IUserService service = null;
if (!ext.equals("conf") && !ext.equals("properties")) {
if (us.equals("com.gitblit.LdapUserService")) {
us = gitblitSettings.getString(Keys.realm.ldap.backingUserService, "${baseFolder}/users.conf");
} else if (us.equals("com.gitblit.LdapUserService")) {
us = gitblitSettings.getString(Keys.realm.redmine.backingUserService, "${baseFolder}/users.conf");
}
}
if (us.endsWith(".conf")) {
service = new ConfigUserService(FileUtils.resolveParameter(Constants.baseFolder$, folder, us));
} else {
throw new RuntimeException("Unsupported user service: " + us);
}
service = new ConfigUserService(FileUtils.resolveParameter(Constants.baseFolder$, folder, us));
return service;
}
private void load(File folder) {
this.folder = folder;
this.userService = loadUsers(folder);
System.out.println(Constants.baseFolder$ + " set to " + folder);
if (userService == null) {
JOptionPane.showMessageDialog(this, MessageFormat.format("Sorry, {0} doesn't look like a Gitblit GO installation.", folder));
} else {
// build empty certificate model for all users
Map<String, UserCertificateModel> map = new HashMap<String, UserCertificateModel>();
for (String user : userService.getAllUsernames()) {
UserModel model = userService.getUserModel(user);
UserCertificateModel ucm = new UserCertificateModel(model);
map.put(user, ucm);
}
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
if (certificatesConfigFile.exists()) {
try {
config.load();
// replace user certificate model with actual data
List<UserCertificateModel> list = UserCertificateConfig.KEY.parse(config).list;
for (UserCertificateModel ucm : list) {
ucm.user = userService.getUserModel(ucm.user.username);
map.put(ucm.user.username, ucm);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ConfigInvalidException e) {
e.printStackTrace();
}
}
tableModel.list = new ArrayList<UserCertificateModel>(map.values());
Collections.sort(tableModel.list);
tableModel.fireTableDataChanged();
Utils.packColumns(table, Utils.MARGIN);
File caKeystore = new File(folder, X509Utils.CA_KEY_STORE);
if (!caKeystore.exists()) {
if (!X509Utils.unlimitedStrength) {
// prompt to confirm user understands JCE Standard Strength encryption
int res = JOptionPane.showConfirmDialog(GitblitAuthority.this, Translation.get("gb.jceWarning"),
Translation.get("gb.warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (res != JOptionPane.YES_OPTION) {
if (Desktop.isDesktopSupported()) {
if (Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
try {
Desktop.getDesktop().browse(URI.create("http://www.oracle.com/technetwork/java/javase/downloads/index.html"));
} catch (IOException e) {
}
}
}
System.exit(1);
}
}
// show certificate defaults dialog
certificateDefaultsButton.doClick();
// create "localhost" ssl certificate
prepareX509Infrastructure();
}
}
}
private boolean prepareX509Infrastructure() {
if (caKeystorePassword == null) {
JPasswordField pass = new JPasswordField(10);
pass.setText(caKeystorePassword);
pass.addAncestorListener(new RequestFocusListener());
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel(Translation.get("gb.enterKeystorePassword")), BorderLayout.NORTH);
panel.add(pass, BorderLayout.CENTER);
int result = JOptionPane.showConfirmDialog(GitblitAuthority.this, panel, Translation.get("gb.password"), JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
caKeystorePassword = new String(pass.getPassword());
} else {
return false;
}
}
X509Metadata metadata = new X509Metadata("localhost", caKeystorePassword);
setMetadataDefaults(metadata);
metadata.notAfter = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
X509Utils.prepareX509Infrastructure(metadata, folder, this);
return true;
}
private List<X509Certificate> findCerts(File folder, String username) {
List<X509Certificate> list = new ArrayList<X509Certificate>();
File userFolder = new File(folder, X509Utils.CERTS + File.separator + username);
if (!userFolder.exists()) {
return list;
}
File [] certs = userFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".cer") || name.toLowerCase().endsWith(".crt");
}
});
try {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
for (File cert : certs) {
BufferedInputStream is = new BufferedInputStream(new FileInputStream(cert));
X509Certificate x509 = (X509Certificate) factory.generateCertificate(is);
is.close();
list.add(x509);
}
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
return list;
}
private Container getUI() {
userCertificatePanel = new UserCertificatePanel(this) {
private static final long serialVersionUID = 1L;
@Override
public Insets getInsets() {
return Utils.INSETS;
}
@Override
public boolean isAllowEmail() {
return mail.isReady();
}
@Override
public Date getDefaultExpiration() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, defaultDuration);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
@Override
public boolean saveUser(String username, UserCertificateModel ucm) {
return userService.updateUserModel(username, ucm.user);
}
@Override
public boolean newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
if (!prepareX509Infrastructure()) {
return false;
}
Date notAfter = metadata.notAfter;
setMetadataDefaults(metadata);
metadata.notAfter = notAfter;
// set user's specified OID values
UserModel user = ucm.user;
if (!StringUtils.isEmpty(user.organizationalUnit)) {
metadata.oids.put("OU", user.organizationalUnit);
}
if (!StringUtils.isEmpty(user.organization)) {
metadata.oids.put("O", user.organization);
}
if (!StringUtils.isEmpty(user.locality)) {
metadata.oids.put("L", user.locality);
}
if (!StringUtils.isEmpty(user.stateProvince)) {
metadata.oids.put("ST", user.stateProvince);
}
if (!StringUtils.isEmpty(user.countryCode)) {
metadata.oids.put("C", user.countryCode);
}
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
File zip = X509Utils.newClientBundle(metadata, caKeystoreFile, caKeystorePassword, GitblitAuthority.this);
// save latest expiration date
if (ucm.expires == null || metadata.notAfter.before(ucm.expires)) {
ucm.expires = metadata.notAfter;
}
updateAuthorityConfig(ucm);
// refresh user
ucm.certs = null;
- int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
+ int selectedIndex = table.getSelectedRow();
tableModel.fireTableDataChanged();
- table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
+ table.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex);
if (sendEmail) {
sendEmail(user, metadata, zip);
}
return true;
}
@Override
public boolean revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
if (!prepareX509Infrastructure()) {
return false;
}
File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword, GitblitAuthority.this)) {
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
if (certificatesConfigFile.exists()) {
try {
config.load();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
}
// add serial to revoked list
ucm.revoke(cert.getSerialNumber(), reason);
ucm.update(config);
try {
config.save();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
// refresh user
ucm.certs = null;
int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
tableModel.fireTableDataChanged();
table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
return true;
}
return false;
}
};
table = Utils.newTable(tableModel, Utils.DATE_FORMAT);
table.setRowSorter(defaultSorter);
table.setDefaultRenderer(CertificateStatus.class, new CertificateStatusRenderer());
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
int row = table.getSelectedRow();
if (row < 0) {
return;
}
int modelIndex = table.convertRowIndexToModel(row);
UserCertificateModel ucm = tableModel.get(modelIndex);
if (ucm.certs == null) {
ucm.certs = findCerts(folder, ucm.user.username);
}
userCertificatePanel.setUserCertificateModel(ucm);
}
});
JPanel usersPanel = new JPanel(new BorderLayout()) {
private static final long serialVersionUID = 1L;
@Override
public Insets getInsets() {
return Utils.INSETS;
}
};
usersPanel.add(new HeaderPanel(Translation.get("gb.users"), "users_16x16.png"), BorderLayout.NORTH);
usersPanel.add(new JScrollPane(table), BorderLayout.CENTER);
usersPanel.setMinimumSize(new Dimension(400, 10));
certificateDefaultsButton = new JButton(new ImageIcon(getClass().getResource("/settings_16x16.png")));
certificateDefaultsButton.setFocusable(false);
certificateDefaultsButton.setToolTipText(Translation.get("gb.newCertificateDefaults"));
certificateDefaultsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
X509Metadata metadata = new X509Metadata("whocares", "whocares");
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
NewCertificateConfig certificateConfig = null;
if (certificatesConfigFile.exists()) {
try {
config.load();
} catch (Exception x) {
Utils.showException(GitblitAuthority.this, x);
}
certificateConfig = NewCertificateConfig.KEY.parse(config);
certificateConfig.update(metadata);
}
InputVerifier verifier = new InputVerifier() {
public boolean verify(JComponent comp) {
boolean returnValue;
JTextField textField = (JTextField) comp;
try {
Integer.parseInt(textField.getText());
returnValue = true;
} catch (NumberFormatException e) {
returnValue = false;
}
return returnValue;
}
};
JTextField siteNameTF = new JTextField(20);
siteNameTF.setText(gitblitSettings.getString(Keys.web.siteName, "Gitblit"));
JPanel siteNamePanel = Utils.newFieldPanel(Translation.get("gb.siteName"),
siteNameTF, Translation.get("gb.siteNameDescription"));
JTextField validityTF = new JTextField(4);
validityTF.setInputVerifier(verifier);
validityTF.setVerifyInputWhenFocusTarget(true);
validityTF.setText("" + certificateConfig.duration);
JPanel validityPanel = Utils.newFieldPanel(Translation.get("gb.validity"),
validityTF, Translation.get("gb.duration.days").replace("{0}", "").trim());
JPanel p1 = new JPanel(new GridLayout(0, 1, 5, 2));
p1.add(siteNamePanel);
p1.add(validityPanel);
DefaultOidsPanel oids = new DefaultOidsPanel(metadata);
JPanel panel = new JPanel(new BorderLayout());
panel.add(p1, BorderLayout.NORTH);
panel.add(oids, BorderLayout.CENTER);
int result = JOptionPane.showConfirmDialog(GitblitAuthority.this,
panel, Translation.get("gb.newCertificateDefaults"), JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/settings_32x32.png")));
if (result == JOptionPane.OK_OPTION) {
try {
oids.update(metadata);
certificateConfig.duration = Integer.parseInt(validityTF.getText());
certificateConfig.store(config, metadata);
config.save();
Map<String, String> updates = new HashMap<String, String>();
updates.put(Keys.web.siteName, siteNameTF.getText());
gitblitSettings.saveSettings(updates);
} catch (Exception e1) {
Utils.showException(GitblitAuthority.this, e1);
}
}
}
});
newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
newSSLCertificate.setFocusable(false);
newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));
newSSLCertificate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Date defaultExpiration = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
NewSSLCertificateDialog dialog = new NewSSLCertificateDialog(GitblitAuthority.this, defaultExpiration);
dialog.setModal(true);
dialog.setVisible(true);
if (dialog.isCanceled()) {
return;
}
final Date expires = dialog.getExpiration();
final String hostname = dialog.getHostname();
final boolean serveCertificate = dialog.isServeCertificate();
AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
@Override
protected Boolean doRequest() throws IOException {
if (!prepareX509Infrastructure()) {
return false;
}
// read CA private key and certificate
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
// generate new SSL certificate
X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
setMetadataDefaults(metadata);
metadata.notAfter = expires;
File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
X509Certificate cert = X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert, serverKeystoreFile, GitblitAuthority.this);
boolean hasCert = cert != null;
if (hasCert && serveCertificate) {
// update Gitblit https connector alias
Map<String, String> updates = new HashMap<String, String>();
updates.put(Keys.server.certificateAlias, metadata.commonName);
gitblitSettings.saveSettings(updates);
}
return hasCert;
}
@Override
protected void onSuccess() {
if (serveCertificate) {
JOptionPane.showMessageDialog(GitblitAuthority.this,
MessageFormat.format(Translation.get("gb.sslCertificateGeneratedRestart"), hostname),
Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(GitblitAuthority.this,
MessageFormat.format(Translation.get("gb.sslCertificateGenerated"), hostname),
Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
}
}
};
worker.execute();
}
});
JButton emailBundle = new JButton(new ImageIcon(getClass().getResource("/mail_16x16.png")));
emailBundle.setFocusable(false);
emailBundle.setToolTipText(Translation.get("gb.emailCertificateBundle"));
emailBundle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row < 0) {
return;
}
int modelIndex = table.convertRowIndexToModel(row);
final UserCertificateModel ucm = tableModel.get(modelIndex);
if (ArrayUtils.isEmpty(ucm.certs)) {
JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.pleaseGenerateClientCertificate"), ucm.user.getDisplayName()));
}
final File zip = new File(folder, X509Utils.CERTS + File.separator + ucm.user.username + File.separator + ucm.user.username + ".zip");
if (!zip.exists()) {
return;
}
AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
@Override
protected Boolean doRequest() throws IOException {
X509Metadata metadata = new X509Metadata(ucm.user.username, "whocares");
metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
if (StringUtils.isEmpty(metadata.serverHostname)) {
metadata.serverHostname = Constants.NAME;
}
metadata.userDisplayname = ucm.user.getDisplayName();
return sendEmail(ucm.user, metadata, zip);
}
@Override
protected void onSuccess() {
JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.clientCertificateBundleSent"),
ucm.user.getDisplayName()));
}
};
worker.execute();
}
});
JButton logButton = new JButton(new ImageIcon(getClass().getResource("/script_16x16.png")));
logButton.setFocusable(false);
logButton.setToolTipText(Translation.get("gb.log"));
logButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File log = new File(folder, X509Utils.CERTS + File.separator + "log.txt");
if (log.exists()) {
String content = FileUtils.readContent(log, "\n");
JTextArea textarea = new JTextArea(content);
JScrollPane scrollPane = new JScrollPane(textarea);
scrollPane.setPreferredSize(new Dimension(700, 400));
JOptionPane.showMessageDialog(GitblitAuthority.this, scrollPane, log.getAbsolutePath(), JOptionPane.INFORMATION_MESSAGE);
}
}
});
final JTextField filterTextfield = new JTextField(15);
filterTextfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterUsers(filterTextfield.getText());
}
});
filterTextfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
filterUsers(filterTextfield.getText());
}
});
JToolBar buttonControls = new JToolBar(JToolBar.HORIZONTAL);
buttonControls.setFloatable(false);
buttonControls.add(certificateDefaultsButton);
buttonControls.add(newSSLCertificate);
buttonControls.add(emailBundle);
buttonControls.add(logButton);
JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
userControls.add(new JLabel(Translation.get("gb.filter")));
userControls.add(filterTextfield);
JPanel topPanel = new JPanel(new BorderLayout(0, 0));
topPanel.add(buttonControls, BorderLayout.WEST);
topPanel.add(userControls, BorderLayout.EAST);
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.add(topPanel, BorderLayout.NORTH);
leftPanel.add(usersPanel, BorderLayout.CENTER);
userCertificatePanel.setMinimumSize(new Dimension(375, 10));
JLabel statusLabel = new JLabel();
statusLabel.setHorizontalAlignment(SwingConstants.RIGHT);
if (X509Utils.unlimitedStrength) {
statusLabel.setText("JCE Unlimited Strength Jurisdiction Policy");
} else {
statusLabel.setText("JCE Standard Encryption Policy");
}
JPanel root = new JPanel(new BorderLayout()) {
private static final long serialVersionUID = 1L;
public Insets getInsets() {
return Utils.INSETS;
}
};
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, userCertificatePanel);
splitPane.setDividerLocation(1d);
root.add(splitPane, BorderLayout.CENTER);
root.add(statusLabel, BorderLayout.SOUTH);
return root;
}
private void filterUsers(final String fragment) {
if (StringUtils.isEmpty(fragment)) {
table.setRowSorter(defaultSorter);
return;
}
RowFilter<UserCertificateTableModel, Object> containsFilter = new RowFilter<UserCertificateTableModel, Object>() {
public boolean include(Entry<? extends UserCertificateTableModel, ? extends Object> entry) {
for (int i = entry.getValueCount() - 1; i >= 0; i--) {
if (entry.getStringValue(i).toLowerCase().contains(fragment.toLowerCase())) {
return true;
}
}
return false;
}
};
TableRowSorter<UserCertificateTableModel> sorter = new TableRowSorter<UserCertificateTableModel>(
tableModel);
sorter.setRowFilter(containsFilter);
table.setRowSorter(sorter);
}
@Override
public void log(String message) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(new File(folder, X509Utils.CERTS + File.separator + "log.txt"), true));
writer.write(MessageFormat.format("{0,date,yyyy-MM-dd HH:mm}: {1}", new Date(), message));
writer.newLine();
writer.flush();
} catch (Exception e) {
LoggerFactory.getLogger(GitblitAuthority.class).error("Failed to append log entry!", e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
private boolean sendEmail(UserModel user, X509Metadata metadata, File zip) {
// send email
try {
if (mail.isReady()) {
Message message = mail.createMessage(user.emailAddress);
message.setSubject("Your Gitblit client certificate for " + metadata.serverHostname);
// body of email
String body = X509Utils.processTemplate(new File(folder, X509Utils.CERTS + File.separator + "mail.tmpl"), metadata);
if (StringUtils.isEmpty(body)) {
body = MessageFormat.format("Hi {0}\n\nHere is your client certificate bundle.\nInside the zip file are installation instructions.", user.getDisplayName());
}
Multipart mp = new MimeMultipart();
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(body);
mp.addBodyPart(messagePart);
// attach zip
MimeBodyPart filePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(zip);
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());
mp.addBodyPart(filePart);
message.setContent(mp);
mail.sendNow(message);
return true;
} else {
JOptionPane.showMessageDialog(GitblitAuthority.this, "Sorry, the mail server settings are not configured properly.\nCan not send email.", Translation.get("gb.error"), JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
return false;
}
private void setMetadataDefaults(X509Metadata metadata) {
metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
if (StringUtils.isEmpty(metadata.serverHostname)) {
metadata.serverHostname = Constants.NAME;
}
// set default values from config file
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
if (certificatesConfigFile.exists()) {
try {
config.load();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
NewCertificateConfig certificateConfig = NewCertificateConfig.KEY.parse(config);
certificateConfig.update(metadata);
}
}
private void updateAuthorityConfig(UserCertificateModel ucm) {
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
if (certificatesConfigFile.exists()) {
try {
config.load();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
}
ucm.update(config);
try {
config.save();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
}
}
| false | true | private Container getUI() {
userCertificatePanel = new UserCertificatePanel(this) {
private static final long serialVersionUID = 1L;
@Override
public Insets getInsets() {
return Utils.INSETS;
}
@Override
public boolean isAllowEmail() {
return mail.isReady();
}
@Override
public Date getDefaultExpiration() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, defaultDuration);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
@Override
public boolean saveUser(String username, UserCertificateModel ucm) {
return userService.updateUserModel(username, ucm.user);
}
@Override
public boolean newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
if (!prepareX509Infrastructure()) {
return false;
}
Date notAfter = metadata.notAfter;
setMetadataDefaults(metadata);
metadata.notAfter = notAfter;
// set user's specified OID values
UserModel user = ucm.user;
if (!StringUtils.isEmpty(user.organizationalUnit)) {
metadata.oids.put("OU", user.organizationalUnit);
}
if (!StringUtils.isEmpty(user.organization)) {
metadata.oids.put("O", user.organization);
}
if (!StringUtils.isEmpty(user.locality)) {
metadata.oids.put("L", user.locality);
}
if (!StringUtils.isEmpty(user.stateProvince)) {
metadata.oids.put("ST", user.stateProvince);
}
if (!StringUtils.isEmpty(user.countryCode)) {
metadata.oids.put("C", user.countryCode);
}
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
File zip = X509Utils.newClientBundle(metadata, caKeystoreFile, caKeystorePassword, GitblitAuthority.this);
// save latest expiration date
if (ucm.expires == null || metadata.notAfter.before(ucm.expires)) {
ucm.expires = metadata.notAfter;
}
updateAuthorityConfig(ucm);
// refresh user
ucm.certs = null;
int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
tableModel.fireTableDataChanged();
table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
if (sendEmail) {
sendEmail(user, metadata, zip);
}
return true;
}
@Override
public boolean revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
if (!prepareX509Infrastructure()) {
return false;
}
File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword, GitblitAuthority.this)) {
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
if (certificatesConfigFile.exists()) {
try {
config.load();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
}
// add serial to revoked list
ucm.revoke(cert.getSerialNumber(), reason);
ucm.update(config);
try {
config.save();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
// refresh user
ucm.certs = null;
int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
tableModel.fireTableDataChanged();
table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
return true;
}
return false;
}
};
table = Utils.newTable(tableModel, Utils.DATE_FORMAT);
table.setRowSorter(defaultSorter);
table.setDefaultRenderer(CertificateStatus.class, new CertificateStatusRenderer());
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
int row = table.getSelectedRow();
if (row < 0) {
return;
}
int modelIndex = table.convertRowIndexToModel(row);
UserCertificateModel ucm = tableModel.get(modelIndex);
if (ucm.certs == null) {
ucm.certs = findCerts(folder, ucm.user.username);
}
userCertificatePanel.setUserCertificateModel(ucm);
}
});
JPanel usersPanel = new JPanel(new BorderLayout()) {
private static final long serialVersionUID = 1L;
@Override
public Insets getInsets() {
return Utils.INSETS;
}
};
usersPanel.add(new HeaderPanel(Translation.get("gb.users"), "users_16x16.png"), BorderLayout.NORTH);
usersPanel.add(new JScrollPane(table), BorderLayout.CENTER);
usersPanel.setMinimumSize(new Dimension(400, 10));
certificateDefaultsButton = new JButton(new ImageIcon(getClass().getResource("/settings_16x16.png")));
certificateDefaultsButton.setFocusable(false);
certificateDefaultsButton.setToolTipText(Translation.get("gb.newCertificateDefaults"));
certificateDefaultsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
X509Metadata metadata = new X509Metadata("whocares", "whocares");
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
NewCertificateConfig certificateConfig = null;
if (certificatesConfigFile.exists()) {
try {
config.load();
} catch (Exception x) {
Utils.showException(GitblitAuthority.this, x);
}
certificateConfig = NewCertificateConfig.KEY.parse(config);
certificateConfig.update(metadata);
}
InputVerifier verifier = new InputVerifier() {
public boolean verify(JComponent comp) {
boolean returnValue;
JTextField textField = (JTextField) comp;
try {
Integer.parseInt(textField.getText());
returnValue = true;
} catch (NumberFormatException e) {
returnValue = false;
}
return returnValue;
}
};
JTextField siteNameTF = new JTextField(20);
siteNameTF.setText(gitblitSettings.getString(Keys.web.siteName, "Gitblit"));
JPanel siteNamePanel = Utils.newFieldPanel(Translation.get("gb.siteName"),
siteNameTF, Translation.get("gb.siteNameDescription"));
JTextField validityTF = new JTextField(4);
validityTF.setInputVerifier(verifier);
validityTF.setVerifyInputWhenFocusTarget(true);
validityTF.setText("" + certificateConfig.duration);
JPanel validityPanel = Utils.newFieldPanel(Translation.get("gb.validity"),
validityTF, Translation.get("gb.duration.days").replace("{0}", "").trim());
JPanel p1 = new JPanel(new GridLayout(0, 1, 5, 2));
p1.add(siteNamePanel);
p1.add(validityPanel);
DefaultOidsPanel oids = new DefaultOidsPanel(metadata);
JPanel panel = new JPanel(new BorderLayout());
panel.add(p1, BorderLayout.NORTH);
panel.add(oids, BorderLayout.CENTER);
int result = JOptionPane.showConfirmDialog(GitblitAuthority.this,
panel, Translation.get("gb.newCertificateDefaults"), JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/settings_32x32.png")));
if (result == JOptionPane.OK_OPTION) {
try {
oids.update(metadata);
certificateConfig.duration = Integer.parseInt(validityTF.getText());
certificateConfig.store(config, metadata);
config.save();
Map<String, String> updates = new HashMap<String, String>();
updates.put(Keys.web.siteName, siteNameTF.getText());
gitblitSettings.saveSettings(updates);
} catch (Exception e1) {
Utils.showException(GitblitAuthority.this, e1);
}
}
}
});
newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
newSSLCertificate.setFocusable(false);
newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));
newSSLCertificate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Date defaultExpiration = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
NewSSLCertificateDialog dialog = new NewSSLCertificateDialog(GitblitAuthority.this, defaultExpiration);
dialog.setModal(true);
dialog.setVisible(true);
if (dialog.isCanceled()) {
return;
}
final Date expires = dialog.getExpiration();
final String hostname = dialog.getHostname();
final boolean serveCertificate = dialog.isServeCertificate();
AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
@Override
protected Boolean doRequest() throws IOException {
if (!prepareX509Infrastructure()) {
return false;
}
// read CA private key and certificate
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
// generate new SSL certificate
X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
setMetadataDefaults(metadata);
metadata.notAfter = expires;
File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
X509Certificate cert = X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert, serverKeystoreFile, GitblitAuthority.this);
boolean hasCert = cert != null;
if (hasCert && serveCertificate) {
// update Gitblit https connector alias
Map<String, String> updates = new HashMap<String, String>();
updates.put(Keys.server.certificateAlias, metadata.commonName);
gitblitSettings.saveSettings(updates);
}
return hasCert;
}
@Override
protected void onSuccess() {
if (serveCertificate) {
JOptionPane.showMessageDialog(GitblitAuthority.this,
MessageFormat.format(Translation.get("gb.sslCertificateGeneratedRestart"), hostname),
Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(GitblitAuthority.this,
MessageFormat.format(Translation.get("gb.sslCertificateGenerated"), hostname),
Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
}
}
};
worker.execute();
}
});
JButton emailBundle = new JButton(new ImageIcon(getClass().getResource("/mail_16x16.png")));
emailBundle.setFocusable(false);
emailBundle.setToolTipText(Translation.get("gb.emailCertificateBundle"));
emailBundle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row < 0) {
return;
}
int modelIndex = table.convertRowIndexToModel(row);
final UserCertificateModel ucm = tableModel.get(modelIndex);
if (ArrayUtils.isEmpty(ucm.certs)) {
JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.pleaseGenerateClientCertificate"), ucm.user.getDisplayName()));
}
final File zip = new File(folder, X509Utils.CERTS + File.separator + ucm.user.username + File.separator + ucm.user.username + ".zip");
if (!zip.exists()) {
return;
}
AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
@Override
protected Boolean doRequest() throws IOException {
X509Metadata metadata = new X509Metadata(ucm.user.username, "whocares");
metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
if (StringUtils.isEmpty(metadata.serverHostname)) {
metadata.serverHostname = Constants.NAME;
}
metadata.userDisplayname = ucm.user.getDisplayName();
return sendEmail(ucm.user, metadata, zip);
}
@Override
protected void onSuccess() {
JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.clientCertificateBundleSent"),
ucm.user.getDisplayName()));
}
};
worker.execute();
}
});
JButton logButton = new JButton(new ImageIcon(getClass().getResource("/script_16x16.png")));
logButton.setFocusable(false);
logButton.setToolTipText(Translation.get("gb.log"));
logButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File log = new File(folder, X509Utils.CERTS + File.separator + "log.txt");
if (log.exists()) {
String content = FileUtils.readContent(log, "\n");
JTextArea textarea = new JTextArea(content);
JScrollPane scrollPane = new JScrollPane(textarea);
scrollPane.setPreferredSize(new Dimension(700, 400));
JOptionPane.showMessageDialog(GitblitAuthority.this, scrollPane, log.getAbsolutePath(), JOptionPane.INFORMATION_MESSAGE);
}
}
});
final JTextField filterTextfield = new JTextField(15);
filterTextfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterUsers(filterTextfield.getText());
}
});
filterTextfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
filterUsers(filterTextfield.getText());
}
});
JToolBar buttonControls = new JToolBar(JToolBar.HORIZONTAL);
buttonControls.setFloatable(false);
buttonControls.add(certificateDefaultsButton);
buttonControls.add(newSSLCertificate);
buttonControls.add(emailBundle);
buttonControls.add(logButton);
JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
userControls.add(new JLabel(Translation.get("gb.filter")));
userControls.add(filterTextfield);
JPanel topPanel = new JPanel(new BorderLayout(0, 0));
topPanel.add(buttonControls, BorderLayout.WEST);
topPanel.add(userControls, BorderLayout.EAST);
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.add(topPanel, BorderLayout.NORTH);
leftPanel.add(usersPanel, BorderLayout.CENTER);
userCertificatePanel.setMinimumSize(new Dimension(375, 10));
JLabel statusLabel = new JLabel();
statusLabel.setHorizontalAlignment(SwingConstants.RIGHT);
if (X509Utils.unlimitedStrength) {
statusLabel.setText("JCE Unlimited Strength Jurisdiction Policy");
} else {
statusLabel.setText("JCE Standard Encryption Policy");
}
JPanel root = new JPanel(new BorderLayout()) {
private static final long serialVersionUID = 1L;
public Insets getInsets() {
return Utils.INSETS;
}
};
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, userCertificatePanel);
splitPane.setDividerLocation(1d);
root.add(splitPane, BorderLayout.CENTER);
root.add(statusLabel, BorderLayout.SOUTH);
return root;
}
| private Container getUI() {
userCertificatePanel = new UserCertificatePanel(this) {
private static final long serialVersionUID = 1L;
@Override
public Insets getInsets() {
return Utils.INSETS;
}
@Override
public boolean isAllowEmail() {
return mail.isReady();
}
@Override
public Date getDefaultExpiration() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, defaultDuration);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
@Override
public boolean saveUser(String username, UserCertificateModel ucm) {
return userService.updateUserModel(username, ucm.user);
}
@Override
public boolean newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
if (!prepareX509Infrastructure()) {
return false;
}
Date notAfter = metadata.notAfter;
setMetadataDefaults(metadata);
metadata.notAfter = notAfter;
// set user's specified OID values
UserModel user = ucm.user;
if (!StringUtils.isEmpty(user.organizationalUnit)) {
metadata.oids.put("OU", user.organizationalUnit);
}
if (!StringUtils.isEmpty(user.organization)) {
metadata.oids.put("O", user.organization);
}
if (!StringUtils.isEmpty(user.locality)) {
metadata.oids.put("L", user.locality);
}
if (!StringUtils.isEmpty(user.stateProvince)) {
metadata.oids.put("ST", user.stateProvince);
}
if (!StringUtils.isEmpty(user.countryCode)) {
metadata.oids.put("C", user.countryCode);
}
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
File zip = X509Utils.newClientBundle(metadata, caKeystoreFile, caKeystorePassword, GitblitAuthority.this);
// save latest expiration date
if (ucm.expires == null || metadata.notAfter.before(ucm.expires)) {
ucm.expires = metadata.notAfter;
}
updateAuthorityConfig(ucm);
// refresh user
ucm.certs = null;
int selectedIndex = table.getSelectedRow();
tableModel.fireTableDataChanged();
table.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex);
if (sendEmail) {
sendEmail(user, metadata, zip);
}
return true;
}
@Override
public boolean revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
if (!prepareX509Infrastructure()) {
return false;
}
File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword, GitblitAuthority.this)) {
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
if (certificatesConfigFile.exists()) {
try {
config.load();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
}
// add serial to revoked list
ucm.revoke(cert.getSerialNumber(), reason);
ucm.update(config);
try {
config.save();
} catch (Exception e) {
Utils.showException(GitblitAuthority.this, e);
}
// refresh user
ucm.certs = null;
int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
tableModel.fireTableDataChanged();
table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
return true;
}
return false;
}
};
table = Utils.newTable(tableModel, Utils.DATE_FORMAT);
table.setRowSorter(defaultSorter);
table.setDefaultRenderer(CertificateStatus.class, new CertificateStatusRenderer());
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
int row = table.getSelectedRow();
if (row < 0) {
return;
}
int modelIndex = table.convertRowIndexToModel(row);
UserCertificateModel ucm = tableModel.get(modelIndex);
if (ucm.certs == null) {
ucm.certs = findCerts(folder, ucm.user.username);
}
userCertificatePanel.setUserCertificateModel(ucm);
}
});
JPanel usersPanel = new JPanel(new BorderLayout()) {
private static final long serialVersionUID = 1L;
@Override
public Insets getInsets() {
return Utils.INSETS;
}
};
usersPanel.add(new HeaderPanel(Translation.get("gb.users"), "users_16x16.png"), BorderLayout.NORTH);
usersPanel.add(new JScrollPane(table), BorderLayout.CENTER);
usersPanel.setMinimumSize(new Dimension(400, 10));
certificateDefaultsButton = new JButton(new ImageIcon(getClass().getResource("/settings_16x16.png")));
certificateDefaultsButton.setFocusable(false);
certificateDefaultsButton.setToolTipText(Translation.get("gb.newCertificateDefaults"));
certificateDefaultsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
X509Metadata metadata = new X509Metadata("whocares", "whocares");
File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
NewCertificateConfig certificateConfig = null;
if (certificatesConfigFile.exists()) {
try {
config.load();
} catch (Exception x) {
Utils.showException(GitblitAuthority.this, x);
}
certificateConfig = NewCertificateConfig.KEY.parse(config);
certificateConfig.update(metadata);
}
InputVerifier verifier = new InputVerifier() {
public boolean verify(JComponent comp) {
boolean returnValue;
JTextField textField = (JTextField) comp;
try {
Integer.parseInt(textField.getText());
returnValue = true;
} catch (NumberFormatException e) {
returnValue = false;
}
return returnValue;
}
};
JTextField siteNameTF = new JTextField(20);
siteNameTF.setText(gitblitSettings.getString(Keys.web.siteName, "Gitblit"));
JPanel siteNamePanel = Utils.newFieldPanel(Translation.get("gb.siteName"),
siteNameTF, Translation.get("gb.siteNameDescription"));
JTextField validityTF = new JTextField(4);
validityTF.setInputVerifier(verifier);
validityTF.setVerifyInputWhenFocusTarget(true);
validityTF.setText("" + certificateConfig.duration);
JPanel validityPanel = Utils.newFieldPanel(Translation.get("gb.validity"),
validityTF, Translation.get("gb.duration.days").replace("{0}", "").trim());
JPanel p1 = new JPanel(new GridLayout(0, 1, 5, 2));
p1.add(siteNamePanel);
p1.add(validityPanel);
DefaultOidsPanel oids = new DefaultOidsPanel(metadata);
JPanel panel = new JPanel(new BorderLayout());
panel.add(p1, BorderLayout.NORTH);
panel.add(oids, BorderLayout.CENTER);
int result = JOptionPane.showConfirmDialog(GitblitAuthority.this,
panel, Translation.get("gb.newCertificateDefaults"), JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/settings_32x32.png")));
if (result == JOptionPane.OK_OPTION) {
try {
oids.update(metadata);
certificateConfig.duration = Integer.parseInt(validityTF.getText());
certificateConfig.store(config, metadata);
config.save();
Map<String, String> updates = new HashMap<String, String>();
updates.put(Keys.web.siteName, siteNameTF.getText());
gitblitSettings.saveSettings(updates);
} catch (Exception e1) {
Utils.showException(GitblitAuthority.this, e1);
}
}
}
});
newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
newSSLCertificate.setFocusable(false);
newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));
newSSLCertificate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Date defaultExpiration = new Date(System.currentTimeMillis() + 10*TimeUtils.ONEYEAR);
NewSSLCertificateDialog dialog = new NewSSLCertificateDialog(GitblitAuthority.this, defaultExpiration);
dialog.setModal(true);
dialog.setVisible(true);
if (dialog.isCanceled()) {
return;
}
final Date expires = dialog.getExpiration();
final String hostname = dialog.getHostname();
final boolean serveCertificate = dialog.isServeCertificate();
AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
@Override
protected Boolean doRequest() throws IOException {
if (!prepareX509Infrastructure()) {
return false;
}
// read CA private key and certificate
File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
// generate new SSL certificate
X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
setMetadataDefaults(metadata);
metadata.notAfter = expires;
File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
X509Certificate cert = X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert, serverKeystoreFile, GitblitAuthority.this);
boolean hasCert = cert != null;
if (hasCert && serveCertificate) {
// update Gitblit https connector alias
Map<String, String> updates = new HashMap<String, String>();
updates.put(Keys.server.certificateAlias, metadata.commonName);
gitblitSettings.saveSettings(updates);
}
return hasCert;
}
@Override
protected void onSuccess() {
if (serveCertificate) {
JOptionPane.showMessageDialog(GitblitAuthority.this,
MessageFormat.format(Translation.get("gb.sslCertificateGeneratedRestart"), hostname),
Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(GitblitAuthority.this,
MessageFormat.format(Translation.get("gb.sslCertificateGenerated"), hostname),
Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
}
}
};
worker.execute();
}
});
JButton emailBundle = new JButton(new ImageIcon(getClass().getResource("/mail_16x16.png")));
emailBundle.setFocusable(false);
emailBundle.setToolTipText(Translation.get("gb.emailCertificateBundle"));
emailBundle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row < 0) {
return;
}
int modelIndex = table.convertRowIndexToModel(row);
final UserCertificateModel ucm = tableModel.get(modelIndex);
if (ArrayUtils.isEmpty(ucm.certs)) {
JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.pleaseGenerateClientCertificate"), ucm.user.getDisplayName()));
}
final File zip = new File(folder, X509Utils.CERTS + File.separator + ucm.user.username + File.separator + ucm.user.username + ".zip");
if (!zip.exists()) {
return;
}
AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {
@Override
protected Boolean doRequest() throws IOException {
X509Metadata metadata = new X509Metadata(ucm.user.username, "whocares");
metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
if (StringUtils.isEmpty(metadata.serverHostname)) {
metadata.serverHostname = Constants.NAME;
}
metadata.userDisplayname = ucm.user.getDisplayName();
return sendEmail(ucm.user, metadata, zip);
}
@Override
protected void onSuccess() {
JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.clientCertificateBundleSent"),
ucm.user.getDisplayName()));
}
};
worker.execute();
}
});
JButton logButton = new JButton(new ImageIcon(getClass().getResource("/script_16x16.png")));
logButton.setFocusable(false);
logButton.setToolTipText(Translation.get("gb.log"));
logButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File log = new File(folder, X509Utils.CERTS + File.separator + "log.txt");
if (log.exists()) {
String content = FileUtils.readContent(log, "\n");
JTextArea textarea = new JTextArea(content);
JScrollPane scrollPane = new JScrollPane(textarea);
scrollPane.setPreferredSize(new Dimension(700, 400));
JOptionPane.showMessageDialog(GitblitAuthority.this, scrollPane, log.getAbsolutePath(), JOptionPane.INFORMATION_MESSAGE);
}
}
});
final JTextField filterTextfield = new JTextField(15);
filterTextfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
filterUsers(filterTextfield.getText());
}
});
filterTextfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
filterUsers(filterTextfield.getText());
}
});
JToolBar buttonControls = new JToolBar(JToolBar.HORIZONTAL);
buttonControls.setFloatable(false);
buttonControls.add(certificateDefaultsButton);
buttonControls.add(newSSLCertificate);
buttonControls.add(emailBundle);
buttonControls.add(logButton);
JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
userControls.add(new JLabel(Translation.get("gb.filter")));
userControls.add(filterTextfield);
JPanel topPanel = new JPanel(new BorderLayout(0, 0));
topPanel.add(buttonControls, BorderLayout.WEST);
topPanel.add(userControls, BorderLayout.EAST);
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.add(topPanel, BorderLayout.NORTH);
leftPanel.add(usersPanel, BorderLayout.CENTER);
userCertificatePanel.setMinimumSize(new Dimension(375, 10));
JLabel statusLabel = new JLabel();
statusLabel.setHorizontalAlignment(SwingConstants.RIGHT);
if (X509Utils.unlimitedStrength) {
statusLabel.setText("JCE Unlimited Strength Jurisdiction Policy");
} else {
statusLabel.setText("JCE Standard Encryption Policy");
}
JPanel root = new JPanel(new BorderLayout()) {
private static final long serialVersionUID = 1L;
public Insets getInsets() {
return Utils.INSETS;
}
};
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, userCertificatePanel);
splitPane.setDividerLocation(1d);
root.add(splitPane, BorderLayout.CENTER);
root.add(statusLabel, BorderLayout.SOUTH);
return root;
}
|
diff --git a/bundles/plugins/org.bonitasoft.studio.validation/src/org/bonitasoft/studio/validation/constraints/form/AvailableValuesReturnTypeConstraint.java b/bundles/plugins/org.bonitasoft.studio.validation/src/org/bonitasoft/studio/validation/constraints/form/AvailableValuesReturnTypeConstraint.java
index 7f2f2f062f..9a1d5e482a 100644
--- a/bundles/plugins/org.bonitasoft.studio.validation/src/org/bonitasoft/studio/validation/constraints/form/AvailableValuesReturnTypeConstraint.java
+++ b/bundles/plugins/org.bonitasoft.studio.validation/src/org/bonitasoft/studio/validation/constraints/form/AvailableValuesReturnTypeConstraint.java
@@ -1,79 +1,82 @@
/**
* Copyright (C) 2009 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
*
* 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.0 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, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.validation.constraints.form;
import java.util.Collection;
import java.util.Map;
import org.bonitasoft.studio.model.expression.Expression;
import org.bonitasoft.studio.model.form.MultipleValuatedFormField;
import org.bonitasoft.studio.model.process.diagram.form.providers.ProcessMarkerNavigationProvider;
import org.bonitasoft.studio.validation.constraints.AbstractLiveValidationMarkerConstraint;
import org.bonitasoft.studio.validation.i18n.Messages;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.validation.IValidationContext;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
/**
* @author Baptiste Mesta
*
*/
public class AvailableValuesReturnTypeConstraint extends AbstractLiveValidationMarkerConstraint {
private static final String ID = "org.bonitasoft.studio.validation.constraints.AvailableValuesReturnTypeConstraint";
@Override
protected IStatus performLiveValidation(IValidationContext ctx) {
return ctx.createSuccessStatus();
}
@Override
protected IStatus performBatchValidation(IValidationContext ctx) {
EObject eObj = ctx.getTarget();
if (eObj instanceof MultipleValuatedFormField) {
MultipleValuatedFormField widget = (MultipleValuatedFormField) eObj;
final Expression availableValues = widget.getInputExpression();
+ if(availableValues == null){
+ return ctx.createSuccessStatus();
+ }
String returnType = availableValues.getReturnType();
Class<?> returnTypeClass;
try {
returnTypeClass = Class.forName(returnType);
} catch (ClassNotFoundException e) {
return ctx.createFailureStatus(Messages.bind(Messages.unsupportedReturnTypeForAvailableValuesOf,widget.getName(),returnType));
}
if(Collection.class.isAssignableFrom(returnTypeClass) || Map.class.isAssignableFrom(returnTypeClass)){
return ctx.createSuccessStatus();
}
return ctx.createFailureStatus(Messages.bind(Messages.unsupportedReturnTypeForAvailableValuesOf,widget.getName(),returnType));
}
return ctx.createSuccessStatus();
}
@Override
protected String getMarkerType(DiagramEditor editor) {
return ProcessMarkerNavigationProvider.MARKER_TYPE;
}
@Override
protected String getConstraintId() {
return ID;
}
}
| true | true | protected IStatus performBatchValidation(IValidationContext ctx) {
EObject eObj = ctx.getTarget();
if (eObj instanceof MultipleValuatedFormField) {
MultipleValuatedFormField widget = (MultipleValuatedFormField) eObj;
final Expression availableValues = widget.getInputExpression();
String returnType = availableValues.getReturnType();
Class<?> returnTypeClass;
try {
returnTypeClass = Class.forName(returnType);
} catch (ClassNotFoundException e) {
return ctx.createFailureStatus(Messages.bind(Messages.unsupportedReturnTypeForAvailableValuesOf,widget.getName(),returnType));
}
if(Collection.class.isAssignableFrom(returnTypeClass) || Map.class.isAssignableFrom(returnTypeClass)){
return ctx.createSuccessStatus();
}
return ctx.createFailureStatus(Messages.bind(Messages.unsupportedReturnTypeForAvailableValuesOf,widget.getName(),returnType));
}
return ctx.createSuccessStatus();
}
| protected IStatus performBatchValidation(IValidationContext ctx) {
EObject eObj = ctx.getTarget();
if (eObj instanceof MultipleValuatedFormField) {
MultipleValuatedFormField widget = (MultipleValuatedFormField) eObj;
final Expression availableValues = widget.getInputExpression();
if(availableValues == null){
return ctx.createSuccessStatus();
}
String returnType = availableValues.getReturnType();
Class<?> returnTypeClass;
try {
returnTypeClass = Class.forName(returnType);
} catch (ClassNotFoundException e) {
return ctx.createFailureStatus(Messages.bind(Messages.unsupportedReturnTypeForAvailableValuesOf,widget.getName(),returnType));
}
if(Collection.class.isAssignableFrom(returnTypeClass) || Map.class.isAssignableFrom(returnTypeClass)){
return ctx.createSuccessStatus();
}
return ctx.createFailureStatus(Messages.bind(Messages.unsupportedReturnTypeForAvailableValuesOf,widget.getName(),returnType));
}
return ctx.createSuccessStatus();
}
|
diff --git a/source/com/mucommander/file/util/ResourceLoader.java b/source/com/mucommander/file/util/ResourceLoader.java
index 6baa0db9..a87354fc 100644
--- a/source/com/mucommander/file/util/ResourceLoader.java
+++ b/source/com/mucommander/file/util/ResourceLoader.java
@@ -1,493 +1,496 @@
/*
* This file is part of muCommander, http://www.mucommander.com
* Copyright (C) 2002-2009 Maxence Bernard
*
* muCommander 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.
*
* muCommander 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/>.
*/
package com.mucommander.file.util;
import com.mucommander.file.AbstractArchiveFile;
import com.mucommander.file.AbstractFile;
import com.mucommander.file.FileFactory;
import com.mucommander.file.FileLogger;
import com.mucommander.file.impl.local.LocalFile;
import com.mucommander.util.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
/**
* This class provides methods to load resources located within the reach of a <code>ClassLoader</code>. Those resources
* can reside either in a JAR file or in a local directory that are in the classpath -- all methods of this class are
* agnostic to either type of location.
*
* <p>The <code>getResourceAsURL</code> and <code>getResourceAsStream</code> methods are akin to those of
* <code>java.lang.Class</code> and <code>java.lang.ClassLoader</code>, except that they are not sensitive to the
* presence of a leading forward-slash separator in the resource path, and that they allow the search to be limited
* to a particular classpath location.</p>
*
* <p>But the real fun lies in the <code>getResourceAsFile</code> methods, which allow to manipulate resources as
* regular files -- again, whether they be in a regular directory or in a JAR file. Likewise,
* the {@link #getRootPackageAsFile(Class)} allows to dynamically explore and manipulate the resource files contained
* in a particular classpath's location.</p>
*
* @author Maxence Bernard
*/
public class ResourceLoader {
/** the default ClassLoader that is used by methods without a ClassLoader argument */
private static ClassLoader defaultClassLoader = ResourceLoader.class.getClassLoader();
/**
* Returns the default <code>ClassLoader</code> that is used by methods without a <code>ClassLoader</code> argument.
* This default <code>ClassLoader</code> is the one that loaded this class, and <b>not</b> the system <code>ClassLoader</code>.
*
* @return the default <code>ClassLoader</code> that is used by methods without a <code>ClassLoader</code> argument
*/
public static ClassLoader getDefaultClassLoader() {
// We do not use the system class loader because it does not work with JNLP/Webstart applications.
// A quote from a FAQ at java.sun.com:
//
// Java Web Start uses a user-level classloader to load all the application resources specified in the JNLP file.
// This classloader implements the security model and the downloading model defined by the JNLP specification.
// This is no different than how the AppletViewer or the Java Plug-In works.
// This has the, unfortunate, side-effect that Class.forName will not find any resources that are defined in the
// JNLP file. The same is true for looking up resources and classes using the system class loader
// (ClassLoader.getSystemClassLoader).
//
return defaultClassLoader;
}
/**
* This method is similar to {@link #getResourceAsURL(String)} except that it looks for a resource with a given
* name in a specific package.
*
* @param ppackage package serving as a base folder for the resource to retrieve
* @param name name of the resource in the package. This is a filename only, not a path.
* @return a URL pointing to the resource, or <code>null</code> if the resource couldn't be located
*/
public static URL getPackageResourceAsURL(Package ppackage, String name) {
return getPackageResourceAsURL(ppackage, name, getDefaultClassLoader(), null);
}
/**
* This method is similar to {@link #getResourceAsURL(String)} except that it looks for a resource with a given
* name in a specific package.
*
* @param ppackage package serving as a base folder for the resource to retrieve
* @param classLoader the ClassLoader used for locating the resource. May not be <code>null</code>.
* @param rootPackageFile root package location (JAR file or directory) that limits the scope of the search,
* <code>null</code> to look for the resource in the whole class path.
* @param name name of the resource in the package. This is a filename only, not a path.
* @return a URL pointing to the resource, or <code>null</code> if the resource couldn't be located
* @see #getRootPackageAsFile(Class)
*/
public static URL getPackageResourceAsURL(Package ppackage, String name, ClassLoader classLoader, AbstractFile rootPackageFile) {
return ResourceLoader.getResourceAsURL(getRelativePackagePath(ppackage)+"/"+name, classLoader, rootPackageFile);
}
/**
* Shorthand for {@link #getResourceAsURL(String, ClassLoader, AbstractFile)} called with the
* {@link #getDefaultClassLoader() default class loader} and a <code>null</code> root package file.
*
* @param path forward slash-separated path to the resource to look for, relative to the parent classpath
* location (directory or JAR file) that contains it.
* @return a URL pointing to the resource, or <code>null</code> if the resource couldn't be located
*/
public static URL getResourceAsURL(String path) {
return getResourceAsURL(path, getDefaultClassLoader(), null);
}
/**
* Finds the resource with the given path and returns a URL pointing to its location, or <code>null</code>
* if the resource couldn't be located. The given <code>ClassLoader</code> is used for locating the resource.
*
* <p>The given resource path must be forward slash (<code>/</code>) separated. It may or may not start with a
* leading forward slash character, this doesn't affect the way it is interpreted.</p>
*
* <p>The <code>rootPackageFile</code> argument can be used to limit the scope of the search to a specific
* location (JAR file or directory) in the classpath: resources located outside of this location will not be matched.
* This avoids potential ambiguities that can arise if the specified resource path exists in several locations.
* If this parameter is <code>null</code>, the resource is looked up in the whole class path. In that case and if
* several resources with the specified path exist, the choice of the resource to return is arbitrary.</p>
*
* @param path forward slash-separated path to the resource to look for, relative to the parent classpath
* location (directory or JAR file) that contains it.
* @param classLoader the ClassLoader used for locating the resource. May not be <code>null</code>.
* @param rootPackageFile root package location (JAR file or directory) that limits the scope of the search,
* <code>null</code> to look for the resource in the whole class path.
* @return a URL pointing to the resource, or <code>null</code> if the resource couldn't be located
*/
public static URL getResourceAsURL(String path, ClassLoader classLoader, AbstractFile rootPackageFile) {
path = removeLeadingSlash(path);
if(rootPackageFile==null)
return classLoader.getResource(path);
String separator = rootPackageFile.getSeparator();
- if(!separator.equals("/"))
- path = StringUtils.replaceCompat(path, "/", separator);
+ String nativePath;
+ if(separator.equals("/"))
+ nativePath = path;
+ else
+ nativePath = StringUtils.replaceCompat(path, "/", separator);
try {
// Iterate through all resources that match the given path, and return the one located inside the
// given root package file.
- Enumeration resourceEnum = classLoader.getResources(removeLeadingSlash(path));
+ Enumeration resourceEnum = classLoader.getResources(path);
String rootPackagePath = rootPackageFile.getAbsolutePath();
- String resourcePath = rootPackageFile.getAbsolutePath(true)+path;
+ String resourcePath = rootPackageFile.getAbsolutePath(true)+nativePath;
URL resourceURL;
while(resourceEnum.hasMoreElements()) {
resourceURL = (URL)resourceEnum.nextElement();
if("jar".equals(resourceURL.getProtocol())) {
if(getJarFilePath(resourceURL).equals(rootPackagePath))
return resourceURL;
}
else {
if(normalizeUrlPath(getDecodedURLPath(resourceURL)).equals(resourcePath))
return resourceURL;
}
}
}
catch(IOException e) {
FileLogger.fine("Failed to lookup resource "+path, e);
return null;
}
return null;
}
/**
* This method is similar to {@link #getResourceAsStream(String)} except that it looks for a resource with a given
* name in a specific package.
*
* @param ppackage package serving as a base folder for the resource to retrieve
* @param name name of the resource in the package. This is a filename only, not a path.
* @return an InputStream that allows to read the resource, or <code>null</code> if the resource couldn't be located
*/
public static InputStream getPackageResourceAsStream(Package ppackage, String name) {
return getPackageResourceAsStream(ppackage, name, getDefaultClassLoader(), null);
}
/**
* This method is similar to {@link #getResourceAsStream(String, ClassLoader, AbstractFile)} except that it looks
* for a resource with a given name in a specific package.
*
* @param ppackage package serving as a base folder for the resource to retrieve
* @param name name of the resource in the package. This is a filename only, not a path.
* @param classLoader the ClassLoader used for locating the resource. May not be <code>null</code>.
* @param rootPackageFile root package location (JAR file or directory) that limits the scope of the search,
* <code>null</code> to look for the resource in the whole class path.
* @return an InputStream that allows to read the resource, or <code>null</code> if the resource couldn't be located
*/
public static InputStream getPackageResourceAsStream(Package ppackage, String name, ClassLoader classLoader, AbstractFile rootPackageFile) {
return ResourceLoader.getResourceAsStream(getRelativePackagePath(ppackage)+"/"+name, classLoader, rootPackageFile);
}
/**
* Shorthand for {@link #getResourceAsStream(String, ClassLoader, AbstractFile)} called with the
* {@link #getDefaultClassLoader() default class loader} and a <code>null</code> root package file.
*
* @param path forward slash-separated path to the resource to look for, relative to the parent classpath
* location (directory or JAR file) that contains it.
* @return an InputStream that allows to read the resource, or <code>null</code> if the resource couldn't be located
*/
public static InputStream getResourceAsStream(String path) {
return getResourceAsStream(path, getDefaultClassLoader(), null);
}
/**
* Finds the resource with the given path and returns an <code>InputStream</code> to read it, or <code>null</code>
* if the resource couldn't be located. The given <code>ClassLoader</code> is used for locating the resource.
*
* <p>The given resource path must be forward slash (<code>/</code>) separated. It may or may not start with a
* leading forward slash character, this doesn't affect the way it is interpreted.</p>
*
* <p>The <code>rootPackageFile</code> argument can be used to limit the scope of the search to a specific
* location (JAR file or directory) in the classpath: resources located outside of this location will not be matched.
* This avoids potential ambiguities that can arise if the specified resource path exists in several locations.
* If this parameter is <code>null</code>, the resource is looked up in the whole class path. In that case and if
* several resources with the specified path exist, the choice of the resource to return is arbitrary.</p>
*
* @param path forward slash-separated path to the resource to look for, relative to the parent classpath
* location (directory or JAR file) that contains it.
* @param classLoader the ClassLoader used for locating the resource. May not be <code>null</code>.
* @param rootPackageFile root package location (JAR file or directory) that limits the scope of the search,
* <code>null</code> to look for the resource in the whole class path.
* @return an InputStream that allows to read the resource, or <code>null</code> if the resource couldn't be located
*/
public static InputStream getResourceAsStream(String path, ClassLoader classLoader, AbstractFile rootPackageFile) {
try {
URL resourceURL = getResourceAsURL(path, classLoader, rootPackageFile);
return resourceURL==null?null:resourceURL.openStream();
}
catch(IOException e) {
return null;
}
}
/**
* This method is similar to {@link #getResourceAsFile(String)} except that it looks for a resource with a given
* name in a specific package.
*
* @param ppackage package serving as a base folder for the resource to retrieve
* @param name name of the resource in the package. This is a filename only, not a path.
* @return an AbstractFile that represents the resource, or <code>null</code> if the resource couldn't be located
*/
public static AbstractFile getPackageResourceAsFile(Package ppackage, String name) {
return getPackageResourceAsFile(ppackage, name, getDefaultClassLoader(), null);
}
/**
* This method is similar to {@link #getResourceAsFile(String, ClassLoader, AbstractFile)} except that it looks for
* a resource with a given name in a specific package.
*
* @param ppackage package serving as a base folder for the resource to retrieve
* @param name name of the resource in the package. This is a filename only, not a path.
* @param classLoader the ClassLoader used for locating the resource. May not be <code>null</code>.
* @param rootPackageFile root package location (JAR file or directory) that limits the scope of the search,
* <code>null</code> to look for the resource in the whole class path.
* @return an AbstractFile that represents the resource, or <code>null</code> if the resource couldn't be located
*/
public static AbstractFile getPackageResourceAsFile(Package ppackage, String name, ClassLoader classLoader, AbstractFile rootPackageFile) {
return ResourceLoader.getResourceAsFile(getRelativePackagePath(ppackage)+"/"+name, classLoader, rootPackageFile);
}
/**
* Shorthand for {@link #getResourceAsFile(String, ClassLoader, AbstractFile)} called with the
* {@link #getDefaultClassLoader() default class loader} and a <code>null</code> root package file.
*
* @param path forward slash-separated path to the resource to look for, relative to the parent classpath
* location (directory or JAR file) that contains it.
* @return an AbstractFile that represents the resource, or <code>null</code> if the resource couldn't be located
*/
public static AbstractFile getResourceAsFile(String path) {
return getResourceAsFile(removeLeadingSlash(path), getDefaultClassLoader(), null);
}
/**
* Finds the resource with the given path and returns an {@link AbstractFile} that gives full access to it,
* or <code>null</code> if the resource couldn't be located. The given <code>ClassLoader</code> is used for locating
* the resource.
*
* <p>The given resource path must be forward slash (<code>/</code>) separated. It may or may not start with a
* leading forward slash character, this doesn't affect the way it is interpreted.</p>
*
* <p>It is worth noting that this method may be slower than {@link #getResourceAsStream(String)} if
* the resource is located inside a JAR file, because the Zip file headers will have to be parsed the first time
* the archive is accessed. Therefore, the latter approach should be favored if the file is simply used for
* reading the resource.</p>
*
* <p>The <code>rootPackageFile</code> argument can be used to limit the scope of the search to a specific
* location (JAR file or directory) in the classpath: resources located outside of this location will not be matched.
* This avoids potential ambiguities that can arise if the specified resource path exists in several locations.
* If this parameter is <code>null</code>, the resource is looked up in the whole class path. In that case and if
* several resources with the specified path exist, the choice of the resource to return is arbitrary.</p>
*
* @param path forward slash-separated path to the resource to look for, relative to the parent classpath
* location (directory or JAR file) that contains it.
* @param classLoader the ClassLoader is used for locating the resource
* @param rootPackageFile root package location (JAR file or directory) that limits the scope of the search,
* <code>null</code> to look for the resource in the whole class path.
* @return an AbstractFile that represents the resource, or <code>null</code> if the resource couldn't be located
*/
public static AbstractFile getResourceAsFile(String path, ClassLoader classLoader, AbstractFile rootPackageFile) {
if(classLoader==null)
classLoader = getDefaultClassLoader();
path = removeLeadingSlash(path);
URL aClassURL = getResourceAsURL(path, classLoader, rootPackageFile);
if(aClassURL==null)
return null; // no resource under that path
if("jar".equals(aClassURL.getProtocol())) {
try {
return ((AbstractArchiveFile)FileFactory.getFile(getJarFilePath(aClassURL))).getArchiveEntryFile(path);
}
catch(Exception e) {
// Shouldn't normally happen, unless the JAR file is corrupt or cannot be parsed by the file API
return null;
}
}
return FileFactory.getFile(getLocalFilePath(aClassURL));
}
/**
* Returns an {@link AbstractFile} to the root package of the given <code>Class</code>. For example, if the
* specified <code>Class</code> is <code>java.lang.Object</code>'s, the returned file will be the Java runtime
* JAR file, which on most platforms is <code>$JAVA_HOME/lib/jre/rt.jar</code>.<br>
* The returned file can be used to list or manipulate all resource files contained in a particular classpath's
* location, including the .class files.
*
* @param aClass the class for which to locate the root package.
* @return an AbstractFile to the root package of the given <code>Class</code>
*/
public static AbstractFile getRootPackageAsFile(Class aClass) {
ClassLoader classLoader = aClass.getClassLoader();
if(classLoader==null)
classLoader = getDefaultClassLoader();
String aClassRelPath = getRelativeClassPath(aClass);
URL aClassURL = getResourceAsURL(aClassRelPath, classLoader, null);
if(aClassURL==null)
return null; // no resource under that path
if("jar".equals(aClassURL.getProtocol()))
return FileFactory.getFile(getJarFilePath(aClassURL));
String aClassPath = getLocalFilePath(aClassURL);
return FileFactory.getFile(aClassPath.substring(0, aClassPath.length()-aClassRelPath.length()));
}
/**
* Returns a path to the given package. The returned path is relative, forward slash-separated and does not end
* with a trailing separator. For example, if the package <code>com.mucommander.file</code> is passed, the returned
* path will be <code>com/mucommander/file</code>.
*
* @param ppackage the package for which to return a path
* @return a path to the given package
*/
public static String getRelativePackagePath(Package ppackage) {
return ppackage.getName().replace('.', '/');
}
/**
* Returns a path to the given class. The returned path is relative, forward slash-separated. For example, if the
* class <code>com.mucommander.file.AbstractFile</code> is passed, the returned path will be
* <code>com/mucommander/file/AbstractFile.class</code>.
*
* @param cclass the class for which to return a path
* @return a path to the given package
*/
public static String getRelativeClassPath(Class cclass) {
return cclass.getName().replace('.', '/')+".class";
}
/////////////////////
// Private methods //
/////////////////////
/**
* Extracts and returns the path to the JAR file from a URL that points to a resource inside a JAR file.
* The returned path is in a format that {@link FileFactory} can turn into an {@link AbstractFile}.
*
* @param url a URL that points to a resource inside a JAR file
* @return returns the path to the JAR file
*/
private static String getJarFilePath(URL url) {
// URL-decode the path
String path = getDecodedURLPath(url);
// Here are a couple examples of such paths:
// file:/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Classes/classes.jar!/java/lang/Object.class
// http://www.mucommander.com/webstart/nightly/mucommander.jar!/com/mucommander/RuntimeConstants.class
int pos = path.indexOf(".jar!");
if(pos==-1)
return path;
// Strip out the part after ".jar" and normalize the path
return normalizeUrlPath(path.substring(0, pos+4));
}
/**
* Extracts and returns the path to a local file represented by the given URL.
* The returned path is in a format that {@link FileFactory} can turn into an {@link AbstractFile}.
*
* @param url a URL that points to a resource inside a JAR file
* @return returns the path to the JAR file
*/
private static String getLocalFilePath(URL url) {
// Here's an example of such a path under Windows:
// /C:/cygwin/home/Administrator/mucommander/tmp/compile/classes/
// URL-decode the path and normalize it
return normalizeUrlPath(getDecodedURLPath(url));
}
/**
* Removes any leading slash from the given path and returns it. Does nothing if the path does not have a
* leading path.
*
* @param path the path to normalize
* @return the path without a leading slash
*/
private static String removeLeadingSlash(String path) {
return PathUtils.removeLeadingSeparator(path, "/");
}
/**
* Normalizes the specified path issued from a <code>java.net.URL</code> and returns it.
* The returned path is in a format that {@link FileFactory} can turn into an {@link AbstractFile}.
*
* @param path the URL path to normalize
* @return the normalized path
*/
private static String normalizeUrlPath(String path) {
// Don't touch http/https URLs
if(path.startsWith("http:") || path.startsWith("https:"))
return path;
// Remove the leading "file:" (if any)
if(path.startsWith("file:"))
path = path.substring(5, path.length());
// Under platforms that use root drives (Windows and OS/2), strip out the leading '/'
if(LocalFile.hasRootDrives() && path.startsWith("/"))
path = removeLeadingSlash(path);
// Use the local file separator
String separator = LocalFile.SEPARATOR;
if(!"/".equals(separator))
path = StringUtils.replaceCompat(path, "/", separator);
return path;
}
/**
* Returns the URL-decoded path of the given <code>java.net.URL</code>. The encoding used for URL-decoding is
* <code>UTF-8</code>.
*
* @param url the URL for which to decode the path
* @return the URL-decoded path of the given URL
*/
private static String getDecodedURLPath(URL url) {
try {
// Decode the URL's path which may contain URL-encoded characters such as %20 for spaces, or non-ASCII
// characters.
// Note: the Java API's javadoc doesn't specify which encoding has been used to encoded URL paths.
// The only indication is in URLDecoder#decode(String, String) javadoc which says:
// "The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may
// introduce incompatibilites."
// Also Note that URLDecoder#decode(String) uses System.getProperty("file.encoding") as the default encoding,
// using this value has been tested without luck under Mac OS X where the value equals "MacRoman" but
// URL are actually encoded in UTF-8. The bottom line is that we blindly use UTF-8 to decode resource URLs.
return URLDecoder.decode(url.getPath(), "UTF-8");
}
catch(UnsupportedEncodingException e) {
// This should never happen, UTF-8 is necessarily supported by the Java runtime
return null;
}
}
}
| false | true | public static URL getResourceAsURL(String path, ClassLoader classLoader, AbstractFile rootPackageFile) {
path = removeLeadingSlash(path);
if(rootPackageFile==null)
return classLoader.getResource(path);
String separator = rootPackageFile.getSeparator();
if(!separator.equals("/"))
path = StringUtils.replaceCompat(path, "/", separator);
try {
// Iterate through all resources that match the given path, and return the one located inside the
// given root package file.
Enumeration resourceEnum = classLoader.getResources(removeLeadingSlash(path));
String rootPackagePath = rootPackageFile.getAbsolutePath();
String resourcePath = rootPackageFile.getAbsolutePath(true)+path;
URL resourceURL;
while(resourceEnum.hasMoreElements()) {
resourceURL = (URL)resourceEnum.nextElement();
if("jar".equals(resourceURL.getProtocol())) {
if(getJarFilePath(resourceURL).equals(rootPackagePath))
return resourceURL;
}
else {
if(normalizeUrlPath(getDecodedURLPath(resourceURL)).equals(resourcePath))
return resourceURL;
}
}
}
catch(IOException e) {
FileLogger.fine("Failed to lookup resource "+path, e);
return null;
}
return null;
}
| public static URL getResourceAsURL(String path, ClassLoader classLoader, AbstractFile rootPackageFile) {
path = removeLeadingSlash(path);
if(rootPackageFile==null)
return classLoader.getResource(path);
String separator = rootPackageFile.getSeparator();
String nativePath;
if(separator.equals("/"))
nativePath = path;
else
nativePath = StringUtils.replaceCompat(path, "/", separator);
try {
// Iterate through all resources that match the given path, and return the one located inside the
// given root package file.
Enumeration resourceEnum = classLoader.getResources(path);
String rootPackagePath = rootPackageFile.getAbsolutePath();
String resourcePath = rootPackageFile.getAbsolutePath(true)+nativePath;
URL resourceURL;
while(resourceEnum.hasMoreElements()) {
resourceURL = (URL)resourceEnum.nextElement();
if("jar".equals(resourceURL.getProtocol())) {
if(getJarFilePath(resourceURL).equals(rootPackagePath))
return resourceURL;
}
else {
if(normalizeUrlPath(getDecodedURLPath(resourceURL)).equals(resourcePath))
return resourceURL;
}
}
}
catch(IOException e) {
FileLogger.fine("Failed to lookup resource "+path, e);
return null;
}
return null;
}
|
diff --git a/src/de/schildbach/pte/AbstractHafasProvider.java b/src/de/schildbach/pte/AbstractHafasProvider.java
index d59f44c3..ba1ea4f1 100644
--- a/src/de/schildbach/pte/AbstractHafasProvider.java
+++ b/src/de/schildbach/pte/AbstractHafasProvider.java
@@ -1,963 +1,972 @@
/*
* Copyright 2010 the original author or authors.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package de.schildbach.pte;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import de.schildbach.pte.dto.Connection;
import de.schildbach.pte.dto.GetConnectionDetailsResult;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.LocationType;
import de.schildbach.pte.dto.NearbyStationsResult;
import de.schildbach.pte.dto.QueryConnectionsResult;
import de.schildbach.pte.dto.QueryConnectionsResult.Status;
import de.schildbach.pte.dto.Station;
import de.schildbach.pte.util.Color;
import de.schildbach.pte.util.ParserUtils;
import de.schildbach.pte.util.XmlPullUtil;
/**
* @author Andreas Schildbach
*/
public abstract class AbstractHafasProvider implements NetworkProvider
{
private static final String DEFAULT_ENCODING = "ISO-8859-1";
private final String apiUri;
private static final String prod = "hafas";
private final String accessId;
public AbstractHafasProvider(final String apiUri, final String accessId)
{
this.apiUri = apiUri;
this.accessId = accessId;
}
protected String[] splitNameAndPlace(final String name)
{
return new String[] { null, name };
}
private final String wrap(final String request)
{
return "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" //
+ "<ReqC ver=\"1.1\" prod=\"" + prod + "\" lang=\"DE\"" + (accessId != null ? " accessId=\"" + accessId + "\"" : "") + ">" //
+ request //
+ "</ReqC>";
}
private static final Location parseStation(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Station".equals(type))
{
final String name = pp.getAttributeValue(null, "name").trim();
final int id = Integer.parseInt(pp.getAttributeValue(null, "externalStationNr"));
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.STATION, id, y, x, null, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parsePoi(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Poi".equals(type))
{
String name = pp.getAttributeValue(null, "name").trim();
if (name.equals("unknown"))
name = null;
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.POI, 0, y, x, null, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parseAddress(final XmlPullParser pp)
{
final String type = pp.getName();
if ("Address".equals(type))
{
String name = pp.getAttributeValue(null, "name").trim();
if (name.equals("unknown"))
name = null;
final int x = Integer.parseInt(pp.getAttributeValue(null, "x"));
final int y = Integer.parseInt(pp.getAttributeValue(null, "y"));
return new Location(LocationType.ADDRESS, 0, y, x, null, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
private static final Location parseReqLoc(final XmlPullParser pp)
{
final String type = pp.getName();
if ("ReqLoc".equals(type))
{
XmlPullUtil.requireAttr(pp, "type", "ADR");
final String name = pp.getAttributeValue(null, "output").trim();
return new Location(LocationType.ADDRESS, 0, null, name);
}
throw new IllegalStateException("cannot handle: " + type);
}
public List<Location> autocompleteStations(final CharSequence constraint) throws IOException
{
final String request = "<LocValReq id=\"req\" maxNr=\"20\"><ReqLoc match=\"" + constraint + "\" type=\"ALLTYPE\"/></LocValReq>";
// System.out.println(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request), 3);
final List<Location> results = new ArrayList<Location>();
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "LocValRes");
XmlPullUtil.requireAttr(pp, "id", "req");
XmlPullUtil.enter(pp);
while (pp.getEventType() == XmlPullParser.START_TAG)
{
final String tag = pp.getName();
if ("Station".equals(tag))
results.add(parseStation(pp));
else if ("Poi".equals(tag))
results.add(parsePoi(pp));
else if ("Address".equals(tag))
results.add(parseAddress(pp));
else if ("ReqLoc".equals(tag))
/* results.add(parseReqLoc(pp)) */;
else
System.out.println("cannot handle tag: " + tag);
XmlPullUtil.next(pp);
}
XmlPullUtil.exit(pp);
return results;
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep,
final String products, final WalkSpeed walkSpeed) throws IOException
{
if (from.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(from.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(autocompletes, null, null);
from = autocompletes.get(0);
}
if (via != null && via.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(via.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, autocompletes, null);
via = autocompletes.get(0);
}
if (to.type == LocationType.ANY)
{
final List<Location> autocompletes = autocompleteStations(to.name);
if (autocompletes.isEmpty())
return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); // TODO
if (autocompletes.size() > 1)
return new QueryConnectionsResult(null, null, autocompletes);
to = autocompletes.get(0);
}
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm");
final String request = "<ConReq>" //
+ "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" //
+ (via != null ? "<Via>" + location(via) + "</Via>" : "") //
+ "<Dest>" + location(to) + "</Dest>" //
+ "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" //
+ "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" //
+ "</ConReq>";
return queryConnections(request, from, via, to);
}
public QueryConnectionsResult queryMoreConnections(final String context) throws IOException
{
final String request = "<ConScrReq scr=\"F\" nrCons=\"4\">" //
+ "<ConResCtxt>" + context + "</ConResCtxt>" //
+ "</ConScrReq>";
return queryConnections(request, null, null, null);
}
private QueryConnectionsResult queryConnections(final String request, final Location from, final Location via, final Location to)
throws IOException
{
// System.out.println(request);
// ParserUtils.printXml(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request), 3);
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp, "ResC");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("F1")) // Spool: Error reading the spoolfile
return new QueryConnectionsResult(Status.SERVICE_DOWN);
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.enter(pp, "ConRes");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
- if (code.equals("K9380"))
+ if (code.equals("K9380") || code.equals("K895")) // Departure/Arrival are too near
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.UNRESOLVABLE_ADDRESS;
+ if (code.equals("K9240")) // Internal error
+ return new QueryConnectionsResult(Status.SERVICE_DOWN);
+ if (code.equals("K9260")) // Departure station does not exist
+ return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
+ if (code.equals("K891")) // No route found (try entering an intermediate station)
+ return QueryConnectionsResult.NO_CONNECTIONS;
+ if (code.equals("K899")) // An error occurred
+ return new QueryConnectionsResult(Status.SERVICE_DOWN);
+ // if (code.equals("K1:890")) // Unsuccessful or incomplete search (direction: forward)
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String context = XmlPullUtil.text(pp);
XmlPullUtil.enter(pp, "ConnectionList");
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "Overview");
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location departure = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Departure");
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location arrival = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Arrival");
XmlPullUtil.exit(pp, "Overview");
XmlPullUtil.enter(pp, "ConSectionList");
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionDeparture = parseLocation(pp);
XmlPullUtil.enter(pp, "Dep");
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
Location destination = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "JourneyAttributeList");
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp, "JourneyAttribute");
XmlPullUtil.require(pp, "Attribute");
final String attrName = pp.getAttributeValue(null, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
destination = new Location(LocationType.ANY, 0, null, attributeVariants.get("NORMAL"));
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.enter(pp, "Duration");
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionArrival = parseLocation(pp);
XmlPullUtil.enter(pp, "Arr");
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, destination, departureTime, departurePos, sectionDeparture.id, sectionDeparture.name,
arrivalTime, arrivalPos, sectionArrival.id, sectionArrival.name, null));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure,
sectionArrival.id, sectionArrival.name));
}
else
{
parts.add(new Connection.Footway(min, sectionDeparture.id, sectionDeparture.name, sectionArrival.id, sectionArrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, departure.id, departure.name, arrival.id, arrival.name,
parts, null));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, context, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
private final Location parseLocation(final XmlPullParser pp) throws XmlPullParserException, IOException
{
Location location;
if (pp.getName().equals("Station"))
location = parseStation(pp);
else if (pp.getName().equals("Poi"))
location = parsePoi(pp);
else if (pp.getName().equals("Address"))
location = parseAddress(pp);
else
throw new IllegalStateException("cannot parse: " + pp.getName());
XmlPullUtil.next(pp);
return location;
}
private final Map<String, String> parseAttributeVariants(final XmlPullParser pp) throws XmlPullParserException, IOException
{
final Map<String, String> attributeVariants = new HashMap<String, String>();
while (XmlPullUtil.test(pp, "AttributeVariant"))
{
final String type = XmlPullUtil.attr(pp, "type");
XmlPullUtil.enter(pp);
XmlPullUtil.require(pp, "Text");
final String value = XmlPullUtil.text(pp).trim();
XmlPullUtil.exit(pp);
attributeVariants.put(type, value);
}
return attributeVariants;
}
private static final Pattern P_TIME = Pattern.compile("(\\d+)d(\\d+):(\\d{2}):(\\d{2})");
private Date parseTime(final Calendar currentDate, final String str)
{
final Matcher m = P_TIME.matcher(str);
if (m.matches())
{
final Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, currentDate.get(Calendar.YEAR));
c.set(Calendar.MONTH, currentDate.get(Calendar.MONTH));
c.set(Calendar.DAY_OF_MONTH, currentDate.get(Calendar.DAY_OF_MONTH));
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(m.group(2)));
c.set(Calendar.MINUTE, Integer.parseInt(m.group(3)));
c.set(Calendar.SECOND, Integer.parseInt(m.group(4)));
c.set(Calendar.MILLISECOND, 0);
c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(m.group(1)));
return c.getTime();
}
else
{
throw new IllegalArgumentException("cannot parse duration: " + str);
}
}
private static final Pattern P_DURATION = Pattern.compile("(\\d+):(\\d{2})");
private final int parseDuration(final String str)
{
final Matcher m = P_DURATION.matcher(str);
if (m.matches())
return Integer.parseInt(m.group(1)) * 60 + Integer.parseInt(m.group(2));
else
throw new IllegalArgumentException("cannot parse duration: " + str);
}
private static final String location(final Location location)
{
if (location.type == LocationType.STATION && location.id != 0)
return "<Station externalId=\"" + location.id + "\" />";
if (location.type == LocationType.POI && location.hasLocation())
return "<Poi type=\"WGS84\" x=\"" + location.lon + "\" y=\"" + location.lat + "\" />";
if (location.type == LocationType.ADDRESS && location.hasLocation())
return "<Address type=\"WGS84\" x=\"" + location.lon + "\" y=\"" + location.lat + "\" />";
throw new IllegalArgumentException("cannot handle: " + location.toDebugString());
}
protected static final String locationId(final Location location)
{
final StringBuilder builder = new StringBuilder();
builder.append("A=").append(locationType(location));
if (location.hasLocation())
builder.append("@X=" + location.lon + "@Y=" + location.lat);
if (location.name != null)
builder.append("@G=" + location.name);
if (location.type == LocationType.STATION && location.id != 0)
builder.append("@L=").append(location.id);
return builder.toString();
}
protected static final int locationType(final Location location)
{
if (location.type == LocationType.STATION)
return 1;
if (location.type == LocationType.POI)
return 4;
if (location.type == LocationType.ADDRESS && location.hasLocation())
return 16;
if (location.type == LocationType.ADDRESS && location.name != null)
return 2;
if (location.type == LocationType.ANY)
return 255;
throw new IllegalArgumentException(location.type.toString());
}
private static final Pattern P_LINE_S = Pattern.compile("S\\d+");
private static final Pattern P_LINE_SN = Pattern.compile("SN\\d*");
private final String _normalizeLine(final String type, final String name, final String longCategory)
{
final String normalizedType = type.split(" ", 2)[0];
final String normalizedName = normalizeWhitespace(name);
if ("EN".equals(normalizedType)) // EuroNight
return "I" + normalizedName;
if ("EC".equals(normalizedType)) // EuroCity
return "I" + normalizedName;
if ("ICE".equals(normalizedType)) // InterCityExpress
return "I" + normalizedName;
if ("IC".equals(normalizedType)) // InterCity
return "I" + normalizedName;
if ("ICN".equals(normalizedType)) // IC-Neigezug
return "I" + normalizedName;
if ("CNL".equals(normalizedType)) // CityNightLine
return "I" + normalizedName;
if ("OEC".equals(normalizedType)) // ÖBB EuroCity
return "I" + normalizedName;
if ("OIC".equals(normalizedType)) // ÖBB InterCity
return "I" + normalizedName;
if ("TGV".equals(normalizedType)) // Train à grande vit.
return "I" + normalizedName;
if ("THA".equals(normalizedType)) // Thalys
return "I" + normalizedName;
if ("THALYS".equals(normalizedType)) // THALYS
return "I" + normalizedName;
if ("ES".equals(normalizedType)) // Eurostar Italia
return "I" + normalizedName;
if ("EST".equals(normalizedType)) // Eurostar
return "I" + normalizedName;
if ("X2".equals(normalizedType)) // X2000 Neigezug, Schweden
return "I" + normalizedName;
if ("RJ".equals(normalizedType)) // Railjet
return "I" + normalizedName;
if ("AVE".equals(normalizedType)) // Alta Velocidad ES
return "I" + normalizedName;
if ("ARC".equals(normalizedType)) // Arco, Spanien
return "I" + normalizedName;
if ("ALS".equals(normalizedType)) // Alaris, Spanien
return "I" + normalizedName;
if ("TAL".equals(normalizedType)) // Talgo, Spanien
return "I" + normalizedName;
if ("NZ".equals(normalizedType)) // Nacht-Zug
return "I" + normalizedName;
if ("FYR".equals(normalizedType)) // Fyra, Amsterdam-Schiphol-Rotterdam
return "I" + normalizedName;
if ("R".equals(normalizedType)) // Regio
return "R" + normalizedName;
if ("D".equals(normalizedType)) // Schnellzug
return "R" + normalizedName;
if ("E".equals(normalizedType)) // Eilzug
return "R" + normalizedName;
if ("RE".equals(normalizedType)) // RegioExpress
return "R" + normalizedName;
if ("IR".equals(normalizedType)) // InterRegio
return "R" + normalizedName;
if ("IRE".equals(normalizedType)) // InterRegioExpress
return "R" + normalizedName;
if ("ATZ".equals(normalizedType)) // Autotunnelzug
return "R" + normalizedName;
if ("EXT".equals(normalizedType)) // Extrazug
return "R" + normalizedName;
if ("S".equals(normalizedType)) // S-Bahn
return "S" + normalizedName;
if (P_LINE_S.matcher(normalizedType).matches()) // diverse S-Bahnen
return "S" + normalizedType;
if (P_LINE_SN.matcher(normalizedType).matches()) // Nacht-S-Bahn
return "S" + normalizedType;
if ("SPR".equals(normalizedType)) // Sprinter, Niederlande
return "S" + normalizedName;
if ("Met".equals(normalizedType)) // Metro
return "U" + normalizedName;
if ("M".equals(normalizedType)) // Metro
return "U" + normalizedName;
if ("Métro".equals(normalizedType))
return "U" + normalizedName;
if ("Tram".equals(normalizedType)) // Tram
return "T" + normalizedName;
if ("T".equals(normalizedType)) // Tram
return "T" + normalizedName;
if ("Tramway".equals(normalizedType))
return "T" + normalizedName;
if ("BUS".equals(normalizedType)) // Bus
return "B" + normalizedName;
if ("Bus".equals(normalizedType)) // Niederflurbus
return "B" + normalizedName;
if ("NFB".equals(normalizedType)) // Niederflur-Bus
return "B" + normalizedName;
if ("N".equals(normalizedType)) // Nachtbus
return "B" + normalizedName;
if ("Tro".equals(normalizedType)) // Trolleybus
return "B" + normalizedName;
if ("Taxi".equals(normalizedType)) // Taxi
return "B" + normalizedName;
if ("TX".equals(normalizedType)) // Taxi
return "B" + normalizedName;
if ("BAT".equals(normalizedType)) // Schiff
return "F" + normalizedName;
if ("LB".equals(normalizedType)) // Luftseilbahn
return "C" + normalizedName;
if ("FUN".equals(normalizedType)) // Standseilbahn
return "C" + normalizedName;
if ("Fun".equals(normalizedType)) // Funiculaire
return "C" + normalizedName;
if ("L".equals(normalizedType))
return "?" + normalizedName;
if ("P".equals(normalizedType))
return "?" + normalizedName;
if ("CR".equals(normalizedType))
return "?" + normalizedName;
if ("TRN".equals(normalizedType))
return "?" + normalizedName;
throw new IllegalStateException("cannot normalize type '" + normalizedType + "' (" + type + ") name '" + normalizedName + "' longCategory '"
+ longCategory + "'");
}
private final static Pattern P_WHITESPACE = Pattern.compile("\\s+");
private final String normalizeWhitespace(final String str)
{
return P_WHITESPACE.matcher(str).replaceAll("");
}
public GetConnectionDetailsResult getConnectionDetails(String connectionUri) throws IOException
{
throw new UnsupportedOperationException();
}
private final static Pattern P_NEARBY_COARSE = Pattern.compile("<tr class=\"(zebra[^\"]*)\">(.*?)</tr>", Pattern.DOTALL);
private final static Pattern P_NEARBY_FINE_COORDS = Pattern
.compile("REQMapRoute0\\.Location0\\.X=(-?\\d+)&(?:amp;)?REQMapRoute0\\.Location0\\.Y=(-?\\d+)&");
private final static Pattern P_NEARBY_FINE_LOCATION = Pattern.compile("[\\?&]input=(\\d+)&[^\"]*\">([^<]*)<");
protected abstract String nearbyStationUri(String stationId);
public NearbyStationsResult nearbyStations(final String stationId, final int lat, final int lon, final int maxDistance, final int maxStations)
throws IOException
{
if (stationId == null)
throw new IllegalArgumentException("stationId must be given");
final List<Station> stations = new ArrayList<Station>();
final String uri = nearbyStationUri(stationId);
final CharSequence page = ParserUtils.scrape(uri);
String oldZebra = null;
final Matcher mCoarse = P_NEARBY_COARSE.matcher(page);
while (mCoarse.find())
{
final String zebra = mCoarse.group(1);
if (oldZebra != null && zebra.equals(oldZebra))
throw new IllegalArgumentException("missed row? last:" + zebra);
else
oldZebra = zebra;
final Matcher mFineLocation = P_NEARBY_FINE_LOCATION.matcher(mCoarse.group(2));
if (mFineLocation.find())
{
int parsedLon = 0;
int parsedLat = 0;
final int parsedId = Integer.parseInt(mFineLocation.group(1));
final String parsedName = ParserUtils.resolveEntities(mFineLocation.group(2));
final Matcher mFineCoords = P_NEARBY_FINE_COORDS.matcher(mCoarse.group(2));
if (mFineCoords.find())
{
parsedLon = Integer.parseInt(mFineCoords.group(1));
parsedLat = Integer.parseInt(mFineCoords.group(2));
}
final String[] nameAndPlace = splitNameAndPlace(parsedName);
stations.add(new Station(parsedId, nameAndPlace[0], nameAndPlace[1], parsedName, parsedLat, parsedLon, 0, null, null));
}
else
{
throw new IllegalArgumentException("cannot parse '" + mCoarse.group(2) + "' on " + uri);
}
}
if (maxStations == 0 || maxStations >= stations.size())
return new NearbyStationsResult(stations);
else
return new NearbyStationsResult(stations.subList(0, maxStations));
}
protected static final Pattern P_NORMALIZE_LINE = Pattern.compile("([A-Za-zÄÖÜäöüßáàâéèêíìîóòôúùû/-]+)[\\s-]*(.*)");
protected final String normalizeLine(final String type, final String line)
{
final Matcher m = P_NORMALIZE_LINE.matcher(line);
final String strippedLine = m.matches() ? m.group(1) + m.group(2) : line;
final char normalizedType = normalizeType(type);
if (normalizedType != 0)
return normalizedType + strippedLine;
throw new IllegalStateException("cannot normalize type '" + type + "' line '" + line + "'");
}
protected abstract char normalizeType(String type);
protected final char normalizeCommonTypes(final String ucType)
{
// Intercity
if (ucType.equals("EC")) // EuroCity
return 'I';
if (ucType.equals("EN")) // EuroNight
return 'I';
if (ucType.equals("ICE")) // InterCityExpress
return 'I';
if (ucType.equals("IC")) // InterCity
return 'I';
if (ucType.equals("EN")) // EuroNight
return 'I';
if (ucType.equals("CNL")) // CityNightLine
return 'I';
if (ucType.equals("OEC")) // ÖBB-EuroCity
return 'I';
if (ucType.equals("OIC")) // ÖBB-InterCity
return 'I';
if (ucType.equals("RJ")) // RailJet, Österreichische Bundesbahnen
return 'I';
if (ucType.equals("THA")) // Thalys
return 'I';
if (ucType.equals("TGV")) // Train à Grande Vitesse
return 'I';
if (ucType.equals("DNZ")) // Berlin-Saratov, Berlin-Moskva, Connections only?
return 'I';
if (ucType.equals("AIR")) // Generic Flight
return 'I';
if (ucType.equals("ECB")) // EC, Verona-München
return 'I';
if (ucType.equals("INZ")) // Nacht
return 'I';
if (ucType.equals("RHI")) // ICE
return 'I';
if (ucType.equals("RHT")) // TGV
return 'I';
if (ucType.equals("TGD")) // TGV
return 'I';
if (ucType.equals("IRX")) // IC
return 'I';
// Regional Germany
if (ucType.equals("ZUG")) // Generic Train
return 'R';
if (ucType.equals("R")) // Generic Regional Train
return 'R';
if (ucType.equals("DPN")) // Dritter Personen Nahverkehr
return 'R';
if (ucType.equals("RB")) // RegionalBahn
return 'R';
if (ucType.equals("RE")) // RegionalExpress
return 'R';
if (ucType.equals("IR")) // Interregio
return 'R';
if (ucType.equals("IRE")) // Interregio Express
return 'R';
if (ucType.equals("HEX")) // Harz-Berlin-Express, Veolia
return 'R';
if (ucType.equals("WFB")) // Westfalenbahn
return 'R';
if (ucType.equals("RT")) // RegioTram
return 'R';
if (ucType.equals("REX")) // RegionalExpress, Österreich
return 'R';
// Regional Poland
if (ucType.equals("OS")) // Chop-Cierna nas Tisou
return 'R';
if (ucType.equals("SP")) // Polen
return 'R';
// Suburban Trains
if (ucType.equals("S")) // Generic S-Bahn
return 'S';
// Subway
if (ucType.equals("U")) // Generic U-Bahn
return 'U';
// Tram
if (ucType.equals("STR")) // Generic Tram
return 'T';
// Bus
if (ucType.equals("BUS")) // Generic Bus
return 'B';
if (ucType.equals("AST")) // Anruf-Sammel-Taxi
return 'B';
if (ucType.equals("RUF")) // Rufbus
return 'B';
if (ucType.equals("SEV")) // Schienen-Ersatz-Verkehr
return 'B';
if (ucType.equals("BUSSEV")) // Schienen-Ersatz-Verkehr
return 'B';
if (ucType.equals("BSV")) // Bus SEV
return 'B';
if (ucType.equals("FB")) // Luxemburg-Saarbrücken
return 'B';
// Ferry
if (ucType.equals("SCH")) // Schiff
return 'F';
if (ucType.equals("AS")) // SyltShuttle, eigentlich Autoreisezug
return 'F';
return 0;
}
private static final Pattern P_CONNECTION_ID = Pattern.compile("co=(C\\d+-\\d+)&");
protected static String extractConnectionId(final String link)
{
final Matcher m = P_CONNECTION_ID.matcher(link);
if (m.find())
return m.group(1);
else
throw new IllegalArgumentException("cannot extract id from " + link);
}
private static final Map<Character, int[]> LINES = new HashMap<Character, int[]>();
static
{
LINES.put('I', new int[] { Color.WHITE, Color.RED, Color.RED });
LINES.put('R', new int[] { Color.GRAY, Color.WHITE });
LINES.put('S', new int[] { Color.parseColor("#006e34"), Color.WHITE });
LINES.put('U', new int[] { Color.parseColor("#003090"), Color.WHITE });
LINES.put('T', new int[] { Color.parseColor("#cc0000"), Color.WHITE });
LINES.put('B', new int[] { Color.parseColor("#993399"), Color.WHITE });
LINES.put('F', new int[] { Color.BLUE, Color.WHITE });
LINES.put('?', new int[] { Color.DKGRAY, Color.WHITE });
}
public int[] lineColors(final String line)
{
if (line.length() == 0)
return null;
return LINES.get(line.charAt(0));
}
private void assertResC(final XmlPullParser pp) throws XmlPullParserException, IOException
{
if (!XmlPullUtil.jumpToStartTag(pp, null, "ResC"))
throw new IOException("cannot find <ResC />");
}
}
| false | true | private QueryConnectionsResult queryConnections(final String request, final Location from, final Location via, final Location to)
throws IOException
{
// System.out.println(request);
// ParserUtils.printXml(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request), 3);
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp, "ResC");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("F1")) // Spool: Error reading the spoolfile
return new QueryConnectionsResult(Status.SERVICE_DOWN);
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.enter(pp, "ConRes");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("K9380"))
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.UNRESOLVABLE_ADDRESS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String context = XmlPullUtil.text(pp);
XmlPullUtil.enter(pp, "ConnectionList");
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "Overview");
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location departure = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Departure");
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location arrival = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Arrival");
XmlPullUtil.exit(pp, "Overview");
XmlPullUtil.enter(pp, "ConSectionList");
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionDeparture = parseLocation(pp);
XmlPullUtil.enter(pp, "Dep");
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
Location destination = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "JourneyAttributeList");
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp, "JourneyAttribute");
XmlPullUtil.require(pp, "Attribute");
final String attrName = pp.getAttributeValue(null, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
destination = new Location(LocationType.ANY, 0, null, attributeVariants.get("NORMAL"));
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.enter(pp, "Duration");
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionArrival = parseLocation(pp);
XmlPullUtil.enter(pp, "Arr");
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, destination, departureTime, departurePos, sectionDeparture.id, sectionDeparture.name,
arrivalTime, arrivalPos, sectionArrival.id, sectionArrival.name, null));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure,
sectionArrival.id, sectionArrival.name));
}
else
{
parts.add(new Connection.Footway(min, sectionDeparture.id, sectionDeparture.name, sectionArrival.id, sectionArrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, departure.id, departure.name, arrival.id, arrival.name,
parts, null));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, context, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
| private QueryConnectionsResult queryConnections(final String request, final Location from, final Location via, final Location to)
throws IOException
{
// System.out.println(request);
// ParserUtils.printXml(ParserUtils.scrape(apiUri, true, wrap(request), null, false));
final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
InputStream is = null;
try
{
is = ParserUtils.scrapeInputStream(apiUri, wrap(request), 3);
final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
final XmlPullParser pp = factory.newPullParser();
pp.setInput(is, DEFAULT_ENCODING);
assertResC(pp);
XmlPullUtil.enter(pp, "ResC");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("F1")) // Spool: Error reading the spoolfile
return new QueryConnectionsResult(Status.SERVICE_DOWN);
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.enter(pp, "ConRes");
if (XmlPullUtil.test(pp, "Err"))
{
final String code = XmlPullUtil.attr(pp, "code");
if (code.equals("K9380") || code.equals("K895")) // Departure/Arrival are too near
return QueryConnectionsResult.TOO_CLOSE;
if (code.equals("K9220")) // Nearby to the given address stations could not be found
return QueryConnectionsResult.UNRESOLVABLE_ADDRESS;
if (code.equals("K9240")) // Internal error
return new QueryConnectionsResult(Status.SERVICE_DOWN);
if (code.equals("K9260")) // Departure station does not exist
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K890")) // No connections found
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K891")) // No route found (try entering an intermediate station)
return QueryConnectionsResult.NO_CONNECTIONS;
if (code.equals("K899")) // An error occurred
return new QueryConnectionsResult(Status.SERVICE_DOWN);
// if (code.equals("K1:890")) // Unsuccessful or incomplete search (direction: forward)
throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text"));
}
XmlPullUtil.require(pp, "ConResCtxt");
final String context = XmlPullUtil.text(pp);
XmlPullUtil.enter(pp, "ConnectionList");
final List<Connection> connections = new ArrayList<Connection>();
while (XmlPullUtil.test(pp, "Connection"))
{
final String id = XmlPullUtil.attr(pp, "id");
XmlPullUtil.enter(pp);
while (pp.getName().equals("RtStateList"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "Overview");
XmlPullUtil.require(pp, "Date");
final Calendar currentDate = new GregorianCalendar();
currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp)));
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location departure = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Departure");
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location arrival = parseLocation(pp);
XmlPullUtil.exit(pp, "BasicStop");
XmlPullUtil.exit(pp, "Arrival");
XmlPullUtil.exit(pp, "Overview");
XmlPullUtil.enter(pp, "ConSectionList");
final List<Connection.Part> parts = new ArrayList<Connection.Part>(4);
Date firstDepartureTime = null;
Date lastArrivalTime = null;
while (XmlPullUtil.test(pp, "ConSection"))
{
XmlPullUtil.enter(pp);
// departure
XmlPullUtil.enter(pp, "Departure");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionDeparture = parseLocation(pp);
XmlPullUtil.enter(pp, "Dep");
XmlPullUtil.require(pp, "Time");
final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String departurePos = XmlPullUtil.text(pp).trim();
if (departurePos.length() == 0)
departurePos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
// journey
String line = null;
Location destination = null;
int min = 0;
final String tag = pp.getName();
if (tag.equals("Journey"))
{
XmlPullUtil.enter(pp);
while (pp.getName().equals("JHandle"))
XmlPullUtil.next(pp);
XmlPullUtil.enter(pp, "JourneyAttributeList");
String name = null;
String category = null;
String longCategory = null;
while (XmlPullUtil.test(pp, "JourneyAttribute"))
{
XmlPullUtil.enter(pp, "JourneyAttribute");
XmlPullUtil.require(pp, "Attribute");
final String attrName = pp.getAttributeValue(null, "type");
XmlPullUtil.enter(pp);
final Map<String, String> attributeVariants = parseAttributeVariants(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if ("NAME".equals(attrName))
{
name = attributeVariants.get("NORMAL");
}
else if ("CATEGORY".equals(attrName))
{
category = attributeVariants.get("NORMAL");
longCategory = attributeVariants.get("LONG");
}
else if ("DIRECTION".equals(attrName))
{
destination = new Location(LocationType.ANY, 0, null, attributeVariants.get("NORMAL"));
}
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
line = _normalizeLine(category, name, longCategory);
}
else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute"))
{
XmlPullUtil.enter(pp);
XmlPullUtil.enter(pp, "Duration");
XmlPullUtil.require(pp, "Time");
min = parseDuration(XmlPullUtil.text(pp).substring(3, 8));
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
}
else
{
throw new IllegalStateException("cannot handle: " + pp.getName());
}
// arrival
XmlPullUtil.enter(pp, "Arrival");
XmlPullUtil.enter(pp, "BasicStop");
while (pp.getName().equals("StAttrList"))
XmlPullUtil.next(pp);
final Location sectionArrival = parseLocation(pp);
XmlPullUtil.enter(pp, "Arr");
XmlPullUtil.require(pp, "Time");
final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp));
XmlPullUtil.enter(pp, "Platform");
XmlPullUtil.require(pp, "Text");
String arrivalPos = XmlPullUtil.text(pp).trim();
if (arrivalPos.length() == 0)
arrivalPos = null;
XmlPullUtil.exit(pp, "Platform");
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
if (min == 0 || line != null)
{
parts.add(new Connection.Trip(line, destination, departureTime, departurePos, sectionDeparture.id, sectionDeparture.name,
arrivalTime, arrivalPos, sectionArrival.id, sectionArrival.name, null));
}
else
{
if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway)
{
final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1);
parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure,
sectionArrival.id, sectionArrival.name));
}
else
{
parts.add(new Connection.Footway(min, sectionDeparture.id, sectionDeparture.name, sectionArrival.id, sectionArrival.name));
}
}
if (firstDepartureTime == null)
firstDepartureTime = departureTime;
lastArrivalTime = arrivalTime;
}
XmlPullUtil.exit(pp);
XmlPullUtil.exit(pp);
connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, departure.id, departure.name, arrival.id, arrival.name,
parts, null));
}
XmlPullUtil.exit(pp);
return new QueryConnectionsResult(null, from, via, to, context, connections);
}
catch (final XmlPullParserException x)
{
throw new RuntimeException(x);
}
catch (final ParseException x)
{
throw new RuntimeException(x);
}
finally
{
if (is != null)
is.close();
}
}
|
diff --git a/src/Commands.java b/src/Commands.java
index df53f84..15b272f 100644
--- a/src/Commands.java
+++ b/src/Commands.java
@@ -1,515 +1,515 @@
import java.awt.Color;
import java.util.ArrayList;
import y.base.Edge;
import y.base.EdgeCursor;
import y.base.Node;
import y.view.Arrow;
import y.view.EdgeRealizer;
import y.view.GenericEdgeRealizer;
import y.view.LineType;
import y.view.NodeLabel;
public final class Commands {
public static boolean processIfNoChange (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() > 1);
assert(answer.get(0) instanceof Symbol);
Symbol key = (Symbol)answer.get(0);
if (key.isEqual("highlight") || key.isEqual("highlight-queue")) {
processCommand(ihl, answer, demo);
return true;
}
return false;
}
public static boolean processCommand (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() > 1);
assert(answer.get(0) instanceof Symbol);
Symbol key = (Symbol)answer.get(0);
if (key.isEqual("beginning"))
return beginning(ihl, answer, demo);
if (! ihl.graphfinished) {
if (! (key.isEqual("highlight") || key.isEqual("highlight-queue") || key.isEqual("relayouted")))
ihl.numChanges++;
if (! key.isEqual("relayouted"))
ihl.changes.get(ihl.changes.size() - 1).add(answer);
}
- if (key.isEqual("dfm-header"))
- return dfmheader(ihl, answer);
+ //if (key.isEqual("dfm-header"))
+ // return dfmheader(ihl, answer);
if (key.isEqual("change-edge"))
return changeedge(ihl, answer);
if (key.isEqual("remove-edge"))
return removeedge(ihl, answer);
if (key.isEqual("insert-edge"))
return insertedge(ihl, answer);
if (key.isEqual("new-computation"))
return newcomputation(ihl, answer);
if (key.isEqual("remove-computation"))
return removenode(ihl, answer, false);
if (key.isEqual("add-temporary"))
return addtemporary(ihl, answer);
if (key.isEqual("add-temporary-user"))
return addtemporaryuser(ihl, answer);
if (key.isEqual("remove-temporary-user"))
return removetemporaryuser(ihl, answer);
if (key.isEqual("temporary-generator"))
return temporarygenerator(ihl, answer);
if (key.isEqual("remove-temporary"))
return removenode(ihl, answer, true);
if (key.isEqual("change-type"))
return changetype(ihl, answer, demo);
if (key.isEqual("change-entry-point"))
return changeentrypoint(ihl, answer, demo);
if (key.isEqual("set-loop-call-loop"))
return setloopcallloop(ihl, answer);
if (key.isEqual("relayouted"))
return relayouted(ihl);
if (key.isEqual("highlight"))
return highlight(ihl, answer, demo);
if (key.isEqual("highlight-queue"))
return highlightqueue(ihl, answer, demo);
if (key.isEqual("new-type-variable"))
return new_type_var(ihl, answer);
if (key.isEqual("new-type-node"))
return new_type_node(ihl, answer);
if (key.isEqual("connect"))
return connect(ihl, answer, demo);
if (key.isEqual("disconnect"))
return disconnect(ihl, answer, demo);
if (key.isEqual("remove-node"))
return removetypenode(ihl, answer, demo);
if (key.isEqual("highlight-constraint"))
return highlightedge(ihl, answer, demo, true);
if (key.isEqual("unhighlight-constraint"))
return highlightedge(ihl, answer, demo, false);
if (key.isEqual("type-relation"))
return typerelation(ihl, answer, demo);
System.out.println("shouldn't be here");
return false;
}
private static boolean setloopcallloop(IncrementalHierarchicLayout ihl,
ArrayList answer) {
Node loopcall = getNode(ihl, answer, 2, false);
Node loop = getNode(ihl, answer, 3, true);
if (loop != null)
ihl.graph.createEdge(loopcall, loop);
return false;
}
private static Node getNode (IncrementalHierarchicLayout ihl, ArrayList answer, int index, boolean maybenull) {
assert(answer.size() >= index);
assert(answer.get(index) instanceof Integer);
Integer nodeid = (Integer)answer.get(index);
Node n = ihl.int_node_map.get(nodeid);
if (! maybenull) {
assert(ihl.int_node_map.containsKey(nodeid));
assert(n != null);
}
return n;
}
private static boolean beginning (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.get(2) instanceof ArrayList);
ArrayList mess = (ArrayList)answer.get(2);
assert(mess.get(0) instanceof String);
String ph = (String)mess.get(0);
if (mess.size() == 2) {
if (mess.get(1) instanceof Integer) {
Node n = getNode(ihl, mess, 1, false);
String label = ihl.graph.getRealizer(n).getLabelText();
ph = ph + " " + label; //or label text? but might be too long
} else if (mess.get(1) instanceof Symbol) {
Symbol tag = (Symbol)mess.get(1);
if (tag.isEqual("global")) {
//demo.phase.setText(ph);
//demo.phase.validate();
return false;
}
}
}
ihl.updatephase(ph);
demo.calcLayout();
return false;
}
private static boolean dfmheader (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 3);
assert(answer.get(2) instanceof ArrayList);
ArrayList cfs = (ArrayList)answer.get(2);
String main = null;
for (Object o : cfs) {
assert(o instanceof ArrayList);
ArrayList cf = (ArrayList)o;
assert(cf.size() == 5);
assert(cf.get(0) instanceof Symbol);
assert(((Symbol)cf.get(0)).isEqual("method"));
assert(cf.get(1) instanceof String); //method name
assert(cf.get(2) instanceof Integer); //bind
if ((Integer)cf.get(2) != 0) {
Node bind = getNode(ihl, cf, 2, false);
assert(cf.get(3) instanceof ArrayList); //args
assert(cf.get(4) instanceof ArrayList); //arg names
main = (String)(cf.get(1));
ihl.addMethodNode(main, bind, (ArrayList)cf.get(3), (ArrayList)cf.get(4));
}
}
return true;
}
private static boolean changeedge (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 6);
assert(answer.get(5) instanceof Symbol);
Node from = getNode(ihl, answer, 2, false);
Node toold = getNode(ihl, answer, 3, false);
Node tonew = getNode(ihl, answer, 4, false);
Symbol label = (Symbol)answer.get(5);
if (label.isEqual("no"))
label = null;
Edge change = null;
for (EdgeCursor ec = from.outEdges(); ec.ok(); ec.next())
if (ec.edge().target() == toold)
if (label == null || label.isEqual(ihl.graph.getRealizer(ec.edge()).getLabelText())) {
change = ec.edge();
break;
}
if (change != null) {
ihl.graph.changeEdge(change, from, tonew);
return true;
} else
if (ihl.safeCreateEdge(from, tonew)) {
System.out.println("only created edge");
if (label != null)
ihl.setEdgeLabel(label);
return true;
}
return false;
}
private static boolean removeedge (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 5);
assert(answer.get(4) instanceof Symbol);
Node from = getNode(ihl, answer, 2, false);
Node to = getNode(ihl, answer, 3, false);
Symbol label = (Symbol)answer.get(4);
if (label.isEqual("no"))
label = null;
for (EdgeCursor ec = from.outEdges(); ec.ok(); ec.next())
if (ec.edge().target() == to)
if (label == null || label.isEqual(ihl.graph.getRealizer(ec.edge()).getLabelText())) {
ihl.graph.removeEdge(ec.edge());
return true;
}
System.out.println("FAILED");
return false;
}
private static boolean insertedge (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 5);
Node from = getNode(ihl, answer, 2, false);
Node to = getNode(ihl, answer, 3, false);
assert(answer.get(4) instanceof Symbol);
Symbol label = (Symbol)answer.get(4);
if (label.isEqual("no"))
label = null;
if (ihl.safeCreateEdge(from, to)) {
if (label != null)
ihl.setEdgeLabel(label);
//System.out.println("connected!");
return true;
}
return false;
}
private static boolean newcomputation (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 3);
assert(answer.get(2) instanceof ArrayList);
ArrayList text = (ArrayList)answer.get(2);
ihl.createNewNode(text);
return true;
}
private static boolean removenode (IncrementalHierarchicLayout ihl, ArrayList answer, boolean mayfail) {
assert(answer.size() == 3);
Node del = getNode(ihl, answer, 2, mayfail);
if (del != null) {
if (ihl.graph.getRealizer(del).getLabelText().contains("bind") && del.inDegree() == 1)
ihl.graph.removeNode(del.firstInEdge().source());
//System.out.println("D:" + del.degree() + " " + ihl.graph.getRealizer(del).getLabelText());
if (del.degree() > 0)
for (EdgeCursor ec = del.edges(); ec.ok(); ec.next()) {
//System.out.println(" was connected to " + ihl.graph.getRealizer(ec.edge().opposite(del)).getLabelText());
}
ihl.graph.removeNode(del);
ihl.int_node_map.remove((Integer)answer.get(2));
return true;
}
return false;
}
private static boolean addtemporary (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 5);
assert(answer.get(2) instanceof Integer);
assert(answer.get(3) instanceof String);
assert(answer.get(4) instanceof Integer);
int temp_id = (Integer)answer.get(2);
String text = (String)answer.get(3);
text.replace(':', ' ');
int c_id = (Integer)answer.get(4);
if (ihl.int_node_map.get(temp_id) == null) {
ihl.createTemporary(temp_id, c_id, text + ":");
return true;
}
//System.out.println("already added temporary " + temp_id + " " + text);
return false;
}
private static boolean addtemporaryuser (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 4);
Node temp = getNode(ihl, answer, 2, false);
Node comp = getNode(ihl, answer, 3, false);
ihl.graph.createEdge(temp, comp);
ihl.setEdgeColor(Color.blue);
return true;
}
private static boolean removetemporaryuser (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 4);
Node temp = getNode(ihl, answer, 2, true);
if (temp == null) {
System.out.println("temp not present " + (Integer)answer.get(2));
return false; //happens with arguments of inlined functions
}
Node comp = getNode(ihl, answer, 3, false);
for (EdgeCursor ec = temp.outEdges(); ec.ok(); ec.next())
if (ec.edge().target() == comp) {
ihl.graph.removeEdge(ec.edge());
return true;
}
return false;
}
private static boolean temporarygenerator (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 5);
Node temp = getNode(ihl, answer, 2, false);
Node newgenerator = getNode(ihl, answer, 3, false);
Node oldgenerator = getNode(ihl, answer, 4, true);
if (oldgenerator != null)
for (EdgeCursor ec = temp.inEdges(); ec.ok(); ec.next())
if (ec.edge().source() == oldgenerator) {
ihl.graph.changeEdge(ec.edge(), temp, newgenerator);
return true;
}
if (ihl.safeCreateEdge(newgenerator, temp)) {
ihl.setEdgeColor(Color.blue);
return true;
}
return false;
}
private static boolean changetype (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() == 4);
Node n = getNode(ihl, answer, 2, true);
if (n != null) {
assert(answer.get(3) instanceof String);
NodeLabel nl = ihl.graph.getRealizer(n).getLabel();
String old = nl.getText();
String newtext = ((String)answer.get(3)).replace(':', ' ');
//filter number out
int start = old.indexOf(':', old.indexOf(':') + 1) + 1;
nl.setText(old.substring(0, start) + newtext);
ihl.graph.getRealizer(n).setWidth(nl.getWidth());
//System.out.println("change type " + old + " => " + (String)answer.get(3));
demo.view.repaint();
//ihl.isok = false;
}
return false;
}
private static boolean changeentrypoint(IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() == 4);
Node n = getNode(ihl, answer, 2, false);
assert(answer.get(3) instanceof Symbol);
NodeLabel nl = ihl.graph.getRealizer(n).getLabel();
String old = nl.getText();
//filter number out
int start = old.indexOf(':') + 1;
nl.setText(old.substring(0, start) + " " + ((Symbol)answer.get(3)).toString() + " " + old.substring(start));
ihl.graph.getRealizer(n).setWidth(nl.getWidth());
//System.out.println("change entry point " + old + " => " + ((Symbol)answer.get(3)).toString());
demo.view.repaint();
return true;
}
private static boolean relayouted (IncrementalHierarchicLayout ihl) {
//ihl.activateLayouter();
return false;
}
private static boolean highlight (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
if ((Integer)answer.get(2) == 0) {
if (ihl.highlight != null) {
ihl.graph.getRealizer(ihl.highlight).setFillColor(ihl.graph.getDefaultNodeRealizer().getFillColor());
ihl.highlight = null;
demo.view.repaint();
}
return false;
}
Node highlightnew = getNode(ihl, answer, 2, false);
if (ihl.highlight != highlightnew) {
if (ihl.highlight != null)
ihl.graph.getRealizer(ihl.highlight).setFillColor(ihl.graph.getDefaultNodeRealizer().getFillColor());
ihl.graph.getRealizer(highlightnew).setFillColor(new Color(0x22, 0xdd, 0, 0x66));
ihl.highlight = highlightnew;
demo.view.repaint();
}
return false;
}
private static boolean highlightqueue (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
ArrayList queue = (ArrayList)answer.get(2);
ArrayList<Integer> removed = new ArrayList<Integer>();
ArrayList<Integer> added = new ArrayList<Integer>();
for (Object ind : queue)
if (! ihl.opt_queue.contains((Integer)ind))
added.add((Integer)ind);
for (Integer old : ihl.opt_queue)
if (! queue.contains(old))
removed.add(old);
for (Integer rem : removed) {
ihl.opt_queue.remove(rem);
Node unh = ihl.int_node_map.get(rem);
if (unh != ihl.highlight && unh != null)
ihl.graph.getRealizer(unh).setFillColor(ihl.graph.getDefaultNodeRealizer().getFillColor());
}
for (Integer a : added) {
ihl.opt_queue.add(a);
Node h = ihl.int_node_map.get(a);
if (h != ihl.highlight && h != null)
ihl.graph.getRealizer(h).setFillColor(Color.orange);
}
demo.view.repaint();
return false;
}
private static boolean new_type_var (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 5);
//Node object = getNode(ihl, answer, 3, false);
assert(answer.get(3) instanceof Integer);
assert(answer.get(2) instanceof Integer);
String t = null;
if (answer.get(4) instanceof Integer)
t = Integer.toString((Integer)answer.get(4));
else {
if (answer.get(4) instanceof String)
t = (String)answer.get(4);
else if (answer.get(4) instanceof Symbol)
t = ((Symbol)answer.get(4)).toString();
}
ihl.createTypeVariable((Integer)answer.get(2), (Integer)answer.get(3), t);
ihl.typechanged = true;
return false;
}
private static boolean new_type_node (IncrementalHierarchicLayout ihl, ArrayList answer) {
assert(answer.size() == 4);
assert(answer.get(2) instanceof Integer);
int id = (Integer)answer.get(2);
if (answer.get(3) instanceof Integer) {
Node object = getNode(ihl, answer, 3, false);
ihl.createTypeNode(id, object);
} else {
Node nnode = null;
//got a "base type" / String or Symbol
if (answer.get(3) instanceof Symbol) //arrow or tuple!
nnode = ihl.createTypeNodeWithLabel(((Symbol)answer.get(3)).toString(), id);
else
nnode = ihl.createTypeNodeWithLabel((String)answer.get(3), id);
ihl.typeHintMap.set(nnode, ihl.typeHintsFactory.createLayerIncrementallyHint(nnode));
}
ihl.typechanged = true;
return false;
}
private static boolean typerelation (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() == 4);
Node temp = getNode(ihl, answer, 3, false);
Node type = getNode(ihl, answer, 2, false);
ihl.tv_temp_map.put(type, temp);
NodeLabel n = ihl.typegraph.getRealizer(type).getLabel();
n.setText(n.getText() + " [" + (Integer)answer.get(3) + "]");
ihl.typegraph.getRealizer(type).setWidth(n.getWidth());
demo.typeview.repaint();
return false;
}
private static boolean removetypenode (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() == 3);
Node del = getNode(ihl, answer, 2, false);
if (del != null) {
ihl.typegraph.removeNode(del);
ihl.int_node_map.remove((Integer)answer.get(2));
ihl.tv_temp_map.remove(del);
//ihl.typechanged = true;
demo.typeview.repaint();
}
return false;
}
private static boolean connect (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() == 5);
Node from = getNode(ihl, answer, 2, false);
Node to = getNode(ihl, answer, 3, false);
EdgeRealizer er = new GenericEdgeRealizer(ihl.typegraph.getDefaultEdgeRealizer());
assert(answer.get(4) instanceof Symbol);
Symbol type = (Symbol)answer.get(4);
if (type.isEqual("<constraint-edge>")) {
er.setLineColor(Color.GREEN);
er.setArrow(Arrow.NONE);
} else if (type.isEqual("<representative-edge>"))
er.setLineColor(Color.red);
else
er.setLineColor(Color.BLUE);
ihl.typegraph.createEdge(from, to, er);
if (! (type.isEqual("<representative-edge>")))
ihl.typescf.addPlaceNodeBelowConstraint(from, to);
demo.typeview.repaint();
return false;
}
private static boolean disconnect (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() == 5);
Node from = getNode(ihl, answer, 2, false);
Node to = getNode(ihl, answer, 3, false);
assert(answer.get(4) instanceof Symbol);
Symbol type = (Symbol)answer.get(4);
Color nc = Color.BLUE;
if (type.isEqual("<constraint-edge>"))
nc = Color.green;
else if (type.isEqual("<representative-edge>"))
nc = Color.red;
for (EdgeCursor ec = from.outEdges(); ec.ok(); ec.next())
if (ec.edge().target() == to)
if (ihl.typegraph.getRealizer(ec.edge()).getLineColor() == nc)
ihl.typegraph.removeEdge(ec.edge());
demo.typeview.repaint();
return false;
}
private static boolean highlightedge (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo, boolean thick) {
Node from = getNode(ihl, answer, 2, false);
Node to = getNode(ihl, answer, 3, false);
LineType lt = LineType.LINE_2;
if (thick)
lt = LineType.LINE_4;
for (EdgeCursor ec = from.outEdges(); ec.ok(); ec.next())
if (ec.edge().target() == to)
ihl.typegraph.getRealizer(ec.edge()).setLineType(lt);
demo.typeview.repaint();
return false;
}
}
| true | true | public static boolean processCommand (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() > 1);
assert(answer.get(0) instanceof Symbol);
Symbol key = (Symbol)answer.get(0);
if (key.isEqual("beginning"))
return beginning(ihl, answer, demo);
if (! ihl.graphfinished) {
if (! (key.isEqual("highlight") || key.isEqual("highlight-queue") || key.isEqual("relayouted")))
ihl.numChanges++;
if (! key.isEqual("relayouted"))
ihl.changes.get(ihl.changes.size() - 1).add(answer);
}
if (key.isEqual("dfm-header"))
return dfmheader(ihl, answer);
if (key.isEqual("change-edge"))
return changeedge(ihl, answer);
if (key.isEqual("remove-edge"))
return removeedge(ihl, answer);
if (key.isEqual("insert-edge"))
return insertedge(ihl, answer);
if (key.isEqual("new-computation"))
return newcomputation(ihl, answer);
if (key.isEqual("remove-computation"))
return removenode(ihl, answer, false);
if (key.isEqual("add-temporary"))
return addtemporary(ihl, answer);
if (key.isEqual("add-temporary-user"))
return addtemporaryuser(ihl, answer);
if (key.isEqual("remove-temporary-user"))
return removetemporaryuser(ihl, answer);
if (key.isEqual("temporary-generator"))
return temporarygenerator(ihl, answer);
if (key.isEqual("remove-temporary"))
return removenode(ihl, answer, true);
if (key.isEqual("change-type"))
return changetype(ihl, answer, demo);
if (key.isEqual("change-entry-point"))
return changeentrypoint(ihl, answer, demo);
if (key.isEqual("set-loop-call-loop"))
return setloopcallloop(ihl, answer);
if (key.isEqual("relayouted"))
return relayouted(ihl);
if (key.isEqual("highlight"))
return highlight(ihl, answer, demo);
if (key.isEqual("highlight-queue"))
return highlightqueue(ihl, answer, demo);
if (key.isEqual("new-type-variable"))
return new_type_var(ihl, answer);
if (key.isEqual("new-type-node"))
return new_type_node(ihl, answer);
if (key.isEqual("connect"))
return connect(ihl, answer, demo);
if (key.isEqual("disconnect"))
return disconnect(ihl, answer, demo);
if (key.isEqual("remove-node"))
return removetypenode(ihl, answer, demo);
if (key.isEqual("highlight-constraint"))
return highlightedge(ihl, answer, demo, true);
if (key.isEqual("unhighlight-constraint"))
return highlightedge(ihl, answer, demo, false);
if (key.isEqual("type-relation"))
return typerelation(ihl, answer, demo);
System.out.println("shouldn't be here");
return false;
}
| public static boolean processCommand (IncrementalHierarchicLayout ihl, ArrayList answer, DemoBase demo) {
assert(answer.size() > 1);
assert(answer.get(0) instanceof Symbol);
Symbol key = (Symbol)answer.get(0);
if (key.isEqual("beginning"))
return beginning(ihl, answer, demo);
if (! ihl.graphfinished) {
if (! (key.isEqual("highlight") || key.isEqual("highlight-queue") || key.isEqual("relayouted")))
ihl.numChanges++;
if (! key.isEqual("relayouted"))
ihl.changes.get(ihl.changes.size() - 1).add(answer);
}
//if (key.isEqual("dfm-header"))
// return dfmheader(ihl, answer);
if (key.isEqual("change-edge"))
return changeedge(ihl, answer);
if (key.isEqual("remove-edge"))
return removeedge(ihl, answer);
if (key.isEqual("insert-edge"))
return insertedge(ihl, answer);
if (key.isEqual("new-computation"))
return newcomputation(ihl, answer);
if (key.isEqual("remove-computation"))
return removenode(ihl, answer, false);
if (key.isEqual("add-temporary"))
return addtemporary(ihl, answer);
if (key.isEqual("add-temporary-user"))
return addtemporaryuser(ihl, answer);
if (key.isEqual("remove-temporary-user"))
return removetemporaryuser(ihl, answer);
if (key.isEqual("temporary-generator"))
return temporarygenerator(ihl, answer);
if (key.isEqual("remove-temporary"))
return removenode(ihl, answer, true);
if (key.isEqual("change-type"))
return changetype(ihl, answer, demo);
if (key.isEqual("change-entry-point"))
return changeentrypoint(ihl, answer, demo);
if (key.isEqual("set-loop-call-loop"))
return setloopcallloop(ihl, answer);
if (key.isEqual("relayouted"))
return relayouted(ihl);
if (key.isEqual("highlight"))
return highlight(ihl, answer, demo);
if (key.isEqual("highlight-queue"))
return highlightqueue(ihl, answer, demo);
if (key.isEqual("new-type-variable"))
return new_type_var(ihl, answer);
if (key.isEqual("new-type-node"))
return new_type_node(ihl, answer);
if (key.isEqual("connect"))
return connect(ihl, answer, demo);
if (key.isEqual("disconnect"))
return disconnect(ihl, answer, demo);
if (key.isEqual("remove-node"))
return removetypenode(ihl, answer, demo);
if (key.isEqual("highlight-constraint"))
return highlightedge(ihl, answer, demo, true);
if (key.isEqual("unhighlight-constraint"))
return highlightedge(ihl, answer, demo, false);
if (key.isEqual("type-relation"))
return typerelation(ihl, answer, demo);
System.out.println("shouldn't be here");
return false;
}
|
diff --git a/test/func/route/SimpleRouteTest.java b/test/func/route/SimpleRouteTest.java
index f3321309..cba8674e 100644
--- a/test/func/route/SimpleRouteTest.java
+++ b/test/func/route/SimpleRouteTest.java
@@ -1,102 +1,102 @@
/*
* Copyright (C) 2008 Steve Ratcliffe
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 or
* version 2 as published by the Free Software Foundation.
*
* 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.
*/
/* Create date: 16-Feb-2009 */
package func.route;
import java.io.FileNotFoundException;
import java.util.List;
import uk.me.parabola.imgfmt.fs.DirectoryEntry;
import uk.me.parabola.imgfmt.fs.FileSystem;
import uk.me.parabola.imgfmt.sys.ImgFS;
import uk.me.parabola.mkgmap.main.Main;
import func.lib.Args;
import func.lib.RangeMatcher;
import org.junit.Test;
import static org.junit.Assert.*;
public class SimpleRouteTest {
/**
* Simple test to ensure that nothing has changed. Of course
* if the output should have changed, then this will have to be altered
* to match.
*/
@Test
public void testSize() throws FileNotFoundException {
Main.main(new String[]{
Args.TEST_STYLE_ARG,
"--route",
Args.TEST_RESOURCE_OSM + "uk-test-1.osm.gz",
Args.TEST_RESOURCE_MP + "test1.mp"
});
FileSystem fs = ImgFS.openFs(Args.DEF_MAP_ID + ".img");
assertNotNull("file exists", fs);
List<DirectoryEntry> entries = fs.list();
int count = 0;
for (DirectoryEntry ent : entries) {
String ext = ent.getExt();
int size = ent.getSize();
if (ext.equals("RGN")) {
count++;
assertThat("RGN size", size, new RangeMatcher(141999));
} else if (ext.equals("TRE")) {
count++;
assertEquals("TRE size", 1341, size);
} else if (ext.equals("LBL")) {
count++;
- assertEquals("LBL size", 27645, size);
+ assertEquals("LBL size", 27647, size);
} else if (ext.equals("NET")) {
count++;
assertEquals("NET size", 73850, size);
} else if (ext.equals("NOD")) {
count++;
assertEquals("NOD size", 195187, size);
}
}
assertTrue("enough checks run", count == 5);
fs = ImgFS.openFs(Args.DEF_MAP_FILENAME2);
assertNotNull("file exists", fs);
entries = fs.list();
count = 0;
for (DirectoryEntry ent : entries) {
String ext = ent.getExt();
int size = ent.getSize();
if (ext.equals("RGN")) {
count++;
assertThat("RGN size", size, new RangeMatcher(2934));
} else if (ext.equals("TRE")) {
count++;
assertEquals("TRE size", 594, size);
} else if (ext.equals("LBL")) {
count++;
assertEquals("LBL size", 957, size);
} else if (ext.equals("NET")) {
count++;
assertEquals("NET size", 1280, size);
} else if (ext.equals("NOD")) {
count++;
assertEquals("NOD size", 3114, size);
}
}
assertTrue("enough checks run", count == 5);
}
}
| true | true | public void testSize() throws FileNotFoundException {
Main.main(new String[]{
Args.TEST_STYLE_ARG,
"--route",
Args.TEST_RESOURCE_OSM + "uk-test-1.osm.gz",
Args.TEST_RESOURCE_MP + "test1.mp"
});
FileSystem fs = ImgFS.openFs(Args.DEF_MAP_ID + ".img");
assertNotNull("file exists", fs);
List<DirectoryEntry> entries = fs.list();
int count = 0;
for (DirectoryEntry ent : entries) {
String ext = ent.getExt();
int size = ent.getSize();
if (ext.equals("RGN")) {
count++;
assertThat("RGN size", size, new RangeMatcher(141999));
} else if (ext.equals("TRE")) {
count++;
assertEquals("TRE size", 1341, size);
} else if (ext.equals("LBL")) {
count++;
assertEquals("LBL size", 27645, size);
} else if (ext.equals("NET")) {
count++;
assertEquals("NET size", 73850, size);
} else if (ext.equals("NOD")) {
count++;
assertEquals("NOD size", 195187, size);
}
}
assertTrue("enough checks run", count == 5);
fs = ImgFS.openFs(Args.DEF_MAP_FILENAME2);
assertNotNull("file exists", fs);
entries = fs.list();
count = 0;
for (DirectoryEntry ent : entries) {
String ext = ent.getExt();
int size = ent.getSize();
if (ext.equals("RGN")) {
count++;
assertThat("RGN size", size, new RangeMatcher(2934));
} else if (ext.equals("TRE")) {
count++;
assertEquals("TRE size", 594, size);
} else if (ext.equals("LBL")) {
count++;
assertEquals("LBL size", 957, size);
} else if (ext.equals("NET")) {
count++;
assertEquals("NET size", 1280, size);
} else if (ext.equals("NOD")) {
count++;
assertEquals("NOD size", 3114, size);
}
}
assertTrue("enough checks run", count == 5);
}
| public void testSize() throws FileNotFoundException {
Main.main(new String[]{
Args.TEST_STYLE_ARG,
"--route",
Args.TEST_RESOURCE_OSM + "uk-test-1.osm.gz",
Args.TEST_RESOURCE_MP + "test1.mp"
});
FileSystem fs = ImgFS.openFs(Args.DEF_MAP_ID + ".img");
assertNotNull("file exists", fs);
List<DirectoryEntry> entries = fs.list();
int count = 0;
for (DirectoryEntry ent : entries) {
String ext = ent.getExt();
int size = ent.getSize();
if (ext.equals("RGN")) {
count++;
assertThat("RGN size", size, new RangeMatcher(141999));
} else if (ext.equals("TRE")) {
count++;
assertEquals("TRE size", 1341, size);
} else if (ext.equals("LBL")) {
count++;
assertEquals("LBL size", 27647, size);
} else if (ext.equals("NET")) {
count++;
assertEquals("NET size", 73850, size);
} else if (ext.equals("NOD")) {
count++;
assertEquals("NOD size", 195187, size);
}
}
assertTrue("enough checks run", count == 5);
fs = ImgFS.openFs(Args.DEF_MAP_FILENAME2);
assertNotNull("file exists", fs);
entries = fs.list();
count = 0;
for (DirectoryEntry ent : entries) {
String ext = ent.getExt();
int size = ent.getSize();
if (ext.equals("RGN")) {
count++;
assertThat("RGN size", size, new RangeMatcher(2934));
} else if (ext.equals("TRE")) {
count++;
assertEquals("TRE size", 594, size);
} else if (ext.equals("LBL")) {
count++;
assertEquals("LBL size", 957, size);
} else if (ext.equals("NET")) {
count++;
assertEquals("NET size", 1280, size);
} else if (ext.equals("NOD")) {
count++;
assertEquals("NOD size", 3114, size);
}
}
assertTrue("enough checks run", count == 5);
}
|
diff --git a/genomix/genomix-driver/src/main/java/edu/uci/ics/genomix/driver/GenomixDriver.java b/genomix/genomix-driver/src/main/java/edu/uci/ics/genomix/driver/GenomixDriver.java
index 871f21e11..2da521ce1 100644
--- a/genomix/genomix-driver/src/main/java/edu/uci/ics/genomix/driver/GenomixDriver.java
+++ b/genomix/genomix-driver/src/main/java/edu/uci/ics/genomix/driver/GenomixDriver.java
@@ -1,366 +1,367 @@
/*
* Copyright 2009-2013 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.genomix.driver;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.kohsuke.args4j.CmdLineException;
import edu.uci.ics.genomix.config.GenomixJobConf;
import edu.uci.ics.genomix.config.GenomixJobConf.Patterns;
import edu.uci.ics.genomix.hadoop.contrailgraphbuilding.GenomixHadoopDriver;
import edu.uci.ics.genomix.hadoop.converttofasta.ConvertToFasta;
import edu.uci.ics.genomix.hadoop.graph.GraphStatistics;
import edu.uci.ics.genomix.hyracks.graph.driver.GenomixHyracksDriver;
import edu.uci.ics.genomix.hyracks.graph.driver.GenomixHyracksDriver.Plan;
import edu.uci.ics.genomix.minicluster.DriverUtils;
import edu.uci.ics.genomix.minicluster.GenerateGraphViz;
import edu.uci.ics.genomix.minicluster.GenomixClusterManager;
import edu.uci.ics.genomix.minicluster.GenomixClusterManager.ClusterType;
import edu.uci.ics.genomix.pregelix.checker.SymmetryCheckerVertex;
import edu.uci.ics.genomix.pregelix.extractsubgraph.ExtractSubgraphVertex;
import edu.uci.ics.genomix.pregelix.format.CheckerOutputFormat;
import edu.uci.ics.genomix.pregelix.format.ExtractSubgraphOutputFormat;
import edu.uci.ics.genomix.pregelix.format.NodeToVertexInputFormat;
import edu.uci.ics.genomix.pregelix.operator.bridgeremove.BridgeRemoveVertex;
import edu.uci.ics.genomix.pregelix.operator.bubblemerge.ComplexBubbleMergeVertex;
import edu.uci.ics.genomix.pregelix.operator.bubblemerge.SimpleBubbleMergeVertex;
import edu.uci.ics.genomix.pregelix.operator.pathmerge.P1ForPathMergeVertex;
import edu.uci.ics.genomix.pregelix.operator.pathmerge.P4ForPathMergeVertex;
import edu.uci.ics.genomix.pregelix.operator.removelowcoverage.RemoveLowCoverageVertex;
import edu.uci.ics.genomix.pregelix.operator.scaffolding.ScaffoldingVertex;
import edu.uci.ics.genomix.pregelix.operator.splitrepeat.SplitRepeatVertex;
import edu.uci.ics.genomix.pregelix.operator.tipremove.TipRemoveVertex;
import edu.uci.ics.genomix.pregelix.operator.unrolltandemrepeat.UnrollTandemRepeat;
import edu.uci.ics.hyracks.api.exceptions.HyracksException;
import edu.uci.ics.pregelix.api.job.PregelixJob;
/**
* The main entry point for the Genomix assembler, a hyracks/pregelix/hadoop-based deBruijn assembler.
*/
public class GenomixDriver {
public static final Logger GENOMIX_ROOT_LOG = Logger.getLogger("edu.uci.ics.genomix"); // here only so we can control children loggers
private static final Logger LOG = Logger.getLogger(GenomixDriver.class.getName());
private String prevOutput;
private String curOutput;
private int stepNum;
private List<PregelixJob> pregelixJobs;
private boolean followingBuild = false; // need to adapt the graph immediately after building
private boolean runLocal = false;
private int numCoresPerMachine;
private int numMachines;
private GenomixClusterManager manager;
private GenomixHyracksDriver hyracksDriver;
private edu.uci.ics.pregelix.core.driver.Driver pregelixDriver;
@SuppressWarnings("deprecation")
private void setOutput(GenomixJobConf conf, Patterns step) {
prevOutput = curOutput;
curOutput = conf.get(GenomixJobConf.HDFS_WORK_PATH) + File.separator + String.format("%02d-", stepNum) + step;
FileInputFormat.setInputPaths(conf, new Path(prevOutput));
FileOutputFormat.setOutputPath(conf, new Path(curOutput));
}
private void addStep(GenomixJobConf conf, Patterns step) throws Exception {
// oh, java, why do you pain me so?
switch (step) {
case BUILD:
case BUILD_HYRACKS:
flushPendingJobs(conf);
buildGraphWithHyracks(conf);
break;
case BUILD_HADOOP:
flushPendingJobs(conf);
buildGraphWithHadoop(conf);
break;
case MERGE_P1:
queuePregelixJob(P1ForPathMergeVertex.getConfiguredJob(conf, P1ForPathMergeVertex.class));
break;
case MERGE_P2:
// queuePregelixJob(P2ForPathMergeVertex.getConfiguredJob(conf, P2ForPathMergeVertex.class));
break;
case MERGE:
case MERGE_P4:
queuePregelixJob(P4ForPathMergeVertex.getConfiguredJob(conf, P4ForPathMergeVertex.class));
break;
case UNROLL_TANDEM:
queuePregelixJob(UnrollTandemRepeat.getConfiguredJob(conf, UnrollTandemRepeat.class));
break;
case TIP_REMOVE:
queuePregelixJob(TipRemoveVertex.getConfiguredJob(conf, TipRemoveVertex.class));
break;
case BUBBLE:
queuePregelixJob(SimpleBubbleMergeVertex.getConfiguredJob(conf, SimpleBubbleMergeVertex.class));
break;
case BUBBLE_COMPLEX:
queuePregelixJob(ComplexBubbleMergeVertex.getConfiguredJob(conf, ComplexBubbleMergeVertex.class));
break;
case LOW_COVERAGE:
queuePregelixJob(RemoveLowCoverageVertex.getConfiguredJob(conf, RemoveLowCoverageVertex.class));
break;
case BRIDGE:
queuePregelixJob(BridgeRemoveVertex.getConfiguredJob(conf, BridgeRemoveVertex.class));
break;
case SPLIT_REPEAT:
queuePregelixJob(SplitRepeatVertex.getConfiguredJob(conf, SplitRepeatVertex.class));
break;
case SCAFFOLD:
queuePregelixJob(ScaffoldingVertex.getConfiguredJob(conf, ScaffoldingVertex.class));
break;
case DUMP_FASTA:
flushPendingJobs(conf);
if (runLocal) {
DriverUtils.dumpGraph(conf, curOutput, "genome.fasta", followingBuild); //?? why curOutput TODO
curOutput = prevOutput; // use previous job's output
} else {
dumpGraphWithHadoop(conf, curOutput, numCoresPerMachine * numMachines);
if (Boolean.parseBoolean(conf.get(GenomixJobConf.GAGE)) == true) {
DriverUtils.dumpGraph(conf, curOutput, "genome.fasta", followingBuild);
}
curOutput = prevOutput;
}
break;
case CHECK_SYMMETRY:
queuePregelixJob(SymmetryCheckerVertex.getConfiguredJob(conf, SymmetryCheckerVertex.class));
curOutput = prevOutput; // use previous job's output
break;
case PLOT_SUBGRAPH:
String lastJobOutput = prevOutput;
queuePregelixJob(ExtractSubgraphVertex.getConfiguredJob(conf, ExtractSubgraphVertex.class));
// curOutput = prevOutput; // use previous job's output
flushPendingJobs(conf);
- curOutput = curOutput + "-PLOT-SUBGRAPH";
+ prevOutput = curOutput;
+ curOutput = prevOutput + "-PLOT-SUBGRAPH";
stepNum--;
String binaryDir = prevOutput;
//copy bin to local
GenomixClusterManager.copyBinToLocal(conf, curOutput, binaryDir);
//covert bin to graphviz
String graphvizDir = binaryDir + File.separator + "graphviz";
int graphType = Integer.parseInt(conf.get(GenomixJobConf.PLOT_SUBGRAPH_GRAPH_VERBOSITY));
GenerateGraphViz.convertBinToGraphViz(binaryDir + File.separator + "bin", graphvizDir, graphType);
LOG.info("Copying graphviz to local: " + graphvizDir);
curOutput = lastJobOutput; // use previous job's output
break;
case STATS:
flushPendingJobs(conf);
manager.startCluster(ClusterType.HADOOP);
curOutput = prevOutput + "-STATS";
stepNum--;
Counters counters = GraphStatistics.run(prevOutput, curOutput, conf);
GraphStatistics.saveGraphStats(curOutput, counters, conf);
GraphStatistics.drawStatistics(curOutput, counters, conf);
manager.stopCluster(ClusterType.HADOOP);
curOutput = prevOutput; // use previous job's output
break;
}
}
private void buildGraphWithHyracks(GenomixJobConf conf) throws Exception {
LOG.info("Building Graph using Hyracks...");
manager.startCluster(ClusterType.HYRACKS);
GenomixJobConf.tick("buildGraphWithHyracks");
String hyracksIP = conf.get(GenomixJobConf.IP_ADDRESS);
int hyracksPort = Integer.parseInt(conf.get(GenomixJobConf.PORT));
hyracksDriver = new GenomixHyracksDriver(hyracksIP, hyracksPort, numCoresPerMachine);
hyracksDriver.runJob(conf, Plan.BUILD_DEBRUIJN_GRAPH, Boolean.parseBoolean(conf.get(GenomixJobConf.PROFILE)));
followingBuild = true;
manager.stopCluster(ClusterType.HYRACKS);
LOG.info("Building the graph took " + GenomixJobConf.tock("buildGraphWithHyracks") + "ms");
}
private void buildGraphWithHadoop(GenomixJobConf conf) throws Exception {
LOG.info("Building Graph using Hadoop...");
manager.startCluster(ClusterType.HADOOP);
GenomixJobConf.tick("buildGraphWithHadoop");
GenomixHadoopDriver hadoopDriver = new GenomixHadoopDriver();
hadoopDriver.run(prevOutput, curOutput, numCoresPerMachine * numMachines,
Integer.parseInt(conf.get(GenomixJobConf.KMER_LENGTH)), 4 * 100000, true, conf);
followingBuild = true;
manager.stopCluster(ClusterType.HADOOP);
LOG.info("Building the graph took " + GenomixJobConf.tock("buildGraphWithHadoop") + "ms");
}
private void queuePregelixJob(PregelixJob job) {
if (followingBuild) {
// if (P2ForPathMergeVertex.class.equals(BspUtils.getVertexClass(job.getConfiguration()))) {
// job.setVertexInputFormatClass(P2InitialGraphCleanInputFormat.class);
// } else {
job.setVertexInputFormatClass(NodeToVertexInputFormat.class);
// }
}
if (job.getClass().equals(SymmetryCheckerVertex.class)) {
job.setVertexOutputFormatClass(CheckerOutputFormat.class);
}
if (job.getClass().equals(ExtractSubgraphVertex.class)) {
job.setVertexOutputFormatClass(ExtractSubgraphOutputFormat.class);
}
pregelixJobs.add(job);
followingBuild = false;
}
/**
* Run any queued pregelix jobs.
* Pregelix and non-Pregelix jobs may be interleaved, so we run whatever's waiting.
*/
private void flushPendingJobs(GenomixJobConf conf) throws Exception {
if (pregelixJobs.size() > 0) {
manager.startCluster(ClusterType.PREGELIX);
pregelixDriver = new edu.uci.ics.pregelix.core.driver.Driver(this.getClass());
String pregelixIP = conf.get(GenomixJobConf.IP_ADDRESS);
int pregelixPort = Integer.parseInt(conf.get(GenomixJobConf.PORT));
// if the user wants to, we can save the intermediate results to HDFS (running each job individually)
// this would let them resume at arbitrary points of the pipeline
if (Boolean.parseBoolean(conf.get(GenomixJobConf.SAVE_INTERMEDIATE_RESULTS))) {
LOG.info("Starting pregelix job series (saving intermediate results)...");
GenomixJobConf.tick("pregelix-runJob-one-by-one");
for (int i = 0; i < pregelixJobs.size(); i++) {
LOG.info("Starting job " + pregelixJobs.get(i).getJobName());
GenomixJobConf.tick("pregelix-job");
pregelixDriver.runJob(pregelixJobs.get(i), pregelixIP, pregelixPort);
LOG.info("Finished job " + pregelixJobs.get(i).getJobName() + " in "
+ GenomixJobConf.tock("pregelix-job"));
}
LOG.info("Finished job series in " + GenomixJobConf.tock("pregelix-runJob-one-by-one"));
} else {
LOG.info("Starting pregelix job series (not saving intermediate results...");
GenomixJobConf.tick("pregelix-runJobs");
pregelixDriver.runJobs(pregelixJobs, pregelixIP, pregelixPort);
LOG.info("Finished job series in " + GenomixJobConf.tock("pregelix-runJobs"));
}
manager.stopCluster(ClusterType.PREGELIX);
pregelixJobs.clear();
}
}
private void dumpGraphWithHadoop(GenomixJobConf conf, String outputPath, int numReducers) throws Exception {
LOG.info("Building dump Graph using Hadoop...");
manager.startCluster(ClusterType.HADOOP);
GenomixJobConf.tick("dumpGraphWithHadoop");
ConvertToFasta.run(outputPath, numReducers, conf);
System.out.println("Finished dumping Graph");
manager.stopCluster(ClusterType.HADOOP);
LOG.info("Dumping the graph took " + GenomixJobConf.tock("dumpGraphWithHadoop") + "ms");
}
private void initGenomix(GenomixJobConf conf) throws Exception {
GenomixJobConf.setGlobalStaticConstants(conf);
DriverUtils.updateCCProperties(conf);
numCoresPerMachine = DriverUtils.getNumCoresPerMachine(conf);
numMachines = DriverUtils.getSlaveList(conf).length;
followingBuild = Boolean.parseBoolean(conf.get(GenomixJobConf.FOLLOWS_GRAPH_BUILD));
pregelixJobs = new ArrayList<PregelixJob>();
stepNum = 0;
runLocal = Boolean.parseBoolean(conf.get(GenomixJobConf.RUN_LOCAL));
manager = new GenomixClusterManager(runLocal, conf);
manager.stopCluster(ClusterType.HYRACKS); // shut down any existing NCs and CCs
}
public void runGenomix(GenomixJobConf conf) throws NumberFormatException, HyracksException, Exception {
LOG.info("Starting Genomix Assembler Pipeline...");
GenomixJobConf.tick("runGenomix");
initGenomix(conf);
String localInput = conf.get(GenomixJobConf.LOCAL_INPUT_DIR);
if (localInput != null) {
conf.set(GenomixJobConf.INITIAL_INPUT_DIR, conf.get(GenomixJobConf.HDFS_WORK_PATH) + File.separator
+ "00-initial-input-from-genomix-driver");
GenomixClusterManager.copyLocalToHDFS(conf, localInput, conf.get(GenomixJobConf.INITIAL_INPUT_DIR));
}
curOutput = conf.get(GenomixJobConf.INITIAL_INPUT_DIR);
// currently, we just iterate over the jobs set in conf[PIPELINE_ORDER]. In the future, we may want more logic to iterate multiple times, etc
String pipelineSteps = conf.get(GenomixJobConf.PIPELINE_ORDER);
for (Patterns step : Patterns.arrayFromString(pipelineSteps)) {
stepNum++;
setOutput(conf, step);
addStep(conf, step);
}
flushPendingJobs(conf);
if (conf.get(GenomixJobConf.LOCAL_OUTPUT_DIR) != null)
GenomixClusterManager.copyBinToLocal(conf, curOutput, conf.get(GenomixJobConf.LOCAL_OUTPUT_DIR));
if (conf.get(GenomixJobConf.FINAL_OUTPUT_DIR) != null)
FileSystem.get(conf).rename(new Path(curOutput), new Path(GenomixJobConf.FINAL_OUTPUT_DIR));
LOG.info("Finished the Genomix Assembler Pipeline in " + GenomixJobConf.tock("runGenomix") + "ms!");
}
public static void main(String[] args) throws NumberFormatException, HyracksException, Exception {
String[] myArgs = { "-runLocal", "true", "-kmerLength", "55",
// "-saveIntermediateResults", "true",
// "-localInput", "../genomix-pregelix/data/input/reads/synthetic/",
"-localInput", "tail600000",
// "-localInput", "/home/wbiesing/code/biggerInput",
// "-hdfsInput", "/home/wbiesing/code/hyracks/genomix/genomix-driver/genomix_out/01-BUILD_HADOOP",
// "-localInput", "/home/wbiesing/code/hyracks/genomix/genomix-pregelix/data/input/reads/test",
// "-localInput", "output-build/bin",
// "-localOutput", "output-skip",
// "-pipelineOrder", "BUILD,MERGE",
// "-inputDir", "/home/wbiesing/code/hyracks/genomix/genomix-driver/graphbuild.binmerge",
// "-localInput", "../genomix-pregelix/data/TestSet/PathMerge/CyclePath/bin/part-00000",
// "-localOutput", "testout",
"-pipelineOrder", "BUILD_HYRACKS,MERGE",
// "-hyracksBuildOutputText", "true",
};
// allow Eclipse to run the maven-generated scripts
if (System.getProperty("app.home") == null)
System.setProperty("app.home", new File("target/appassembler").getAbsolutePath());
// Patterns.BUILD, Patterns.MERGE,
// Patterns.TIP_REMOVE, Patterns.MERGE,
// Patterns.BUBBLE, Patterns.MERGE,
GenomixJobConf conf;
try {
conf = GenomixJobConf.fromArguments(args);
} catch (CmdLineException ex) {
System.err.println("Usage: bin/genomix [options]\n");
ex.getParser().setUsageWidth(80);
ex.getParser().printUsage(System.err);
System.err.println("\nExample:");
System.err
.println("\tbin/genomix -kmerLength 55 -pipelineOrder BUILD_HYRACKS,MERGE,TIP_REMOVE,MERGE,BUBBLE,MERGE -localInput /path/to/readfiledir/\n");
System.err.println(ex.getMessage());
return;
}
// GenomixJobConf conf = GenomixJobConf.fromArguments(myArgs);
GenomixDriver driver = new GenomixDriver();
driver.runGenomix(conf);
}
}
| true | true | private void addStep(GenomixJobConf conf, Patterns step) throws Exception {
// oh, java, why do you pain me so?
switch (step) {
case BUILD:
case BUILD_HYRACKS:
flushPendingJobs(conf);
buildGraphWithHyracks(conf);
break;
case BUILD_HADOOP:
flushPendingJobs(conf);
buildGraphWithHadoop(conf);
break;
case MERGE_P1:
queuePregelixJob(P1ForPathMergeVertex.getConfiguredJob(conf, P1ForPathMergeVertex.class));
break;
case MERGE_P2:
// queuePregelixJob(P2ForPathMergeVertex.getConfiguredJob(conf, P2ForPathMergeVertex.class));
break;
case MERGE:
case MERGE_P4:
queuePregelixJob(P4ForPathMergeVertex.getConfiguredJob(conf, P4ForPathMergeVertex.class));
break;
case UNROLL_TANDEM:
queuePregelixJob(UnrollTandemRepeat.getConfiguredJob(conf, UnrollTandemRepeat.class));
break;
case TIP_REMOVE:
queuePregelixJob(TipRemoveVertex.getConfiguredJob(conf, TipRemoveVertex.class));
break;
case BUBBLE:
queuePregelixJob(SimpleBubbleMergeVertex.getConfiguredJob(conf, SimpleBubbleMergeVertex.class));
break;
case BUBBLE_COMPLEX:
queuePregelixJob(ComplexBubbleMergeVertex.getConfiguredJob(conf, ComplexBubbleMergeVertex.class));
break;
case LOW_COVERAGE:
queuePregelixJob(RemoveLowCoverageVertex.getConfiguredJob(conf, RemoveLowCoverageVertex.class));
break;
case BRIDGE:
queuePregelixJob(BridgeRemoveVertex.getConfiguredJob(conf, BridgeRemoveVertex.class));
break;
case SPLIT_REPEAT:
queuePregelixJob(SplitRepeatVertex.getConfiguredJob(conf, SplitRepeatVertex.class));
break;
case SCAFFOLD:
queuePregelixJob(ScaffoldingVertex.getConfiguredJob(conf, ScaffoldingVertex.class));
break;
case DUMP_FASTA:
flushPendingJobs(conf);
if (runLocal) {
DriverUtils.dumpGraph(conf, curOutput, "genome.fasta", followingBuild); //?? why curOutput TODO
curOutput = prevOutput; // use previous job's output
} else {
dumpGraphWithHadoop(conf, curOutput, numCoresPerMachine * numMachines);
if (Boolean.parseBoolean(conf.get(GenomixJobConf.GAGE)) == true) {
DriverUtils.dumpGraph(conf, curOutput, "genome.fasta", followingBuild);
}
curOutput = prevOutput;
}
break;
case CHECK_SYMMETRY:
queuePregelixJob(SymmetryCheckerVertex.getConfiguredJob(conf, SymmetryCheckerVertex.class));
curOutput = prevOutput; // use previous job's output
break;
case PLOT_SUBGRAPH:
String lastJobOutput = prevOutput;
queuePregelixJob(ExtractSubgraphVertex.getConfiguredJob(conf, ExtractSubgraphVertex.class));
// curOutput = prevOutput; // use previous job's output
flushPendingJobs(conf);
curOutput = curOutput + "-PLOT-SUBGRAPH";
stepNum--;
String binaryDir = prevOutput;
//copy bin to local
GenomixClusterManager.copyBinToLocal(conf, curOutput, binaryDir);
//covert bin to graphviz
String graphvizDir = binaryDir + File.separator + "graphviz";
int graphType = Integer.parseInt(conf.get(GenomixJobConf.PLOT_SUBGRAPH_GRAPH_VERBOSITY));
GenerateGraphViz.convertBinToGraphViz(binaryDir + File.separator + "bin", graphvizDir, graphType);
LOG.info("Copying graphviz to local: " + graphvizDir);
curOutput = lastJobOutput; // use previous job's output
break;
case STATS:
flushPendingJobs(conf);
manager.startCluster(ClusterType.HADOOP);
curOutput = prevOutput + "-STATS";
stepNum--;
Counters counters = GraphStatistics.run(prevOutput, curOutput, conf);
GraphStatistics.saveGraphStats(curOutput, counters, conf);
GraphStatistics.drawStatistics(curOutput, counters, conf);
manager.stopCluster(ClusterType.HADOOP);
curOutput = prevOutput; // use previous job's output
break;
}
}
| private void addStep(GenomixJobConf conf, Patterns step) throws Exception {
// oh, java, why do you pain me so?
switch (step) {
case BUILD:
case BUILD_HYRACKS:
flushPendingJobs(conf);
buildGraphWithHyracks(conf);
break;
case BUILD_HADOOP:
flushPendingJobs(conf);
buildGraphWithHadoop(conf);
break;
case MERGE_P1:
queuePregelixJob(P1ForPathMergeVertex.getConfiguredJob(conf, P1ForPathMergeVertex.class));
break;
case MERGE_P2:
// queuePregelixJob(P2ForPathMergeVertex.getConfiguredJob(conf, P2ForPathMergeVertex.class));
break;
case MERGE:
case MERGE_P4:
queuePregelixJob(P4ForPathMergeVertex.getConfiguredJob(conf, P4ForPathMergeVertex.class));
break;
case UNROLL_TANDEM:
queuePregelixJob(UnrollTandemRepeat.getConfiguredJob(conf, UnrollTandemRepeat.class));
break;
case TIP_REMOVE:
queuePregelixJob(TipRemoveVertex.getConfiguredJob(conf, TipRemoveVertex.class));
break;
case BUBBLE:
queuePregelixJob(SimpleBubbleMergeVertex.getConfiguredJob(conf, SimpleBubbleMergeVertex.class));
break;
case BUBBLE_COMPLEX:
queuePregelixJob(ComplexBubbleMergeVertex.getConfiguredJob(conf, ComplexBubbleMergeVertex.class));
break;
case LOW_COVERAGE:
queuePregelixJob(RemoveLowCoverageVertex.getConfiguredJob(conf, RemoveLowCoverageVertex.class));
break;
case BRIDGE:
queuePregelixJob(BridgeRemoveVertex.getConfiguredJob(conf, BridgeRemoveVertex.class));
break;
case SPLIT_REPEAT:
queuePregelixJob(SplitRepeatVertex.getConfiguredJob(conf, SplitRepeatVertex.class));
break;
case SCAFFOLD:
queuePregelixJob(ScaffoldingVertex.getConfiguredJob(conf, ScaffoldingVertex.class));
break;
case DUMP_FASTA:
flushPendingJobs(conf);
if (runLocal) {
DriverUtils.dumpGraph(conf, curOutput, "genome.fasta", followingBuild); //?? why curOutput TODO
curOutput = prevOutput; // use previous job's output
} else {
dumpGraphWithHadoop(conf, curOutput, numCoresPerMachine * numMachines);
if (Boolean.parseBoolean(conf.get(GenomixJobConf.GAGE)) == true) {
DriverUtils.dumpGraph(conf, curOutput, "genome.fasta", followingBuild);
}
curOutput = prevOutput;
}
break;
case CHECK_SYMMETRY:
queuePregelixJob(SymmetryCheckerVertex.getConfiguredJob(conf, SymmetryCheckerVertex.class));
curOutput = prevOutput; // use previous job's output
break;
case PLOT_SUBGRAPH:
String lastJobOutput = prevOutput;
queuePregelixJob(ExtractSubgraphVertex.getConfiguredJob(conf, ExtractSubgraphVertex.class));
// curOutput = prevOutput; // use previous job's output
flushPendingJobs(conf);
prevOutput = curOutput;
curOutput = prevOutput + "-PLOT-SUBGRAPH";
stepNum--;
String binaryDir = prevOutput;
//copy bin to local
GenomixClusterManager.copyBinToLocal(conf, curOutput, binaryDir);
//covert bin to graphviz
String graphvizDir = binaryDir + File.separator + "graphviz";
int graphType = Integer.parseInt(conf.get(GenomixJobConf.PLOT_SUBGRAPH_GRAPH_VERBOSITY));
GenerateGraphViz.convertBinToGraphViz(binaryDir + File.separator + "bin", graphvizDir, graphType);
LOG.info("Copying graphviz to local: " + graphvizDir);
curOutput = lastJobOutput; // use previous job's output
break;
case STATS:
flushPendingJobs(conf);
manager.startCluster(ClusterType.HADOOP);
curOutput = prevOutput + "-STATS";
stepNum--;
Counters counters = GraphStatistics.run(prevOutput, curOutput, conf);
GraphStatistics.saveGraphStats(curOutput, counters, conf);
GraphStatistics.drawStatistics(curOutput, counters, conf);
manager.stopCluster(ClusterType.HADOOP);
curOutput = prevOutput; // use previous job's output
break;
}
}
|
diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java
index 8d50f38f7e..66b4936bce 100644
--- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java
+++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java
@@ -1,156 +1,156 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.virtualbox.functions;
import static org.jclouds.scriptbuilder.domain.Statements.call;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.transform;
import java.net.URI;
import java.util.List;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import org.jclouds.ssh.SshClient;
import org.jclouds.virtualbox.Preconfiguration;
import org.jclouds.virtualbox.domain.IsoSpec;
import org.jclouds.virtualbox.domain.MasterSpec;
import org.jclouds.virtualbox.domain.VmSpec;
import org.jclouds.virtualbox.predicates.GuestAdditionsInstaller;
import org.jclouds.virtualbox.util.MachineController;
import org.jclouds.virtualbox.util.MachineUtils;
import org.virtualbox_4_1.IMachine;
import org.virtualbox_4_1.LockType;
import org.virtualbox_4_1.VirtualBoxManager;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.base.Supplier;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.inject.Inject;
@Singleton
public class CreateAndInstallVm implements Function<MasterSpec, IMachine> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
private final Supplier<VirtualBoxManager> manager;
private final CreateAndRegisterMachineFromIsoIfNotAlreadyExists createAndRegisterMachineFromIsoIfNotAlreadyExists;
private final GuestAdditionsInstaller guestAdditionsInstaller;
private final Predicate<SshClient> sshResponds;
private LoadingCache<IsoSpec, URI> preConfiguration;
private final Function<IMachine, SshClient> sshClientForIMachine;
private final MachineUtils machineUtils;
private final IMachineToNodeMetadata imachineToNodeMetadata;
private final MachineController machineController;
@Inject
public CreateAndInstallVm(
Supplier<VirtualBoxManager> manager,
CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists,
GuestAdditionsInstaller guestAdditionsInstaller,
IMachineToNodeMetadata imachineToNodeMetadata,
Predicate<SshClient> sshResponds,
Function<IMachine, SshClient> sshClientForIMachine,
MachineUtils machineUtils,
@Preconfiguration LoadingCache<IsoSpec, URI> preConfiguration, MachineController machineController) {
this.manager = manager;
this.createAndRegisterMachineFromIsoIfNotAlreadyExists = CreateAndRegisterMachineFromIsoIfNotAlreadyExists;
this.sshResponds = sshResponds;
this.sshClientForIMachine = sshClientForIMachine;
this.machineUtils = machineUtils;
this.preConfiguration = preConfiguration;
this.guestAdditionsInstaller = guestAdditionsInstaller;
this.imachineToNodeMetadata = imachineToNodeMetadata;
this.machineController = machineController;
}
@Override
public IMachine apply(MasterSpec masterSpec) {
VmSpec vmSpec = masterSpec.getVmSpec();
IsoSpec isoSpec = masterSpec.getIsoSpec();
String vmName = vmSpec.getVmName();
IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists
.apply(masterSpec);
// Launch machine and wait for it to come online
machineController.ensureMachineIsLaunched(vmName);
URI uri = preConfiguration.getUnchecked(isoSpec);
String installationKeySequence = isoSpec.getInstallationKeySequence()
.replace("PRECONFIGURATION_URL", uri.toASCIIString());
configureOsInstallationWithKeyboardSequence(vmName,
installationKeySequence);
SshClient client = sshClientForIMachine.apply(vm);
logger.debug(">> awaiting installation to finish node(%s)", vmName);
checkState(sshResponds.apply(client),
"timed out waiting for guest %s to be accessible via ssh",
vmName);
- //logger.debug(">> awaiting installation of guest additions on vm: %s", vmName);
- //checkState(guestAdditionsInstaller.apply(vm));
+ logger.debug(">> awaiting installation of guest additions on vm: %s", vmName);
+ checkState(guestAdditionsInstaller.apply(vm));
logger.debug(">> awaiting post-installation actions on vm: %s", vmName);
- NodeMetadata vmMetadata = imachineToNodeMetadata.apply(vm);
+// NodeMetadata vmMetadata = imachineToNodeMetadata.apply(vm);
- ListenableFuture<ExecResponse> execFuture =
- machineUtils.runScriptOnNode(vmMetadata, call("cleanupUdevIfNeeded"), RunScriptOptions.NONE);
+// ListenableFuture<ExecResponse> execFuture =
+// machineUtils.runScriptOnNode(vmMetadata, call("cleanupUdevIfNeeded"), RunScriptOptions.NONE);
- ExecResponse execResponse = Futures.getUnchecked(execFuture);
- checkState(execResponse.getExitStatus() == 0);
+// ExecResponse execResponse = Futures.getUnchecked(execFuture);
+// checkState(execResponse.getExitStatus() == 0);
logger.debug(
"<< installation of image complete. Powering down node(%s)",
vmName);
machineController.ensureMachineHasPowerDown(vmName);
return vm;
}
private void configureOsInstallationWithKeyboardSequence(String vmName,
String installationKeySequence) {
Iterable<List<Integer>> scancodelist = transform(Splitter.on(" ")
.split(installationKeySequence), new StringToKeyCode());
for (List<Integer> scancodes : scancodelist) {
machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared,
new SendScancodes(scancodes));
}
}
}
| false | true | public IMachine apply(MasterSpec masterSpec) {
VmSpec vmSpec = masterSpec.getVmSpec();
IsoSpec isoSpec = masterSpec.getIsoSpec();
String vmName = vmSpec.getVmName();
IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists
.apply(masterSpec);
// Launch machine and wait for it to come online
machineController.ensureMachineIsLaunched(vmName);
URI uri = preConfiguration.getUnchecked(isoSpec);
String installationKeySequence = isoSpec.getInstallationKeySequence()
.replace("PRECONFIGURATION_URL", uri.toASCIIString());
configureOsInstallationWithKeyboardSequence(vmName,
installationKeySequence);
SshClient client = sshClientForIMachine.apply(vm);
logger.debug(">> awaiting installation to finish node(%s)", vmName);
checkState(sshResponds.apply(client),
"timed out waiting for guest %s to be accessible via ssh",
vmName);
//logger.debug(">> awaiting installation of guest additions on vm: %s", vmName);
//checkState(guestAdditionsInstaller.apply(vm));
logger.debug(">> awaiting post-installation actions on vm: %s", vmName);
NodeMetadata vmMetadata = imachineToNodeMetadata.apply(vm);
ListenableFuture<ExecResponse> execFuture =
machineUtils.runScriptOnNode(vmMetadata, call("cleanupUdevIfNeeded"), RunScriptOptions.NONE);
ExecResponse execResponse = Futures.getUnchecked(execFuture);
checkState(execResponse.getExitStatus() == 0);
logger.debug(
"<< installation of image complete. Powering down node(%s)",
vmName);
machineController.ensureMachineHasPowerDown(vmName);
return vm;
}
| public IMachine apply(MasterSpec masterSpec) {
VmSpec vmSpec = masterSpec.getVmSpec();
IsoSpec isoSpec = masterSpec.getIsoSpec();
String vmName = vmSpec.getVmName();
IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists
.apply(masterSpec);
// Launch machine and wait for it to come online
machineController.ensureMachineIsLaunched(vmName);
URI uri = preConfiguration.getUnchecked(isoSpec);
String installationKeySequence = isoSpec.getInstallationKeySequence()
.replace("PRECONFIGURATION_URL", uri.toASCIIString());
configureOsInstallationWithKeyboardSequence(vmName,
installationKeySequence);
SshClient client = sshClientForIMachine.apply(vm);
logger.debug(">> awaiting installation to finish node(%s)", vmName);
checkState(sshResponds.apply(client),
"timed out waiting for guest %s to be accessible via ssh",
vmName);
logger.debug(">> awaiting installation of guest additions on vm: %s", vmName);
checkState(guestAdditionsInstaller.apply(vm));
logger.debug(">> awaiting post-installation actions on vm: %s", vmName);
// NodeMetadata vmMetadata = imachineToNodeMetadata.apply(vm);
// ListenableFuture<ExecResponse> execFuture =
// machineUtils.runScriptOnNode(vmMetadata, call("cleanupUdevIfNeeded"), RunScriptOptions.NONE);
// ExecResponse execResponse = Futures.getUnchecked(execFuture);
// checkState(execResponse.getExitStatus() == 0);
logger.debug(
"<< installation of image complete. Powering down node(%s)",
vmName);
machineController.ensureMachineHasPowerDown(vmName);
return vm;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.