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/contactlist/src/com/dmdirc/addons/contactlist/ContactListListener.java b/contactlist/src/com/dmdirc/addons/contactlist/ContactListListener.java index f7fcae6b..4cb5bbad 100644 --- a/contactlist/src/com/dmdirc/addons/contactlist/ContactListListener.java +++ b/contactlist/src/com/dmdirc/addons/contactlist/ContactListListener.java @@ -1,114 +1,114 @@ /* * Copyright (c) 2006-2014 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.addons.contactlist; import com.dmdirc.DMDircMBassador; import com.dmdirc.Query; import com.dmdirc.events.ChannelUserAwayEvent; import com.dmdirc.events.ChannelUserBackEvent; import com.dmdirc.events.FrameClosingEvent; import com.dmdirc.interfaces.GroupChat; import com.dmdirc.interfaces.NicklistListener; import com.dmdirc.parser.interfaces.ChannelClientInfo; import java.util.Collection; import net.engio.mbassy.listener.Handler; /** * Listens for contact list related events. */ public class ContactListListener implements NicklistListener { /** The group chat this listener is for. */ private final GroupChat groupChat; /** Event bus to register listeners with. */ private final DMDircMBassador eventBus; /** * Creates a new ContactListListener for the specified group chat. * * @param groupChat The group chat to show a contact list for */ public ContactListListener(final GroupChat groupChat) { this.groupChat = groupChat; this.eventBus = groupChat.getEventBus(); } /** * Adds all necessary listeners for this contact list listener to function. */ public void addListeners() { groupChat.addNicklistListener(this); eventBus.subscribe(this); } /** * Removes the listeners added by {@link #addListeners()}. */ public void removeListeners() { groupChat.removeNicklistListener(this); eventBus.unsubscribe(this); } @Override public void clientListUpdated(final Collection<ChannelClientInfo> clients) { for (ChannelClientInfo client : clients) { clientAdded(client); } } @Override public void clientListUpdated() { // Do nothing } @Override public void clientAdded(final ChannelClientInfo client) { - final Query query = groupChat.getConnection(). - getQuery(client.getClient().getNickname(), false); + final Query query = groupChat.getOptionalConnection().get() + .getQuery(client.getClient().getNickname(), false); query.setIcon("query-" + client.getClient().getAwayState().name().toLowerCase()); } @Override public void clientRemoved(final ChannelClientInfo client) { // Do nothing } @Handler public void handleUserAway(final ChannelUserAwayEvent event) { clientAdded(event.getUser()); } @Handler public void handleUserBack(final ChannelUserBackEvent event) { clientAdded(event.getUser()); } @Handler public void windowClosing(final FrameClosingEvent event) { removeListeners(); } }
true
true
public void clientAdded(final ChannelClientInfo client) { final Query query = groupChat.getConnection(). getQuery(client.getClient().getNickname(), false); query.setIcon("query-" + client.getClient().getAwayState().name().toLowerCase()); }
public void clientAdded(final ChannelClientInfo client) { final Query query = groupChat.getOptionalConnection().get() .getQuery(client.getClient().getNickname(), false); query.setIcon("query-" + client.getClient().getAwayState().name().toLowerCase()); }
diff --git a/opal-shell/src/main/java/org/obiba/opal/shell/commands/ReportCommand.java b/opal-shell/src/main/java/org/obiba/opal/shell/commands/ReportCommand.java index a10f6a0ae..6723fcba2 100644 --- a/opal-shell/src/main/java/org/obiba/opal/shell/commands/ReportCommand.java +++ b/opal-shell/src/main/java/org/obiba/opal/shell/commands/ReportCommand.java @@ -1,202 +1,202 @@ /******************************************************************************* * Copyright 2008(c) The OBiBa Consortium. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.shell.commands; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemException; import org.apache.velocity.app.VelocityEngine; import org.obiba.opal.core.cfg.ReportTemplate; import org.obiba.opal.reporting.service.ReportException; import org.obiba.opal.reporting.service.ReportService; import org.obiba.opal.shell.commands.options.ReportCommandOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.MailException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; import org.springframework.ui.velocity.VelocityEngineUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; @CommandUsage(description = "Generate a report based on the specified report template.", syntax = "Syntax: report --name TEMPLATE") public class ReportCommand extends AbstractOpalRuntimeDependentCommand<ReportCommandOptions> { // // Constants // private static final Logger log = LoggerFactory.getLogger(ReportCommand.class); private static final String DATE_FORMAT_PATTERN = "yyyyMMdd_HHmm"; private static final Map<String, String> formatFileExtension = ImmutableMap.of("HTML", "html", "PDF", "pdf", "EXCEL", "xls"); // // Instance Variables // @Autowired private ReportService reportService; @Autowired private MailSender mailSender; @Autowired private VelocityEngine velocityEngine; @Autowired @Value("${org.obiba.opal.public.url}") private String opalPublicUrl; @Autowired @Value("${org.obiba.opal.smtp.from}") private String fromAddress; // // AbstractOpalRuntimeDependentCommand Methods // @Override public int execute() { // Get the report template. String reportTemplateName = getOptions().getName(); ReportTemplate reportTemplate = this.getOpalRuntime().getOpalConfiguration().getReportTemplate(reportTemplateName); if(reportTemplate == null) { getShell().printf("Report template '%s' does not exist.\n", reportTemplateName); return 1; } - Date reportDate = new Date(); + Date reportDate = getCurrentTime(); try { FileObject reportOutput = getReportOutput(reportTemplateName, reportTemplate.getFormat(), reportDate); return renderAndSendEmail(reportTemplate, reportOutput); } catch(FileSystemException e) { getShell().printf("Cannot create report output: '/reports/%s/%s'", reportTemplateName, getReportFileName(reportTemplateName, reportTemplate.getFormat(), reportDate)); return 1; } } // // Methods // public void setReportService(ReportService reportService) { this.reportService = reportService; } public void setMailSender(MailSender mailSender) { this.mailSender = mailSender; } public void setOpalPublicUrl(String opalPublicUrl) { this.opalPublicUrl = opalPublicUrl; } public void setFromAddress(String fromAddress) { this.fromAddress = fromAddress; } @Override public String toString() { return "report -n " + getOptions().getName(); } private int renderAndSendEmail(ReportTemplate reportTemplate, FileObject reportOutput) throws FileSystemException { try { reportService.render(reportTemplate.getFormat(), reportTemplate.getParameters(), getLocalFile(getReportDesign(reportTemplate.getDesign())).getPath(), getLocalFile(reportOutput).getPath()); } catch(ReportException ex) { getShell().printf("Error rendering report: '%s'\n", ex.getMessage()); deleteFileSilently(reportOutput); return 1; } if(!reportTemplate.getEmailNotificationAddresses().isEmpty()) { sendEmailNotification(reportTemplate, reportOutput); } return 0; } private FileObject getReportDesign(String reportDesign) throws FileSystemException { return getFile(reportDesign); } private FileObject getReportOutput(String reportTemplateName, String reportFormat, Date reportDate) throws FileSystemException { String reportFileName = getReportFileName(reportTemplateName, reportFormat, reportDate); FileObject reportDir = getFile("/reports/" + reportTemplateName); reportDir.createFolder(); FileObject reportFile = reportDir.resolveFile(reportFileName); return reportFile; } private String getReportFileName(String reportTemplateName, String reportFormat, Date reportDate) { SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_PATTERN); String reportDateText = dateFormat.format(reportDate); return String.format("%s-%s.%s", reportTemplateName, reportDateText, formatFileExtension.get(reportFormat.toUpperCase())); } private void deleteFileSilently(FileObject file) { try { if(file.exists()) { file.delete(); } } catch(FileSystemException ex) { log.error("Could not delete file: {}", file.getName().getPath()); } } private void sendEmailNotification(ReportTemplate reportTemplate, FileObject reportOutput) { String reportTemplateName = reportTemplate.getName(); SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(fromAddress); message.setSubject("[Opal] Report: " + reportTemplateName); message.setText(getEmailNotificationText(reportTemplateName, reportOutput)); for(String emailAddress : reportTemplate.getEmailNotificationAddresses()) { message.setTo(emailAddress); try { mailSender.send(message); } catch(MailException ex) { getShell().printf("Email notification not sent: %s", ex.getMessage()); log.error("Email notification not sent: {}", ex.getMessage()); } } } private String getEmailNotificationText(String reportTemplateName, FileObject reportOutput) { Map<String, String> model = new HashMap<String, String>(); model.put("report_template", reportTemplateName); model.put("report_public_link", opalPublicUrl + "/ws/report/public/" + getOpalRuntime().getFileSystem().getObfuscatedPath(reportOutput)); return getMergedVelocityTemplate(model); } @VisibleForTesting String getMergedVelocityTemplate(Map<String, String> model) { return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "velocity/opal-reporting/report-email-notification.vm", model); } @VisibleForTesting Date getCurrentTime() { return new Date(); } }
true
true
public int execute() { // Get the report template. String reportTemplateName = getOptions().getName(); ReportTemplate reportTemplate = this.getOpalRuntime().getOpalConfiguration().getReportTemplate(reportTemplateName); if(reportTemplate == null) { getShell().printf("Report template '%s' does not exist.\n", reportTemplateName); return 1; } Date reportDate = new Date(); try { FileObject reportOutput = getReportOutput(reportTemplateName, reportTemplate.getFormat(), reportDate); return renderAndSendEmail(reportTemplate, reportOutput); } catch(FileSystemException e) { getShell().printf("Cannot create report output: '/reports/%s/%s'", reportTemplateName, getReportFileName(reportTemplateName, reportTemplate.getFormat(), reportDate)); return 1; } }
public int execute() { // Get the report template. String reportTemplateName = getOptions().getName(); ReportTemplate reportTemplate = this.getOpalRuntime().getOpalConfiguration().getReportTemplate(reportTemplateName); if(reportTemplate == null) { getShell().printf("Report template '%s' does not exist.\n", reportTemplateName); return 1; } Date reportDate = getCurrentTime(); try { FileObject reportOutput = getReportOutput(reportTemplateName, reportTemplate.getFormat(), reportDate); return renderAndSendEmail(reportTemplate, reportOutput); } catch(FileSystemException e) { getShell().printf("Cannot create report output: '/reports/%s/%s'", reportTemplateName, getReportFileName(reportTemplateName, reportTemplate.getFormat(), reportDate)); return 1; } }
diff --git a/src/com/RoboMobo/Map.java b/src/com/RoboMobo/Map.java index 2d3326e..c45bf8b 100644 --- a/src/com/RoboMobo/Map.java +++ b/src/com/RoboMobo/Map.java @@ -1,506 +1,506 @@ package com.RoboMobo; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.os.Message; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.concurrent.ExecutionException; /** * Created with IntelliJ IDEA. * User: Роман * Date: 31.07.13 * Time: 11:01 */ public class Map { public final int width; public final int height; public double corner1latt = 0; public double corner1long = 0; public double corner2latt = 0; public double corner2long = 0; public boolean corner1fixed; public boolean corner2fixed; public double basexlatt = 0; public double basexlong = 0; public double baseylatt = 0; public double baseylong = 0; public double det; public ArrayList<int[]> pickups; public Player p0; public Player p1; public float prevFilteredCompass = 0; public MapState state; public Point suspendTile; /** * Array of tile IDs. Every [width] indexes starts a new row. */ public short[][] tiles; public Map(int w, int h) { this.width = w; this.height = h; pickups = new ArrayList<int[]>(); corner1fixed = false; corner2fixed = false; tiles = new short[RMR.mapSideLength][RMR.mapSideLength]; for (int i = 0; i < RMR.mapSideLength; i++) { for (int j = 0; j < RMR.mapSideLength; j++) { tiles[i][j] = 0; } } for (int i = 0; i < 3; i++) { tiles[3][i] = 1; } for (int i = 2; i < 7; i++) { tiles[i][5] = 1; } for (int i = 0; i < 3; i++) { tiles[i][8] = 2; } state = MapState.PreGame; this.suspendTile = null; /*Runnable r = new Runnable() { @Override public void run() { Generation.generateRivers(tiles, width, height); } }; r.run();*/ } public void Update(long elapsedTime) { //Log.wtf("current coords", RMR.gps.last_latt + " " + RMR.gps.last_long); int[] coord = coordTransform(RMR.gps.last_latt, RMR.gps.last_long); if (coord != null) { this.p0.changePos(coord); } if (this.suspendTile != null && (Math.floor(this.p0.posX / 32.0) == this.suspendTile.x && Math.floor(this.p0.posY / 32.0) == this.suspendTile.y)) { this.suspendTile = null; this.state = MapState.Game; } if (RMR.state == RMR.GameState.ClientIngame || RMR.state == RMR.GameState.ServerIngame) { JSONObject pl = new JSONObject(); try { pl.put("X", p0.posX); pl.put("Y", p0.posY); } catch (JSONException e) { e.printStackTrace(); } JSONObject jobj = new JSONObject(); try { jobj.put("Player", pl); } catch (JSONException e) { e.printStackTrace(); } try { switch (RMR.net.getStatus()) { case FINISHED: JSONObject[] jb = RMR.net.get(); RMR.net = new Networking(RMR.net.ip, RMR.net.isServer); RMR.net.execute(jobj); if(jb==null) { break; } for (int i = 0; i < jb.length; i++) { JSONObject jo = jb[i]; if (jo.has("Player")) { this.p1.prevPosX = this.p1.posX; this.p1.prevPosY = this.p1.posY; this.p1.posX = jo.getJSONObject("Player").getInt("X"); this.p1.posY = jo.getJSONObject("Player").getInt("Y"); } } break; case PENDING: RMR.net.execute(jobj); break; } } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (ExecutionException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (JSONException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } if (state == MapState.Game) { if (this.p0.posX < 0 || this.p0.posY < 0 || Math.floor(this.p0.posX / 32.0) >= RMR.mapSideLength || Math.floor(this.p0.posY / 32.0) >= RMR.mapSideLength) { this.state = MapState.Suspended; this.suspendTile = new Point(); this.suspendTile.set((int) Math.floor(this.p0.prevPosX / 32.0), (int) Math.floor(this.p0.prevPosY / 32.0)); } else if (this.tiles[((int) Math.floor(this.p0.posX / 32.0))][((int) Math.floor(this.p0.posY / 32.0))] != 0) { this.state = MapState.Suspended; this.suspendTile = new Point(); this.suspendTile.set((int) Math.floor(this.p0.prevPosX / 32.0), (int) Math.floor(this.p0.prevPosY / 32.0)); } for (int i = 0; i < this.pickups.size(); i++) { this.pickups.get(i)[2] -= elapsedTime; if (this.pickups.get(i)[2] <= 0) { pickups.remove(this.pickups.get(i)); } if ((Math.floor(this.p0.posX / 32.0) == this.pickups.get(i)[0]) && (Math.floor(this.p0.posY / 32.0) == this.pickups.get(i)[1])) { /*Log.wtf("Pl", Math.floor(this.player1.posX / 32) + " " + Math.floor(this.player1.posY / 32)); Log.wtf("Pick", this.pickups.get(i)[0] + " " + this.pickups.get(i)[1]);*/ this.p0.addScore(this.pickups.get(i)[4]); this.pickups.remove(i); Message msg = new Message(); msg.arg1 = this.p0.score; ((ActivityMain) RMR.am).HandlerUIUpdate.sendMessage(msg); } } if (this.pickups.size() < 10 && RMR.rnd.nextInt(20) == 1) { int x = RMR.rnd.nextInt(RMR.mapSideLength); int y = RMR.rnd.nextInt(RMR.mapSideLength); if (this.tiles[x][y] == 0) { int t = RMR.rnd.nextInt(20000) + 20000; pickups.add(new int[]{x, y, t, t, 1 + RMR.rnd.nextInt(2)}); //[x, y, timer, lifetime, type] } } /*TextView text = (TextView) RMR.am.findViewById(R.id.tv_score); text.setText("Очки: "+this.player1.score);*/ } } public void Draw() { Paint pa = new Paint(); RMR.c.save(); { int mapW = this.width * 32; int mapH = this.height * 32; Player p = this.p0; //double mapRotation = Math.toDegrees(Math.asin(Math.abs(this.basexlong - this.baseylong) / Math.sqrt(Math.pow(this.basexlatt - this.baseylatt, 2) + Math.pow(this.basexlong - this.baseylong, 2)))); double mapRotation = Math.toDegrees(Math.asin(Math.abs(p.posY - p.prevPosY) / Math.sqrt(Math.pow(p.posX - p.prevPosX, 2) + Math.pow(p.posY - p.prevPosY, 2)))); if ((p.posX - p.prevPosX) >= 0) { if ((p.posY - p.prevPosY) >= 0) { mapRotation = 180 - mapRotation; } else { mapRotation = 180 + mapRotation; } } else { if ((p.posY - p.prevPosY) < 0) { mapRotation = 360 - mapRotation; } } RMR.c.scale(((float) RMR.sw.getWidth() / (float) mapH), ((float) RMR.sw.getWidth() / (float) mapH)); Rect src = new Rect(); Rect dst = new Rect(); float α = 0.9f; RMR.c.save(); { RMR.c.translate(RMR.mapSideLength * 32 / 2, RMR.mapSideLength * 32 / 2); /*if(this.corner1fixed && this.corner2fixed)*/ double delta = prevFilteredCompass + Math.toDegrees(RMR.compass.orientationData[0]); Log.d("compass", delta + " " + prevFilteredCompass + " " + (Math.abs(delta) > 180)); delta = (delta > 180) ? (delta - 360) : ((delta < -180) ? (delta + 360) : delta); prevFilteredCompass = (float) (α * delta - Math.toDegrees(RMR.compass.orientationData[0])); if (this.corner1fixed && this.corner2fixed) { RMR.c.rotate((!Double.isNaN(mapRotation) ? (float) mapRotation : 0) + prevFilteredCompass/*-(float) playerAngle*/, 0, 0); } RMR.c.translate(-this.p0.posY, -this.p0.posX); pa.setColor(Color.DKGRAY); RMR.c.save(); { /*for (int i = 0; i < RMR.currentMap.width; i++) { for (int j = 0; j < RMR.currentMap.height; j++) { RMR.c.save(); { RMR.c.translate(i * 32, j * 32); RMR.c.drawLine(0, 0, 32, 0, pa); RMR.c.drawLine(0, 0, 0, 32, pa); RMR.c.drawLine(32, 32, 32, 0, pa); RMR.c.drawLine(32, 32, 0, 32, pa); } RMR.c.restore(); } }*/ RMR.c.drawLine(0, 0, 32 * this.width, 0, pa); RMR.c.drawLine(0, 0, 0, 32 * this.height, pa); RMR.c.drawLine(32 * this.width, 32 * this.height, 32 * this.width, 0, pa); RMR.c.drawLine(32 * this.width, 32 * this.height, 0, 32 * this.height, pa); } RMR.c.restore(); pa = new Paint(); RMR.c.save(); { if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.tile_0_iterator++; if(RMGR.tile_0_iterator == RMGR.TILE_0.length) RMGR.tile_0_iterator = 0; if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.tile_1_iterator++; if(RMGR.tile_1_iterator == RMGR.TILE_1.length) RMGR.tile_1_iterator = 0; for (int i = 0; i < this.height; i++) { for (int j = 0; j < this.width; j++) { switch (this.tiles[j][i]) { default: continue; case 1: RMR.c.save(); { int it = RMGR.tile_0_iterator + i + j; it %= RMGR.TILE_0.length; RMR.c.translate(i * 32, j * 32); src.set(0, 0, RMGR.TILE_0[it].getWidth(), RMGR.TILE_0[it].getHeight()); dst.set(0, 0, 32, 32); pa.setColor(Color.WHITE); RMR.c.drawBitmap(RMGR.TILE_0[it], src, dst, pa); } RMR.c.restore(); break; case 2: RMR.c.save(); { int it = RMGR.tile_1_iterator + i + j; it %= RMGR.TILE_1.length; RMR.c.translate(i * 32, j * 32); src.set(0, 0, RMGR.TILE_1[it].getWidth(), RMGR.TILE_1[it].getHeight()); dst.set(0, 0, 32, 32); pa.setColor(Color.WHITE); RMR.c.drawBitmap(RMGR.TILE_1[it], src, dst, pa); } RMR.c.restore(); break; } } } } RMR.c.restore(); RMR.c.save(); { if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.pickup_0_iterator++; if(RMGR.pickup_0_iterator == RMGR.PICKUP_0.length) RMGR.pickup_0_iterator = 0; if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.pickup_1_iterator++; if(RMGR.pickup_1_iterator == RMGR.PICKUP_1.length) RMGR.pickup_1_iterator = 0; for (int i = 0; i < this.pickups.size(); i++) { RMR.c.save(); { RMR.c.translate(this.pickups.get(i)[1] * 32, this.pickups.get(i)[0] * 32); pa.setAlpha((int) Math.floor(100 / ((float)this.pickups.get(i)[3] / ((float)this.pickups.get(i)[2] != 0 ? (float)this.pickups.get(i)[2] : 1)))); switch (this.pickups.get(i)[4]) { default: case 1: int it = (RMGR.pickup_0_iterator + this.pickups.get(i)[0] + this.pickups.get(i)[1]); it %= RMGR.PICKUP_0.length; src.set(0, 0, RMGR.PICKUP_0[it].getWidth(), RMGR.PICKUP_0[it].getHeight()); dst.set(4, 4, 28, 28); RMR.c.drawBitmap(RMGR.PICKUP_0[it], src, dst, pa); break; case 2: int it1 = (RMGR.pickup_1_iterator + this.pickups.get(i)[0] + this.pickups.get(i)[1]); it1 %= RMGR.PICKUP_1.length; src.set(0, 0, RMGR.PICKUP_1[it1].getWidth(), RMGR.PICKUP_1[it1].getHeight()); dst.set(4, 4, 28, 28); RMR.c.drawBitmap(RMGR.PICKUP_1[it1], src, dst, pa); break; } } RMR.c.restore(); } } RMR.c.restore(); pa = new Paint(); if (this.state == MapState.Suspended) { RMR.c.save(); { pa.setColor(Color.BLACK); pa.setAlpha(80); RMR.c.drawRect(0, 0, RMR.mapSideLength * 32, this.suspendTile.x * 32, pa); RMR.c.drawRect((this.suspendTile.y + 1) * 32, this.suspendTile.x * 32, RMR.mapSideLength * 32, (this.suspendTile.x + 1) * 32, pa); RMR.c.drawRect(0, this.suspendTile.x * 32, this.suspendTile.y * 32, (this.suspendTile.x + 1) * 32, pa); RMR.c.drawRect(0, (this.suspendTile.x + 1) * 32, RMR.mapSideLength * 32, RMR.mapSideLength * 32, pa); pa.setColor(Color.YELLOW); pa.setAlpha((int) Math.floor((Math.sin(System.currentTimeMillis() / 100) + 2) * 30)); RMR.c.drawRect(this.suspendTile.y * 32, this.suspendTile.x * 32, (this.suspendTile.y + 1) * 32, (this.suspendTile.x + 1) * 32, pa); } RMR.c.restore(); } RMR.c.save(); { pa.setColor(Color.WHITE); - RMR.c.translate(p1.posY * 32, p1.posX * 32); + RMR.c.translate(p1.posY, p1.posX); src.set(0, 0, RMGR.CHAR_0.getWidth(), RMGR.CHAR_0.getHeight()); dst.set(-12, -12, 12, 12); RMR.c.drawBitmap(RMGR.CHAR_0, src, dst, pa); } RMR.c.restore(); } RMR.c.restore(); RMR.c.save(); { pa.setColor(Color.WHITE); RMR.c.translate(RMR.mapSideLength * 32 / 2, RMR.mapSideLength * 32 / 2); src.set(0, 0, RMGR.CHAR_0.getWidth(), RMGR.CHAR_0.getHeight()); dst.set(-12, -12, 12, 12); RMR.c.drawBitmap(RMGR.CHAR_0, src, dst, pa); } RMR.c.restore(); } RMR.c.restore(); } public void fixCorner1(double latt, double longt) { if (corner1fixed) { return; } corner1latt = latt; corner1long = longt; corner1fixed = true; } public void fixCorner2(double latt, double longt) { if (corner2fixed) { return; } corner2latt = latt; corner2long = longt; corner2fixed = true; double dbaseLatt = (corner2latt - corner1latt) / Math.sqrt((corner2latt - corner1latt) * (corner2latt - corner1latt) + (corner2long - corner1long) * (corner2long - corner1long)); double dbaseLong = (corner2long - corner1long) / Math.sqrt((corner2latt - corner1latt) * (corner2latt - corner1latt) + (corner2long - corner1long) * (corner2long - corner1long)); basexlatt = (dbaseLatt / 2 - dbaseLong / 2) * Math.sqrt(2); basexlong = (dbaseLong / 2 + dbaseLatt / 2) * Math.sqrt(2); baseylatt = (dbaseLatt / 2 + dbaseLong / 2) * Math.sqrt(2); baseylong = (dbaseLong / 2 - dbaseLatt / 2) * Math.sqrt(2); det = basexlatt * baseylong - basexlong * baseylatt; this.p0.posX = 32 * (RMR.mapSideLength - 1); this.p0.posY = 32 * (RMR.mapSideLength - 1); //Log.wtf("dbase",Double.toString(Math.sqrt(dbaseLatt*dbaseLatt+dbaseLong*dbaseLong))); //Log.wtf("basex",Double.toString(Math.sqrt(basexlatt*basexlatt+baseylong*baseylong))); //Log.wtf("basey",Double.toString(Math.sqrt(baseylatt*baseylatt+baseylong*baseylong))); } public int[] coordTransform(double latt, double longt) { if (!(corner1fixed && corner2fixed)) { return null; } double relLatt = latt - corner1latt; double relLong = longt - corner1long; int[] coord = new int[2]; coord[0] = (int) ((baseylong * relLatt / det - baseylatt * relLong / det) * Math.sqrt((2048 * RMR.mapSideLength * RMR.mapSideLength) / ((corner2latt - corner1latt) * (corner2latt - corner1latt) + (corner2long - corner1long) * (corner2long - corner1long)))); coord[1] = (int) ((-basexlong * relLatt / det + basexlatt * relLong / det) * Math.sqrt((2048 * RMR.mapSideLength * RMR.mapSideLength) / ((corner2latt - corner1latt) * (corner2latt - corner1latt) + (corner2long - corner1long) * (corner2long - corner1long)))); return coord; } public enum MapState { Invalid, PreGame, Game, Suspended, PostGame } }
true
true
public void Draw() { Paint pa = new Paint(); RMR.c.save(); { int mapW = this.width * 32; int mapH = this.height * 32; Player p = this.p0; //double mapRotation = Math.toDegrees(Math.asin(Math.abs(this.basexlong - this.baseylong) / Math.sqrt(Math.pow(this.basexlatt - this.baseylatt, 2) + Math.pow(this.basexlong - this.baseylong, 2)))); double mapRotation = Math.toDegrees(Math.asin(Math.abs(p.posY - p.prevPosY) / Math.sqrt(Math.pow(p.posX - p.prevPosX, 2) + Math.pow(p.posY - p.prevPosY, 2)))); if ((p.posX - p.prevPosX) >= 0) { if ((p.posY - p.prevPosY) >= 0) { mapRotation = 180 - mapRotation; } else { mapRotation = 180 + mapRotation; } } else { if ((p.posY - p.prevPosY) < 0) { mapRotation = 360 - mapRotation; } } RMR.c.scale(((float) RMR.sw.getWidth() / (float) mapH), ((float) RMR.sw.getWidth() / (float) mapH)); Rect src = new Rect(); Rect dst = new Rect(); float α = 0.9f; RMR.c.save(); { RMR.c.translate(RMR.mapSideLength * 32 / 2, RMR.mapSideLength * 32 / 2); /*if(this.corner1fixed && this.corner2fixed)*/ double delta = prevFilteredCompass + Math.toDegrees(RMR.compass.orientationData[0]); Log.d("compass", delta + " " + prevFilteredCompass + " " + (Math.abs(delta) > 180)); delta = (delta > 180) ? (delta - 360) : ((delta < -180) ? (delta + 360) : delta); prevFilteredCompass = (float) (α * delta - Math.toDegrees(RMR.compass.orientationData[0])); if (this.corner1fixed && this.corner2fixed) { RMR.c.rotate((!Double.isNaN(mapRotation) ? (float) mapRotation : 0) + prevFilteredCompass/*-(float) playerAngle*/, 0, 0); } RMR.c.translate(-this.p0.posY, -this.p0.posX); pa.setColor(Color.DKGRAY); RMR.c.save(); { /*for (int i = 0; i < RMR.currentMap.width; i++) { for (int j = 0; j < RMR.currentMap.height; j++) { RMR.c.save(); { RMR.c.translate(i * 32, j * 32); RMR.c.drawLine(0, 0, 32, 0, pa); RMR.c.drawLine(0, 0, 0, 32, pa); RMR.c.drawLine(32, 32, 32, 0, pa); RMR.c.drawLine(32, 32, 0, 32, pa); } RMR.c.restore(); } }*/ RMR.c.drawLine(0, 0, 32 * this.width, 0, pa); RMR.c.drawLine(0, 0, 0, 32 * this.height, pa); RMR.c.drawLine(32 * this.width, 32 * this.height, 32 * this.width, 0, pa); RMR.c.drawLine(32 * this.width, 32 * this.height, 0, 32 * this.height, pa); } RMR.c.restore(); pa = new Paint(); RMR.c.save(); { if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.tile_0_iterator++; if(RMGR.tile_0_iterator == RMGR.TILE_0.length) RMGR.tile_0_iterator = 0; if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.tile_1_iterator++; if(RMGR.tile_1_iterator == RMGR.TILE_1.length) RMGR.tile_1_iterator = 0; for (int i = 0; i < this.height; i++) { for (int j = 0; j < this.width; j++) { switch (this.tiles[j][i]) { default: continue; case 1: RMR.c.save(); { int it = RMGR.tile_0_iterator + i + j; it %= RMGR.TILE_0.length; RMR.c.translate(i * 32, j * 32); src.set(0, 0, RMGR.TILE_0[it].getWidth(), RMGR.TILE_0[it].getHeight()); dst.set(0, 0, 32, 32); pa.setColor(Color.WHITE); RMR.c.drawBitmap(RMGR.TILE_0[it], src, dst, pa); } RMR.c.restore(); break; case 2: RMR.c.save(); { int it = RMGR.tile_1_iterator + i + j; it %= RMGR.TILE_1.length; RMR.c.translate(i * 32, j * 32); src.set(0, 0, RMGR.TILE_1[it].getWidth(), RMGR.TILE_1[it].getHeight()); dst.set(0, 0, 32, 32); pa.setColor(Color.WHITE); RMR.c.drawBitmap(RMGR.TILE_1[it], src, dst, pa); } RMR.c.restore(); break; } } } } RMR.c.restore(); RMR.c.save(); { if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.pickup_0_iterator++; if(RMGR.pickup_0_iterator == RMGR.PICKUP_0.length) RMGR.pickup_0_iterator = 0; if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.pickup_1_iterator++; if(RMGR.pickup_1_iterator == RMGR.PICKUP_1.length) RMGR.pickup_1_iterator = 0; for (int i = 0; i < this.pickups.size(); i++) { RMR.c.save(); { RMR.c.translate(this.pickups.get(i)[1] * 32, this.pickups.get(i)[0] * 32); pa.setAlpha((int) Math.floor(100 / ((float)this.pickups.get(i)[3] / ((float)this.pickups.get(i)[2] != 0 ? (float)this.pickups.get(i)[2] : 1)))); switch (this.pickups.get(i)[4]) { default: case 1: int it = (RMGR.pickup_0_iterator + this.pickups.get(i)[0] + this.pickups.get(i)[1]); it %= RMGR.PICKUP_0.length; src.set(0, 0, RMGR.PICKUP_0[it].getWidth(), RMGR.PICKUP_0[it].getHeight()); dst.set(4, 4, 28, 28); RMR.c.drawBitmap(RMGR.PICKUP_0[it], src, dst, pa); break; case 2: int it1 = (RMGR.pickup_1_iterator + this.pickups.get(i)[0] + this.pickups.get(i)[1]); it1 %= RMGR.PICKUP_1.length; src.set(0, 0, RMGR.PICKUP_1[it1].getWidth(), RMGR.PICKUP_1[it1].getHeight()); dst.set(4, 4, 28, 28); RMR.c.drawBitmap(RMGR.PICKUP_1[it1], src, dst, pa); break; } } RMR.c.restore(); } } RMR.c.restore(); pa = new Paint(); if (this.state == MapState.Suspended) { RMR.c.save(); { pa.setColor(Color.BLACK); pa.setAlpha(80); RMR.c.drawRect(0, 0, RMR.mapSideLength * 32, this.suspendTile.x * 32, pa); RMR.c.drawRect((this.suspendTile.y + 1) * 32, this.suspendTile.x * 32, RMR.mapSideLength * 32, (this.suspendTile.x + 1) * 32, pa); RMR.c.drawRect(0, this.suspendTile.x * 32, this.suspendTile.y * 32, (this.suspendTile.x + 1) * 32, pa); RMR.c.drawRect(0, (this.suspendTile.x + 1) * 32, RMR.mapSideLength * 32, RMR.mapSideLength * 32, pa); pa.setColor(Color.YELLOW); pa.setAlpha((int) Math.floor((Math.sin(System.currentTimeMillis() / 100) + 2) * 30)); RMR.c.drawRect(this.suspendTile.y * 32, this.suspendTile.x * 32, (this.suspendTile.y + 1) * 32, (this.suspendTile.x + 1) * 32, pa); } RMR.c.restore(); } RMR.c.save(); { pa.setColor(Color.WHITE); RMR.c.translate(p1.posY * 32, p1.posX * 32); src.set(0, 0, RMGR.CHAR_0.getWidth(), RMGR.CHAR_0.getHeight()); dst.set(-12, -12, 12, 12); RMR.c.drawBitmap(RMGR.CHAR_0, src, dst, pa); } RMR.c.restore(); } RMR.c.restore(); RMR.c.save(); { pa.setColor(Color.WHITE); RMR.c.translate(RMR.mapSideLength * 32 / 2, RMR.mapSideLength * 32 / 2); src.set(0, 0, RMGR.CHAR_0.getWidth(), RMGR.CHAR_0.getHeight()); dst.set(-12, -12, 12, 12); RMR.c.drawBitmap(RMGR.CHAR_0, src, dst, pa); } RMR.c.restore(); } RMR.c.restore(); }
public void Draw() { Paint pa = new Paint(); RMR.c.save(); { int mapW = this.width * 32; int mapH = this.height * 32; Player p = this.p0; //double mapRotation = Math.toDegrees(Math.asin(Math.abs(this.basexlong - this.baseylong) / Math.sqrt(Math.pow(this.basexlatt - this.baseylatt, 2) + Math.pow(this.basexlong - this.baseylong, 2)))); double mapRotation = Math.toDegrees(Math.asin(Math.abs(p.posY - p.prevPosY) / Math.sqrt(Math.pow(p.posX - p.prevPosX, 2) + Math.pow(p.posY - p.prevPosY, 2)))); if ((p.posX - p.prevPosX) >= 0) { if ((p.posY - p.prevPosY) >= 0) { mapRotation = 180 - mapRotation; } else { mapRotation = 180 + mapRotation; } } else { if ((p.posY - p.prevPosY) < 0) { mapRotation = 360 - mapRotation; } } RMR.c.scale(((float) RMR.sw.getWidth() / (float) mapH), ((float) RMR.sw.getWidth() / (float) mapH)); Rect src = new Rect(); Rect dst = new Rect(); float α = 0.9f; RMR.c.save(); { RMR.c.translate(RMR.mapSideLength * 32 / 2, RMR.mapSideLength * 32 / 2); /*if(this.corner1fixed && this.corner2fixed)*/ double delta = prevFilteredCompass + Math.toDegrees(RMR.compass.orientationData[0]); Log.d("compass", delta + " " + prevFilteredCompass + " " + (Math.abs(delta) > 180)); delta = (delta > 180) ? (delta - 360) : ((delta < -180) ? (delta + 360) : delta); prevFilteredCompass = (float) (α * delta - Math.toDegrees(RMR.compass.orientationData[0])); if (this.corner1fixed && this.corner2fixed) { RMR.c.rotate((!Double.isNaN(mapRotation) ? (float) mapRotation : 0) + prevFilteredCompass/*-(float) playerAngle*/, 0, 0); } RMR.c.translate(-this.p0.posY, -this.p0.posX); pa.setColor(Color.DKGRAY); RMR.c.save(); { /*for (int i = 0; i < RMR.currentMap.width; i++) { for (int j = 0; j < RMR.currentMap.height; j++) { RMR.c.save(); { RMR.c.translate(i * 32, j * 32); RMR.c.drawLine(0, 0, 32, 0, pa); RMR.c.drawLine(0, 0, 0, 32, pa); RMR.c.drawLine(32, 32, 32, 0, pa); RMR.c.drawLine(32, 32, 0, 32, pa); } RMR.c.restore(); } }*/ RMR.c.drawLine(0, 0, 32 * this.width, 0, pa); RMR.c.drawLine(0, 0, 0, 32 * this.height, pa); RMR.c.drawLine(32 * this.width, 32 * this.height, 32 * this.width, 0, pa); RMR.c.drawLine(32 * this.width, 32 * this.height, 0, 32 * this.height, pa); } RMR.c.restore(); pa = new Paint(); RMR.c.save(); { if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.tile_0_iterator++; if(RMGR.tile_0_iterator == RMGR.TILE_0.length) RMGR.tile_0_iterator = 0; if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.tile_1_iterator++; if(RMGR.tile_1_iterator == RMGR.TILE_1.length) RMGR.tile_1_iterator = 0; for (int i = 0; i < this.height; i++) { for (int j = 0; j < this.width; j++) { switch (this.tiles[j][i]) { default: continue; case 1: RMR.c.save(); { int it = RMGR.tile_0_iterator + i + j; it %= RMGR.TILE_0.length; RMR.c.translate(i * 32, j * 32); src.set(0, 0, RMGR.TILE_0[it].getWidth(), RMGR.TILE_0[it].getHeight()); dst.set(0, 0, 32, 32); pa.setColor(Color.WHITE); RMR.c.drawBitmap(RMGR.TILE_0[it], src, dst, pa); } RMR.c.restore(); break; case 2: RMR.c.save(); { int it = RMGR.tile_1_iterator + i + j; it %= RMGR.TILE_1.length; RMR.c.translate(i * 32, j * 32); src.set(0, 0, RMGR.TILE_1[it].getWidth(), RMGR.TILE_1[it].getHeight()); dst.set(0, 0, 32, 32); pa.setColor(Color.WHITE); RMR.c.drawBitmap(RMGR.TILE_1[it], src, dst, pa); } RMR.c.restore(); break; } } } } RMR.c.restore(); RMR.c.save(); { if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.pickup_0_iterator++; if(RMGR.pickup_0_iterator == RMGR.PICKUP_0.length) RMGR.pickup_0_iterator = 0; if((System.currentTimeMillis() / 30) % 2 == 0) RMGR.pickup_1_iterator++; if(RMGR.pickup_1_iterator == RMGR.PICKUP_1.length) RMGR.pickup_1_iterator = 0; for (int i = 0; i < this.pickups.size(); i++) { RMR.c.save(); { RMR.c.translate(this.pickups.get(i)[1] * 32, this.pickups.get(i)[0] * 32); pa.setAlpha((int) Math.floor(100 / ((float)this.pickups.get(i)[3] / ((float)this.pickups.get(i)[2] != 0 ? (float)this.pickups.get(i)[2] : 1)))); switch (this.pickups.get(i)[4]) { default: case 1: int it = (RMGR.pickup_0_iterator + this.pickups.get(i)[0] + this.pickups.get(i)[1]); it %= RMGR.PICKUP_0.length; src.set(0, 0, RMGR.PICKUP_0[it].getWidth(), RMGR.PICKUP_0[it].getHeight()); dst.set(4, 4, 28, 28); RMR.c.drawBitmap(RMGR.PICKUP_0[it], src, dst, pa); break; case 2: int it1 = (RMGR.pickup_1_iterator + this.pickups.get(i)[0] + this.pickups.get(i)[1]); it1 %= RMGR.PICKUP_1.length; src.set(0, 0, RMGR.PICKUP_1[it1].getWidth(), RMGR.PICKUP_1[it1].getHeight()); dst.set(4, 4, 28, 28); RMR.c.drawBitmap(RMGR.PICKUP_1[it1], src, dst, pa); break; } } RMR.c.restore(); } } RMR.c.restore(); pa = new Paint(); if (this.state == MapState.Suspended) { RMR.c.save(); { pa.setColor(Color.BLACK); pa.setAlpha(80); RMR.c.drawRect(0, 0, RMR.mapSideLength * 32, this.suspendTile.x * 32, pa); RMR.c.drawRect((this.suspendTile.y + 1) * 32, this.suspendTile.x * 32, RMR.mapSideLength * 32, (this.suspendTile.x + 1) * 32, pa); RMR.c.drawRect(0, this.suspendTile.x * 32, this.suspendTile.y * 32, (this.suspendTile.x + 1) * 32, pa); RMR.c.drawRect(0, (this.suspendTile.x + 1) * 32, RMR.mapSideLength * 32, RMR.mapSideLength * 32, pa); pa.setColor(Color.YELLOW); pa.setAlpha((int) Math.floor((Math.sin(System.currentTimeMillis() / 100) + 2) * 30)); RMR.c.drawRect(this.suspendTile.y * 32, this.suspendTile.x * 32, (this.suspendTile.y + 1) * 32, (this.suspendTile.x + 1) * 32, pa); } RMR.c.restore(); } RMR.c.save(); { pa.setColor(Color.WHITE); RMR.c.translate(p1.posY, p1.posX); src.set(0, 0, RMGR.CHAR_0.getWidth(), RMGR.CHAR_0.getHeight()); dst.set(-12, -12, 12, 12); RMR.c.drawBitmap(RMGR.CHAR_0, src, dst, pa); } RMR.c.restore(); } RMR.c.restore(); RMR.c.save(); { pa.setColor(Color.WHITE); RMR.c.translate(RMR.mapSideLength * 32 / 2, RMR.mapSideLength * 32 / 2); src.set(0, 0, RMGR.CHAR_0.getWidth(), RMGR.CHAR_0.getHeight()); dst.set(-12, -12, 12, 12); RMR.c.drawBitmap(RMGR.CHAR_0, src, dst, pa); } RMR.c.restore(); } RMR.c.restore(); }
diff --git a/enough-polish-j2me/source/src/de/enough/polish/ui/FilteredList.java b/enough-polish-j2me/source/src/de/enough/polish/ui/FilteredList.java index eb6db60..757ea99 100644 --- a/enough-polish-j2me/source/src/de/enough/polish/ui/FilteredList.java +++ b/enough-polish-j2me/source/src/de/enough/polish/ui/FilteredList.java @@ -1,797 +1,798 @@ //#condition polish.usePolishGui /* * Created on Jun 21, 2007 at 11:28:35 PM. * * Copyright (c) 2010 Robert Virkus / Enough Software * * This file is part of J2ME Polish. * * J2ME Polish 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. * * J2ME Polish 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 J2ME Polish; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Commercial licenses are also available, please * refer to the accompanying LICENSE.txt or visit * http://www.j2mepolish.org for details. */ package de.enough.polish.ui; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import de.enough.polish.util.ArrayList; /** * <p>Displays a list of choices that can be limited by the user by entering some input.</p> * * <p>Copyright Enough Software 2007 - 2011</p> * @author Michael Koch * @author Robert Virkus, [email protected] */ public class FilteredList extends List implements ItemStateListener //, CommandListener { private static final int FIELD_POSITION_TOP = 0; private static final int FIELD_POSITION_BOTTOM = 1; private static final int FILTER_STARTS_WITH = 0; private static final int FILTER_INDEX_OF = 1; protected int filterPosition = FIELD_POSITION_BOTTOM; protected int filterMode = FILTER_STARTS_WITH; protected final TextField filterTextField; private final ArrayList itemsList; //private CommandListener originalCommandListener; private String lastFilterText; private int filterHeight; /** * Creates a new FilteredList * @param title the title * @param listType the type, either Choice.MULTIPLE, Choice.IMPLICIT or Choice.EXCLUSIVE */ public FilteredList(String title, int listType) { this( title, listType, (ChoiceItem[])null, (Style) null ); } /** * Creates a new FilteredList * @param title the title * @param listType the type, either Choice.MULTIPLE, Choice.IMPLICIT or Choice.EXCLUSIVE * @param style style for the list */ public FilteredList(String title, int listType, Style style) { this( title, listType, (ChoiceItem[])null, style ); } /** * Creates a new FilteredList * @param title the title * @param listType the type, either Choice.MULTIPLE, Choice.IMPLICIT or Choice.EXCLUSIVE * @param stringElements list item texts * @param imageElements list item images */ public FilteredList(String title, int listType, String[] stringElements, Image[] imageElements) { this( title, listType, stringElements, imageElements, null ); } /** * Creates a new FilteredList * @param title the title * @param listType the type, either Choice.MULTIPLE, Choice.IMPLICIT or Choice.EXCLUSIVE * @param stringElements list item texts * @param imageElements list item images * @param style style for the list */ public FilteredList(String title, int listType, String[] stringElements, Image[] imageElements, Style style) { this( title, listType, ChoiceGroup.buildChoiceItems(stringElements, imageElements, listType, style), style ); } /** * Creates a new FilteredList * @param title the title * @param listType the type, either Choice.MULTIPLE, Choice.IMPLICIT or Choice.EXCLUSIVE * @param items items of the list */ public FilteredList(String title, int listType, ChoiceItem[] items) { this(title, listType, items, null); } /** * Creates a new FilteredList * @param title the title * @param listType the type, either Choice.MULTIPLE, Choice.IMPLICIT or Choice.EXCLUSIVE * @param items items of the list * @param style style for the list */ public FilteredList(String title, int listType, ChoiceItem[] items, Style style) { super(title, listType, items, style); //#style filterTextField? this.filterTextField = new TextField( null, "", 30, TextField.ANY ); this.filterTextField.screen = this; setItemStateListener( this ); this.itemsList = new ArrayList(); //super.setCommandListener( this ); } /* (non-Javadoc) * @see de.enough.polish.ui.List#handleKeyPressed(int, int) */ protected boolean handleKeyPressed(int keyCode, int gameAction) { //#debug System.out.println("handleKeyPressed( " + keyCode + ", " + gameAction + ")"); boolean handled = false; if (! isGameActionFire( keyCode, gameAction )) { handled = this.filterTextField.handleKeyPressed(keyCode, gameAction); if (handled && this.filterTextField.getItemHeight( this.contentWidth, this.contentWidth, this.contentHeight + this.filterHeight) != this.filterHeight) { calculateContentArea(0, 0, this.screenWidth, this.screenHeight ); } } if (!handled) { handled = super.handleKeyPressed(keyCode, gameAction); } return handled; } /* (non-Javadoc) * @see de.enough.polish.ui.List#handleKeyReleased(int, int) */ protected boolean handleKeyReleased(int keyCode, int gameAction) { //#debug System.out.println("handleKeyReleased( " + keyCode + ", " + gameAction + ")"); boolean handled = false; if (!(isGameActionFire(keyCode, gameAction)) ) { handled = this.filterTextField.handleKeyReleased(keyCode, gameAction); } if (!handled) { handled = super.handleKeyReleased(keyCode, gameAction); } return handled; } /* (non-Javadoc) * @see de.enough.polish.ui.List#handleKeyRepeated(int, int) */ protected boolean handleKeyRepeated(int keyCode, int gameAction) { //#debug System.out.println("handleKeyRepeated( " + keyCode + ", " + gameAction + ")"); boolean handled = false; if (!(isGameActionFire(keyCode, gameAction))) { handled = this.filterTextField.handleKeyRepeated(keyCode, gameAction); } if (!handled) { handled = super.handleKeyRepeated(keyCode, gameAction); } return handled; } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#animate(long,ClippingRegion) */ public void animate( long currentTime, ClippingRegion repaintRegion ) { super.animate(currentTime, repaintRegion); this.filterTextField.animate(currentTime, repaintRegion); } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#setItemCommands( ArrayList,Item) */ protected void setItemCommands( ArrayList commandsList, Item item ) { if (item != this.filterTextField) { this.filterTextField.addCommands(commandsList); } else { this.container.addCommands(commandsList); } super.setItemCommands(commandsList, item); } /* * (non-Javadoc) * @see de.enough.polish.ui.Screen#adjustContentArea(int, int, int, int, de.enough.polish.ui.Container) */ protected void adjustContentArea(int x, int y, int width, int height, Container cont) { this.filterHeight = this.filterTextField.getItemHeight( this.contentWidth, this.contentWidth, this.contentHeight / 2 ); this.contentHeight -= this.filterHeight; this.container.setScrollHeight( this.contentHeight ); this.filterTextField.relativeX = x; if (this.filterPosition == FIELD_POSITION_TOP) { this.filterTextField.relativeY = this.contentY; this.contentY += this.filterHeight; } else { this.filterTextField.relativeY = this.contentY + this.contentHeight; } super.adjustContentArea(x, y, width, height, cont); } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#showNotify() */ public void showNotify() { //#debug System.out.println("showNotify of FilteredList" + this ); this.filterTextField.showNotify(); if (!this.filterTextField.isFocused) { this.filterTextField.setShowInputInfo( false ); this.filterTextField.focus( this.filterTextField.getFocusedStyle(), 0 ); } //#if polish.blackberry Display.getInstance().notifyFocusSet(this.filterTextField); //#endif itemStateChanged( this.filterTextField ); super.showNotify(); } /* * (non-Javadoc) * @see de.enough.polish.ui.Screen#hideNotify() */ public void hideNotify() { this.filterTextField.hideNotify(); super.hideNotify(); } //#if polish.blackberry /* * (non-Javadoc) * @see de.enough.polish.ui.Screen#notifyFocusSet(de.enough.polish.ui.Item) */ protected void notifyFocusSet(Item item) { if (this.isMenuOpened() || item == this.filterTextField) { super.notifyFocusSet(item); } } //#endif //#if !polish.blackberry private boolean forwardEventToNativeField(Screen screen, int keyCode) { //# return false; //#else //# protected boolean forwardEventToNativeField(Screen screen, int keyCode) { boolean forward = Display.getInstance().forwardEventToNativeField( screen, keyCode ); return forward && (getGameAction( keyCode ) != FIRE); //#endif } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#getCurrentItem() */ public Item getCurrentItem() { return this.filterTextField; } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#paintScreen(javax.microedition.lcdui.Graphics) */ protected void paintScreen(Graphics g) { TextField textField = this.filterTextField; textField.paint( textField.relativeX, textField.relativeY, this.contentX, this.contentX + this.contentWidth, g ); super.paintScreen(g); } /* (non-Javadoc) * @see de.enough.polish.ui.List#append(de.enough.polish.ui.ChoiceItem) */ public int append(ChoiceItem item) { if (this.listType == Choice.MULTIPLE) { this.choiceGroup.selectChoiceItem(item, item.isSelected); //#if !( polish.ChoiceGroup.suppressSelectCommand || polish.ChoiceGroup.suppressMarkCommands) item.setItemCommandListener( this.choiceGroup ); //#endif } this.itemsList.add( item ); this.lastFilterText = null; if (isShown()) { itemStateChanged( this.filterTextField ); } return this.itemsList.size() - 1; } /* (non-Javadoc) * @see de.enough.polish.ui.List#delete(int) */ public void delete(int elementNum) { this.itemsList.remove(elementNum); this.lastFilterText = null; if (isShown()) { itemStateChanged( this.filterTextField ); } } /* (non-Javadoc) * @see de.enough.polish.ui.List#deleteAll() */ public void deleteAll() { this.itemsList.clear(); this.lastFilterText = null; if (isShown()) { itemStateChanged( this.filterTextField ); } } /* (non-Javadoc) * @see de.enough.polish.ui.List#getItem(int) */ public ChoiceItem getItem(int elementNum) { return (ChoiceItem) this.itemsList.get(elementNum); } /* (non-Javadoc) * @see de.enough.polish.ui.List#getSelectedFlags(boolean[]) */ public int getSelectedFlags(boolean[] selectedArray_return) { int count = 0; for (int i = 0; i < selectedArray_return.length; i++) { boolean selected = ((ChoiceItem) this.itemsList.get(i)).isSelected; selectedArray_return[i] = selected; if (selected) { count++; } } return count; } /** * Determines whether there are any changes compared to the specified boolean array. * * @param flags an array indicating the expected state of this list - true array elements indicate "selected" items of this list * @return true when there are changes in this list */ public boolean containsChangesTo( boolean[] flags ) { if (this.itemsList.size() != flags.length ) { return true; } for (int i = 0; i < flags.length; i++) { boolean flag = flags[i]; if (flag != ((ChoiceItem)this.itemsList.get(i)).isSelected ) { return true; } } return false; } /* (non-Javadoc) * @see de.enough.polish.ui.List#getSelectedIndex() */ public int getSelectedIndex() { if (this.listType == Choice.IMPLICIT && isShown()) { Item focItem = this.container.getFocusedItem(); if (focItem != null) { return this.itemsList.indexOf(focItem); } } Object[] items = this.itemsList.getInternalArray(); for (int i = 0; i < items.length; i++) { Object object = items[i]; if (object == null) { return -1; } ChoiceItem item = (ChoiceItem) object; if ( item.isSelected ) { return i; } } return -1; } /* (non-Javadoc) * @see de.enough.polish.ui.List#insert(int, de.enough.polish.ui.ChoiceItem) */ public void insert(int elementNum, ChoiceItem item) { this.itemsList.add(elementNum, item); this.lastFilterText = null; if (isShown()) { itemStateChanged( this.filterTextField ); } } /** * Sets the <code>String</code> and <code>Image</code> parts of the * element referenced by <code>elementNum</code>, * replacing the previous contents of the element. * * @param elementNum the index of the element to be set * @param stringPart the string part of the new element * @param imagePart the image part of the element, or null if there is no image part * @param elementStyle the style for the new list element. * @throws IndexOutOfBoundsException if elementNum is invalid * @throws NullPointerException if stringPart is null * @see Choice#set(int, String, Image) in interface Choice */ public void set(int elementNum, String stringPart, Image imagePart, Style elementStyle ) { ChoiceItem item = getItem(elementNum ); item.setText( stringPart ); if (imagePart != null) { item.setImage(imagePart); } if (elementStyle != null) { item.setStyle(elementStyle); } this.lastFilterText = null; if (isShown()) { itemStateChanged( this.filterTextField ); } } /* (non-Javadoc) * @see de.enough.polish.ui.List#set(int, de.enough.polish.ui.ChoiceItem) */ public void set(int elementNum, ChoiceItem item) { this.itemsList.set(elementNum, item); this.lastFilterText = null; if (isShown()) { itemStateChanged( this.filterTextField ); } } /* (non-Javadoc) * @see de.enough.polish.ui.List#setSelectedFlags(boolean[]) */ public void setSelectedFlags(boolean[] selectedArray) { for (int i = 0; i < selectedArray.length; i++) { boolean isSelected = selectedArray[i]; ChoiceItem item = ((ChoiceItem) this.itemsList.get(i)); item.select( isSelected ); //#if !polish.ChoiceGroup.suppressMarkCommands if ( this.listType == Choice.MULTIPLE ) { if (isSelected) { item.removeCommand(ChoiceGroup.MARK_COMMAND); item.setDefaultCommand(ChoiceGroup.UNMARK_COMMAND); } else { item.removeCommand(ChoiceGroup.UNMARK_COMMAND); item.setDefaultCommand(ChoiceGroup.MARK_COMMAND); } } //#endif } if (isShown()) { itemStateChanged( this.filterTextField ); } } /* (non-Javadoc) * @see de.enough.polish.ui.List#setSelectedIndex(int, boolean) */ public void setSelectedIndex(int elementNum, boolean isSelected) { if ( this.listType == Choice.MULTIPLE ) { ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum ); item.select( isSelected ); //#if !polish.ChoiceGroup.suppressMarkCommands if (isSelected) { item.removeCommand(ChoiceGroup.MARK_COMMAND); item.setDefaultCommand(ChoiceGroup.UNMARK_COMMAND); } else { item.removeCommand(ChoiceGroup.UNMARK_COMMAND); item.setDefaultCommand(ChoiceGroup.MARK_COMMAND); } //#endif } else { if (!isSelected) { return; // ignore this call } int oldIndex = getSelectedIndex(); if ( oldIndex != -1) { ChoiceItem oldSelected = (ChoiceItem) this.itemsList.get( oldIndex ); oldSelected.select( false ); } ChoiceItem newSelected = (ChoiceItem) this.itemsList.get( elementNum ); newSelected.select( true ); } if (isShown()) { if (this.listType == Choice.IMPLICIT) { focus( elementNum ); } itemStateChanged( this.filterTextField ); } } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#focus(int, boolean) */ public void focus(int index, boolean force) { Item item = null; if (index != -1) { item = (Item) this.itemsList.get( index ); } focus( index, item, force ); } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#focus(de.enough.polish.ui.Item, boolean) */ public void focus(Item item, boolean force) { int index = -1; if (item != null) { index = this.itemsList.indexOf( item ); if (index == -1) { super.focus( item, force ); return; } } focus( index, item, force ); } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#focus(int, de.enough.polish.ui.Item, boolean) */ public void focus(int index, Item item, boolean force) { if (isMenuOpened()) { super.focus( index, item, force ); return; } if (index != -1 && item == null) { item = (Item) this.itemsList.get( index ); } if (item != null) { index = this.container.indexOf(item); if (index == -1) { super.focus( index, item, force ); } else { this.container.focusChild(index); } } else { super.focus( index, item, force ); //this.container.focusChild(-1); } } /* (non-Javadoc) * @see de.enough.polish.ui.List#isSelected(int) */ public boolean isSelected(int elementNum) { ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum ); return item.isSelected; } /* (non-Javadoc) * @see de.enough.polish.ui.List#size() */ public int size() { return this.itemsList.size(); } // /* (non-Javadoc) // * @see de.enough.polish.ui.Screen#getCommandListener() // */ // public CommandListener getCommandListener() { // return this.originalCommandListener; // } // // /* (non-Javadoc) // * @see de.enough.polish.ui.Screen#setCommandListener(javax.microedition.lcdui.CommandListener) // */ // public void setCommandListener(CommandListener listener) { // this.originalCommandListener = listener; // } // // /* (non-Javadoc) // * @see de.enough.polish.ui.Screen#commandAction(javax.microedition.lcdui.Command, javax.microedition.lcdui.Displayable) // */ // public void commandAction(Command command, Displayable screen) { // System.out.println("commandAction: " + command.getLabel() ); // this.filterTextField.commandAction(command, this.filterTextField); // if (this.container.itemCommandListener != null && this.container.commands != null && this.container.commands.contains(command)) { // this.container.itemCommandListener.commandAction(command, this.container); // } else if (this.originalCommandListener != null) { // this.originalCommandListener.commandAction(command, this); // } // } /* (non-Javadoc) * @see de.enough.polish.ui.Screen#handleCommand(javax.microedition.lcdui.Command) */ protected boolean handleCommand(Command cmd) { if (this.filterTextField.handleCommand(cmd)) { return true; } return super.handleCommand(cmd); } public void setFilterLabel( String label ) { this.filterTextField.setLabel(label); } /** * Sets the text of the filter element. * * @param text the text that is should be entered into the filter field. */ public void setFilterText( String text ) { this.filterTextField.setString( text ); if (this.contentWidth != 0 && isShown()) { int height = this.filterTextField.getItemHeight( this.contentWidth, this.contentWidth, this.contentHeight + this.filterHeight ); if (height != this.filterHeight) { calculateContentArea( 0, 0, this.screenWidth, this.screenHeight ); } itemStateChanged( this.filterTextField ); } } /** * Retrieves the text from the filter element. * * @return the text that is currently entered into the filter field. */ public String getFilterText() { return this.filterTextField.getString(); } /** * @param filterStyle */ public void setFilterStyle(Style filterStyle) { this.filterTextField.focusedStyle = filterStyle; if (isShown()) { this.filterTextField.focus(filterStyle, 0); } } /** * Checks if the given item matches the current input text. * Subclasses can override this method for implementing specific * filter strategies. * * @param filterText the current filter text * @param cItem the ChoiceItem * @param checkForSelectedRadioItem true when this is an exclusive list * @return true for choice items that should be appended to the shown list. * @see #FILTER_STARTS_WITH * @see #FILTER_INDEX_OF * @see #setFitPolicy(int) */ protected boolean matches( String filterText, ChoiceItem cItem, boolean checkForSelectedRadioItem ) { if (checkForSelectedRadioItem && cItem.isSelected) { return true; } else if (this.filterMode == FILTER_STARTS_WITH) { return ( cItem.getText().toLowerCase().startsWith(filterText)); } else { return ( cItem.getText().toLowerCase().indexOf( filterText ) != -1); } } /* (non-Javadoc) * @see de.enough.polish.ui.ItemStateListener#itemStateChanged(de.enough.polish.ui.Item) */ public void itemStateChanged(Item item) { if (item == this.filterTextField) { String text = this.filterTextField.getString(); if (text == this.lastFilterText || (text != null && text.equals(this.lastFilterText))) { return; } this.lastFilterText = text; Object[] itemObjects = this.itemsList.getInternalArray(); ArrayList matchingItems = new ArrayList( itemObjects.length ); int focIndex = -1; Item focItem = this.container.focusedItem; boolean checkForSelectedRadioItem = (this.listType == Choice.EXCLUSIVE); if (text.length() == 0) { matchingItems.addAll( this.itemsList ); focIndex = getSelectedIndex(); if (focIndex != -1 && focItem == null) { focItem = (Item) this.itemsList.get( focIndex ); } } else { String filterText = text.toLowerCase(); //System.out.println("caretPos=" + this.filterTextField.getCaretPosition() + ", tex.length=" + text.length()); //System.out.println("filter=[" + filterText + "] - number of elements=" + this.itemsList.size()); for (int i = 0; i < itemObjects.length; i++) { Object object = itemObjects[i]; if (object == null) { break; } ChoiceItem cItem = (ChoiceItem) object; boolean isMatch = matches( filterText, cItem, checkForSelectedRadioItem ); if (isMatch) { matchingItems.add(cItem); if (cItem == focItem) { - focIndex = i; + focIndex = matchingItems.size() - 1; } } } } this.container.setItemsList( matchingItems ); if (focIndex != -1) { super.focus( focIndex, focItem, false ); } else if (matchingItems.size() > 0) { - super.focus( 0, (Item) matchingItems.get(0), false ); + focItem = (Item) matchingItems.get(0); + super.focus( 0, focItem, false ); } if (checkForSelectedRadioItem && this.getSelectedIndex() != -1) { ( (ChoiceGroup)this.container ).setSelectedIndex( matchingItems.indexOf( this.itemsList.get( getSelectedIndex() ) ) , true); } this.filterTextField.showCommands(); } } /* (non-Javadoc) * @see de.enough.polish.ui.List#setStyle(de.enough.polish.ui.Style) */ public void setStyle(Style style) { super.setStyle(style); //#if polish.css.filter-position Integer filterPositionInt = style.getIntProperty("filter-position"); if (filterPositionInt != null) { this.filterPosition = filterPositionInt.intValue(); } //#endif //#if polish.css.filter-style Style filterStyle = (Style) style.getObjectProperty("filter-style"); if (filterStyle != null) { this.filterTextField.focusedStyle = filterStyle; this.filterTextField.focus(filterStyle, 0); } //#endif } //#ifdef polish.useDynamicStyles /* (non-Javadoc) * @see de.enough.polish.ui.Screen#getCssSelector() */ protected String createCssSelector() { return "filteredlist"; } //#endif /** * Concats all strings from the selected elements together. * * @param delimiter the delimiter between elements * @return the String including all selected elements or null when none is selected */ public String toSelectionString( String delimiter ) { Object[] elements = this.itemsList.getInternalArray(); StringBuffer buffer = null; for (int i = 0; i < elements.length; i++) { ChoiceItem item = (ChoiceItem) elements[i]; if (item == null) { break; } if (item.isSelected) { if (buffer == null) { buffer = new StringBuffer(); } else { buffer.append( delimiter ); } buffer.append( item.text ); } } if (buffer == null) { return null; } else { return buffer.toString(); } } }
false
true
public void itemStateChanged(Item item) { if (item == this.filterTextField) { String text = this.filterTextField.getString(); if (text == this.lastFilterText || (text != null && text.equals(this.lastFilterText))) { return; } this.lastFilterText = text; Object[] itemObjects = this.itemsList.getInternalArray(); ArrayList matchingItems = new ArrayList( itemObjects.length ); int focIndex = -1; Item focItem = this.container.focusedItem; boolean checkForSelectedRadioItem = (this.listType == Choice.EXCLUSIVE); if (text.length() == 0) { matchingItems.addAll( this.itemsList ); focIndex = getSelectedIndex(); if (focIndex != -1 && focItem == null) { focItem = (Item) this.itemsList.get( focIndex ); } } else { String filterText = text.toLowerCase(); //System.out.println("caretPos=" + this.filterTextField.getCaretPosition() + ", tex.length=" + text.length()); //System.out.println("filter=[" + filterText + "] - number of elements=" + this.itemsList.size()); for (int i = 0; i < itemObjects.length; i++) { Object object = itemObjects[i]; if (object == null) { break; } ChoiceItem cItem = (ChoiceItem) object; boolean isMatch = matches( filterText, cItem, checkForSelectedRadioItem ); if (isMatch) { matchingItems.add(cItem); if (cItem == focItem) { focIndex = i; } } } } this.container.setItemsList( matchingItems ); if (focIndex != -1) { super.focus( focIndex, focItem, false ); } else if (matchingItems.size() > 0) { super.focus( 0, (Item) matchingItems.get(0), false ); } if (checkForSelectedRadioItem && this.getSelectedIndex() != -1) { ( (ChoiceGroup)this.container ).setSelectedIndex( matchingItems.indexOf( this.itemsList.get( getSelectedIndex() ) ) , true); } this.filterTextField.showCommands(); } }
public void itemStateChanged(Item item) { if (item == this.filterTextField) { String text = this.filterTextField.getString(); if (text == this.lastFilterText || (text != null && text.equals(this.lastFilterText))) { return; } this.lastFilterText = text; Object[] itemObjects = this.itemsList.getInternalArray(); ArrayList matchingItems = new ArrayList( itemObjects.length ); int focIndex = -1; Item focItem = this.container.focusedItem; boolean checkForSelectedRadioItem = (this.listType == Choice.EXCLUSIVE); if (text.length() == 0) { matchingItems.addAll( this.itemsList ); focIndex = getSelectedIndex(); if (focIndex != -1 && focItem == null) { focItem = (Item) this.itemsList.get( focIndex ); } } else { String filterText = text.toLowerCase(); //System.out.println("caretPos=" + this.filterTextField.getCaretPosition() + ", tex.length=" + text.length()); //System.out.println("filter=[" + filterText + "] - number of elements=" + this.itemsList.size()); for (int i = 0; i < itemObjects.length; i++) { Object object = itemObjects[i]; if (object == null) { break; } ChoiceItem cItem = (ChoiceItem) object; boolean isMatch = matches( filterText, cItem, checkForSelectedRadioItem ); if (isMatch) { matchingItems.add(cItem); if (cItem == focItem) { focIndex = matchingItems.size() - 1; } } } } this.container.setItemsList( matchingItems ); if (focIndex != -1) { super.focus( focIndex, focItem, false ); } else if (matchingItems.size() > 0) { focItem = (Item) matchingItems.get(0); super.focus( 0, focItem, false ); } if (checkForSelectedRadioItem && this.getSelectedIndex() != -1) { ( (ChoiceGroup)this.container ).setSelectedIndex( matchingItems.indexOf( this.itemsList.get( getSelectedIndex() ) ) , true); } this.filterTextField.showCommands(); } }
diff --git a/src/java/com/idega/block/trade/stockroom/business/StockroomBusinessBean.java b/src/java/com/idega/block/trade/stockroom/business/StockroomBusinessBean.java index b98bacc..14dbde3 100644 --- a/src/java/com/idega/block/trade/stockroom/business/StockroomBusinessBean.java +++ b/src/java/com/idega/block/trade/stockroom/business/StockroomBusinessBean.java @@ -1,666 +1,670 @@ package com.idega.block.trade.stockroom.business; import java.rmi.RemoteException; import java.sql.Date; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.axis.util.AxisUtil; import com.idega.block.trade.business.CurrencyBusiness; import com.idega.block.trade.business.CurrencyHolder; import com.idega.block.trade.stockroom.data.PriceCategory; import com.idega.block.trade.stockroom.data.Product; import com.idega.block.trade.stockroom.data.ProductPrice; import com.idega.block.trade.stockroom.data.ProductPriceHome; import com.idega.block.trade.stockroom.data.Reseller; import com.idega.block.trade.stockroom.data.ResellerHome; import com.idega.block.trade.stockroom.data.ResellerStaffGroup; import com.idega.block.trade.stockroom.data.ResellerStaffGroupBMPBean; import com.idega.block.trade.stockroom.data.Supplier; import com.idega.block.trade.stockroom.data.SupplierHome; import com.idega.block.trade.stockroom.data.SupplierStaffGroupBMPBean; import com.idega.block.trade.stockroom.data.Timeframe; import com.idega.block.trade.stockroom.data.TravelAddress; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.business.IBORuntimeException; import com.idega.business.IBOServiceBean; import com.idega.core.accesscontrol.business.LoginBusinessBean; import com.idega.core.accesscontrol.business.NotLoggedOnException; import com.idega.core.data.ICApplicationBinding; import com.idega.core.data.ICApplicationBindingHome; import com.idega.data.EntityControl; import com.idega.data.EntityFinder; import com.idega.data.IDOAddRelationshipException; import com.idega.data.IDOCompositePrimaryKeyException; import com.idega.data.IDOFinderException; import com.idega.data.IDOLookup; import com.idega.data.IDOLookupException; import com.idega.idegaweb.IWBundle; import com.idega.presentation.IWContext; import com.idega.presentation.ui.DropdownMenu; import com.idega.user.data.Group; import com.idega.user.data.User; import com.idega.util.FileUtil; import com.idega.util.IWTimestamp; /** * Title: IW Trade * Description: * Copyright: Copyright (c) 2001 * Company: idega.is * @author 2000 - idega team - <br><a href="mailto:[email protected]">Gudmundur Agust Saemundsson</a><br><a href="mailto:[email protected]">Grimur Jonsson</a> * @version 1.0 */ public class StockroomBusinessBean extends IBOServiceBean implements StockroomBusiness { public static final String REMOTE_TRAVEL_APPLICATION_URL_CSV_LIST = "REMOTE_TRAVEL_APPLICATION_URL_CSV_LIST"; private static String remoteTravelApplications = null; public StockroomBusinessBean() { } public void addSupplies(int product_id, float amount) { /**@todo: Implement this com.idega.block.trade.stockroom.business.SupplyManager method*/ throw new java.lang.UnsupportedOperationException("Method addSupplies() not yet implemented."); } public void depleteSupplies(int product_id, float amount) { /**@todo: Implement this com.idega.block.trade.stockroom.business.SupplyManager method*/ throw new java.lang.UnsupportedOperationException("Method depleteSupplies() not yet implemented."); } public void setSupplyStatus(int product_id, float status) { /**@todo: Implement this com.idega.block.trade.stockroom.business.SupplyManager method*/ throw new java.lang.UnsupportedOperationException("Method addSupplies() not yet implemented."); } public float getSupplyStatus(int product_id) throws SQLException { /**@todo: Implement this com.idega.block.trade.stockroom.business.SupplyManager method*/ throw new java.lang.UnsupportedOperationException("Method getSupplyStatus() not yet implemented."); } public float getSupplyStatus(int product_id, Timestamp time) { /**@todo: Implement this com.idega.block.trade.stockroom.business.SupplyManager method*/ throw new java.lang.UnsupportedOperationException("Method getSupplyStatus() not yet implemented."); } public ProductPrice setPrice(int productPriceIdToReplace, int productId, int priceCategoryId, int currencyId, Timestamp time, float price, int priceType, int timeframeId, int addressId) throws FinderException, IDOAddRelationshipException, CreateException, RemoteException { return setPrice(productPriceIdToReplace, productId, priceCategoryId, currencyId, time, price, priceType, timeframeId, addressId, -1); } public ProductPrice setPrice(int productPriceIdToReplace, int productId, int priceCategoryId, int currencyId, Timestamp time, float price, int priceType, int timeframeId, int addressId, int maxUsage) throws FinderException, IDOAddRelationshipException, CreateException, RemoteException { if (productPriceIdToReplace != -1) { ProductPrice pPrice = ((com.idega.block.trade.stockroom.data.ProductPriceHome)com.idega.data.IDOLookup.getHome(ProductPrice.class)).findByPrimaryKey(new Integer(productPriceIdToReplace)); pPrice.invalidate(); pPrice.store(); } return setPrice(productId, priceCategoryId, currencyId, time, price, priceType, timeframeId, addressId, maxUsage, null); } public ProductPrice setPrice(int productId, int priceCategoryId, int currencyId, Timestamp time, float price, int priceType, int timeframeId, int addressId) throws IDOAddRelationshipException, CreateException, RemoteException { return setPrice(productId, priceCategoryId, currencyId, time, price, priceType, timeframeId, addressId, -1, null); } public ProductPrice setPrice(int productId, int priceCategoryId, int currencyId, Timestamp time, float price, int priceType, int timeframeId, int addressId, int maxUsage, Date exactDate) throws IDOAddRelationshipException, CreateException, RemoteException { ProductPrice prPrice = ((com.idega.block.trade.stockroom.data.ProductPriceHome)com.idega.data.IDOLookup.getHome(ProductPrice.class)).create(); prPrice.setProductId(productId); prPrice.setCurrencyId(currencyId); prPrice.setPriceCategoryID(priceCategoryId); prPrice.setPriceDate(time); prPrice.setPrice(price); prPrice.setPriceType(priceType); prPrice.setMaxUsage(maxUsage); if(exactDate != null) { prPrice.setExactDate(exactDate); } prPrice.store(); if (timeframeId != -1) { prPrice.addTimeframe(new Integer(timeframeId)); } if (addressId != -1) { prPrice.addTravelAddress(new Integer(addressId)); } getProductPriceBusiness().invalidateCache(Integer.toString(productId)); return prPrice; } public float getPrice(int productPriceId, int productId, int priceCategoryId, int currencyId, Timestamp time) throws SQLException, RemoteException { return getPrice(productPriceId, productId, priceCategoryId, currencyId, time, -1, -1); } public ProductPrice getPrice(Product product) throws RemoteException { StringBuffer buffer = new StringBuffer(); buffer.append("SELECT * FROM "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getProductPriceTableName()); buffer.append(" WHERE "); buffer.append(com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameProductId() +" = "+product.getID()); buffer.append(" AND "); buffer.append(com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceCategoryId() +" is null"); buffer.append(" ORDER BY "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+" DESC"); try { // EntityFinder.debug = true; List prices = EntityFinder.getInstance().findAll(ProductPrice.class, buffer.toString()); // List prices = EntityFinder.findAll(((com.idega.block.trade.stockroom.data.ProductPriceHome)com.idega.data.IDOLookup.getHomeLegacy(ProductPrice.class)).createLegacy(), buffer.toString()); // EntityFinder.debug = false; if (prices != null) if (prices.size() > 0) { return ((ProductPrice)prices.get(0)); } }catch (IDOFinderException ido) { ido.printStackTrace(System.err); } return null; } public float getPrice(int productPriceId, int productId, int priceCategoryId, Timestamp time, int timeframeId, int addressId) throws SQLException, RemoteException { return getPrice(productPriceId, productId, priceCategoryId, -1, time, timeframeId, addressId); } public float getPrice(int productPriceId, int productId, int priceCategoryId, int currencyId, Timestamp time, int timeframeId, int addressId) throws SQLException, RemoteException { /**@todo: Implement this com.idega.block.trade.stockroom.business.SupplyManager method*/ /*skila ver�i ef PRICETYPE_PRICE annars ver�i me� tilliti til afsl�ttar*/ try { PriceCategory cat = ((com.idega.block.trade.stockroom.data.PriceCategoryHome)com.idega.data.IDOLookup.getHomeLegacy(PriceCategory.class)).findByPrimaryKeyLegacy(priceCategoryId); ProductPrice ppr = ((ProductPrice)com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getStaticInstanceIDO(ProductPrice.class)); TravelAddress taddr = ((TravelAddress) com.idega.block.trade.stockroom.data.TravelAddressBMPBean.getStaticInstance(TravelAddress.class)); Timeframe tfr = ((Timeframe) com.idega.block.trade.stockroom.data.TimeframeBMPBean.getStaticInstance(Timeframe.class)); String addrTable = EntityControl.getManyToManyRelationShipTableName(TravelAddress.class, ProductPrice.class); String tfrTable = EntityControl.getManyToManyRelationShipTableName(Timeframe.class, ProductPrice.class); String ppColName = ppr.getEntityDefinition().getPrimaryKeyDefinition().getField().getSQLFieldName(); String ppTable = ppr.getEntityDefinition().getSQLTableName(); if(cat.getType().equals(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_PRICE)){ StringBuffer buffer = new StringBuffer(); buffer.append("select p.* from "+ppTable+" p"); if (timeframeId != -1) { buffer.append(", "+tfrTable+" tm"); } if (addressId != -1) { buffer.append(", "+addrTable+" am"); } buffer.append(" where "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameProductId()+" = "+productId); if (timeframeId != -1) { buffer.append(" and "); buffer.append("tm."+tfr.getIDColumnName()+" = "+timeframeId); buffer.append(" and "); buffer.append("p."+ppColName+" = tm."+ppColName); } if (addressId != -1) { buffer.append(" and "); buffer.append("am."+taddr.getIDColumnName()+" = "+addressId); buffer.append(" and "); buffer.append("p."+ppColName+" = am."+ppColName); } if (productPriceId != -1) { buffer.append(" and "); buffer.append("p."+ppColName+" = "+productPriceId); } buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceCategoryId()+" = "+priceCategoryId); buffer.append(" and "); IWTimestamp stamp = new IWTimestamp(time); // buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameCurrencyId()+" = "+currencyId); // buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+" <= '"+stamp.toSQLString()+"'"); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceType()+" = "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.PRICETYPE_PRICE); + buffer.append(" and "); + buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameCurrencyId()+" = "+currencyId); //buffer.append(" and "); //buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameIsValid()+" = 'Y'"); buffer.append(" order by p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+ " desc"); // List result = EntityFinder.findAll(ppr,buffer.toString()); // List result = EntityFinder.findAll(ppr,buffer.toString()); ProductPriceHome ppHome = (ProductPriceHome) IDOLookup.getHome(ProductPrice.class); Collection result = ppHome.findBySQL(buffer.toString()); if(result != null && result.size() > 0){ Iterator iter = result.iterator(); ProductPrice price = (ProductPrice) iter.next(); CurrencyHolder iceCurr = CurrencyBusiness.getCurrencyHolder(CurrencyHolder.ICELANDIC_KRONA); if ( iceCurr != null && (price.getCurrencyId() == iceCurr.getCurrencyID())) { return new Float(Math.round( price.getPrice()) ).floatValue(); } else { return price.getPrice(); } }else{ System.err.println(buffer.toString()); throw new ProductPriceException("No Price Was Found"); } }else if(cat.getType().equals(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_DISCOUNT)){ StringBuffer buffer = new StringBuffer(); buffer.append("select p.* from "+ppTable+" p"); if (timeframeId != -1) { buffer.append(", "+tfrTable+" tm"); } if (addressId != -1) { buffer.append(", "+addrTable+" am"); } buffer.append(" where "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameProductId()+" = "+productId); if (timeframeId != -1) { buffer.append(" and "); buffer.append("tm."+tfr.getIDColumnName()+" = "+timeframeId); buffer.append(" and "); buffer.append("p."+ppColName+" = tm."+ppColName); } if (addressId != -1) { buffer.append(" and "); buffer.append("am."+taddr.getIDColumnName()+" = "+addressId); buffer.append(" and "); buffer.append("p."+ppColName+" = am."+ppColName); } buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceCategoryId()+" = "+priceCategoryId); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+" < '"+time.toString()+"'"); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceType()+" = "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.PRICETYPE_DISCOUNT); + buffer.append(" and "); + buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameCurrencyId()+" = "+currencyId); //buffer.append(" and "); //buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameIsValid()+" = 'Y'"); buffer.append(" order by p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+ " desc"); ProductPriceHome ppHome = (ProductPriceHome) IDOLookup.getHome(ProductPrice.class); Collection result = ppHome.findBySQL(buffer.toString()); // List result = EntityFinder.findAll(ppr,buffer.toString()); float disc = 0; if(result != null && result.size() > 0){ Iterator iter = result.iterator(); ProductPrice price = (ProductPrice) iter.next(); disc = price.getPrice(); } float pr = getPrice(-1, productId,cat.getParentId(),currencyId,time, timeframeId, addressId); return pr*((100-disc) /100); }else{ throw new ProductPriceException("No Price Was Found"); } } catch (FinderException e) { e.printStackTrace(System.err); return 0; } catch (IDOCompositePrimaryKeyException e) { e.printStackTrace(System.err); return 0; } } /** * returns 0.0 if pricecategory is not of type com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_DISCOUNT * @throws SQLException * @throws SQLException * @throws FinderException */ public float getDiscount(int productId, int priceCategoryId, Timestamp time) throws RemoteException, SQLException, FinderException { PriceCategory cat = ((com.idega.block.trade.stockroom.data.PriceCategoryHome)com.idega.data.IDOLookup.getHomeLegacy(PriceCategory.class)).findByPrimaryKeyLegacy(priceCategoryId); if(cat.getType().equals(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_DISCOUNT)){ ProductPrice ppr = ((ProductPrice)com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getStaticInstance(ProductPrice.class)); String ppTable = ppr.getEntityDefinition().getSQLTableName(); StringBuffer buffer = new StringBuffer(); buffer.append("select * from "+ppTable); buffer.append(" where "); buffer.append(com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameProductId()+" = "+productId); buffer.append(" and "); buffer.append(com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceCategoryId()+" = "+priceCategoryId); buffer.append(" and "); buffer.append(com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+" < '"+time.toString()+"'"); buffer.append(" and "); buffer.append(com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameIsValid()+" = 'Y'"); buffer.append(" order by "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()); ProductPriceHome ppHome = (ProductPriceHome) IDOLookup.getHome(ProductPrice.class); Collection result = ppHome.findBySQL(buffer.toString()); // List result = EntityFinder.findAll(ppr,buffer.toString()); if(result != null && result.size() > 0){ Iterator iter = result.iterator(); ProductPrice price = (ProductPrice) iter.next(); return price.getPrice(); }else{ return 0; } }else{ throw new ProductPriceException(); } } public int createPriceCategory(int supplierId, String name, String description, String extraInfo) throws SQLException { return createPriceCategory(supplierId, name, description, extraInfo, null); } public int createPriceCategory(int supplierId, String name, String description, String extraInfo, String key)throws SQLException { try { PriceCategory cat = ((com.idega.block.trade.stockroom.data.PriceCategoryHome)com.idega.data.IDOLookup.getHome(PriceCategory.class)).create(); cat.setType(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_PRICE); cat.setName(name); if(description != null){ cat.setDescription(description); } if(extraInfo != null){ cat.setExtraInfo(extraInfo); } if (key != null) { cat.setKey(key); } cat.insert(); return cat.getID(); } catch (Exception e) { throw new SQLException(e.getMessage()); } } public void createPriceDiscountCategory(int parentId, int supplierId, String name, String description, String extraInfo) throws SQLException{ try { PriceCategory cat = ((com.idega.block.trade.stockroom.data.PriceCategoryHome)com.idega.data.IDOLookup.getHome(PriceCategory.class)).create(); cat.setParentId(parentId); cat.setType(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_DISCOUNT); cat.setName(name); if(description != null){ cat.setDescription(description); } if(extraInfo != null){ cat.setExtraInfo(extraInfo); } cat.insert(); } catch (Exception e) { throw new SQLException(e.getMessage()); } } public int getUserSupplierId(User user) throws RuntimeException, SQLException{ try { List gr = user.getParentGroups(); if(gr != null){ SupplierHome sHome = (SupplierHome) IDOLookup.getHome(Supplier.class); Iterator iter = gr.iterator(); while (iter.hasNext()) { Group item = (Group)iter.next(); if(item.getGroupType().equals(SupplierStaffGroupBMPBean.GROUP_TYPE_VALUE)){ try { Collection coll = sHome.findAllByGroupID( ((Integer) item.getPrimaryKey()).intValue()); if (coll != null && !coll.isEmpty()) { return ((Supplier) coll.iterator().next()).getID(); } } catch (FinderException fe) { fe.printStackTrace(); } // IDOLegacyEntity[] supp = ((Supplier) SupplierBMPBean.getStaticInstance(Supplier.class)).findAllByColumn(SupplierBMPBean.getColumnNameGroupID(),item.getID()); // if(supp != null && supp.length > 0){ // return supp[0].getID(); // } } } } throw new RuntimeException("Does not belong to any supplier"); } catch (IDOLookupException e) { e.printStackTrace(); throw new RuntimeException("Does not belong to any supplier"); } } public int getUserSupplierId(IWContext iwc) throws RuntimeException, SQLException { String supplierLoginAttributeString = "sr_supplier_id"; Object obj = LoginBusinessBean.getLoginAttribute(supplierLoginAttributeString,iwc); if(obj != null){ return ((Integer)obj).intValue(); }else{ User us = iwc.getCurrentUser();//LoginBusinessBean.getUser(iwc); if(us != null){ int suppId = getUserSupplierId(us); LoginBusinessBean.setLoginAttribute(supplierLoginAttributeString,new Integer(suppId), iwc); return suppId; } else{ throw new NotLoggedOnException(); } } } public int getUserResellerId(IWContext iwc) throws RuntimeException, SQLException { String resellerLoginAttributeString = "sr_reseller_id"; Object obj = LoginBusinessBean.getLoginAttribute(resellerLoginAttributeString,iwc); if(obj != null){ return ((Integer)obj).intValue(); }else{ User us = iwc.getCurrentUser();//LoginBusinessBean.getUser(iwc); if(us != null){ int resellerId = getUserResellerId(us); LoginBusinessBean.setLoginAttribute(resellerLoginAttributeString,new Integer(resellerId), iwc); return resellerId; } else{ throw new NotLoggedOnException(); } } } public int getUserResellerId(User user) throws RuntimeException, SQLException{ List gr = user.getParentGroups(); if(gr != null){ try { ResellerHome rHome = (ResellerHome) IDOLookup.getHome(Reseller.class); Iterator iter = gr.iterator(); while (iter.hasNext()) { Group item = (Group)iter.next(); if(item.getGroupType().equals(((ResellerStaffGroup) ResellerStaffGroupBMPBean.getStaticInstance(ResellerStaffGroup.class)).getGroupTypeValue())){ try { Collection coll = rHome.findAllByGroupID( item.getPrimaryKey() ); if (coll != null && !coll.isEmpty()) { return ((Reseller) coll.iterator().next()).getID(); } } catch (FinderException fe) { fe.printStackTrace(); } // IDOLegacyEntity[] reseller = ((Reseller) ResellerBMPBean.getStaticInstance(Reseller.class)).findAllByColumn(ResellerBMPBean.getColumnNameGroupID(),item.getID()); // if(reseller != null && reseller.length > 0){ // return reseller[0].getID(); // } } } } catch (IDOLookupException e) { e.printStackTrace(); } } throw new RuntimeException("Does not belong to any reseller"); /*com.idega.core.data.GenericGroup gGroup = ((com.idega.core.data.GenericGroupHome)com.idega.data.IDOLookup.getHomeLegacy(GenericGroup.class)).createLegacy(); List gr = gGroup.getAllGroupsContainingUser(user); if(gr != null){ Iterator iter = gr.iterator(); while (iter.hasNext()) { GenericGroup item = (GenericGroup)iter.next(); if(item.getGroupType().equals(((ResellerStaffGroup)com.idega.block.trade.stockroom.data.ResellerStaffGroupBMPBean.getStaticInstance(ResellerStaffGroup.class)).getGroupTypeValue())){ IDOLegacyEntity[] reseller = ((Reseller)com.idega.block.trade.stockroom.data.ResellerBMPBean.getStaticInstance(Reseller.class)).findAllByColumn(com.idega.block.trade.stockroom.data.ResellerBMPBean.getColumnNameGroupID(),item.getID()); if(reseller != null && reseller.length > 0){ return reseller[0].getID(); } } } } throw new RuntimeException("Does not belong to any reseller"); */ } public int updateProduct(int productId, int supplierId, Integer fileId, String productName, String number, String productDescription, boolean isValid, int[] addressIds, int discountTypeId) throws Exception{ return getProductBusiness().createProduct(productId,supplierId, fileId, productName, number, productDescription, isValid, addressIds, discountTypeId); } public int createProduct(int supplierId, Integer fileId, String productName, String number, String productDescription, boolean isValid, int[] addressIds, int discountTypeId) throws Exception{ return getProductBusiness().createProduct(-1,supplierId, fileId, productName, number, productDescription, isValid, addressIds, discountTypeId); } private ProductBusiness getProductBusiness() throws RemoteException { return (ProductBusiness) IBOLookup.getServiceInstance(getIWApplicationContext(), ProductBusiness.class); } public DropdownMenu getCurrencyDropdownMenu(String menuName) { DropdownMenu menu = new DropdownMenu(menuName); List currencyList = CurrencyBusiness.getCurrencyList(); Iterator iter = currencyList.iterator(); while (iter.hasNext()) { CurrencyHolder holder = (CurrencyHolder) iter.next(); menu.addMenuElement(holder.getCurrencyID(), holder.getCurrencyName()); } return menu; } public boolean isInTimeframe(IWTimestamp from, IWTimestamp to, IWTimestamp stampToCheck, boolean yearly) { return isBetween(from, to, stampToCheck, yearly, true); } public boolean isBetween(IWTimestamp from, IWTimestamp to, IWTimestamp stampToCheck, boolean yearly, boolean bordersCount) { from.setAsDate(); to.setAsDate(); if (yearly) { IWTimestamp temp = new IWTimestamp(stampToCheck); temp.setAsDate(); if (from.getYear() == to.getYear()) { temp.setYear(from.getYear()); if (bordersCount) { return (temp.isLaterThanOrEquals(from) && to.isLaterThanOrEquals(temp)); } else { return (temp.isLaterThan(from) && to.isLaterThan(temp)); } } else { if (temp.getYear() >= to.getYear()) { if (temp.getMonth() > to.getMonth()) { temp.setYear(from.getYear()); } else { temp.setYear(to.getYear()); } } return isBetween(from, to, temp, false, bordersCount); } } else { if (bordersCount) { return (stampToCheck.isLaterThanOrEquals(from) && to.isLaterThanOrEquals(stampToCheck)); } else { return (stampToCheck.isLaterThan(from) && to.isLaterThan(stampToCheck)); } } } protected ProductPriceBusiness getProductPriceBusiness() { try { return (ProductPriceBusiness) IBOLookup.getServiceInstance(getIWApplicationContext(), ProductPriceBusiness.class); } catch (IBOLookupException e) { throw new IBORuntimeException(e); } } private String getRemoteTravelApplicationUrlCsvList() { if (remoteTravelApplications == null) { try { ICApplicationBindingHome abHome = (ICApplicationBindingHome) IDOLookup.getHome(ICApplicationBinding.class); String icABKey = "RemoteTravelAppUrl"; try { ICApplicationBinding binding = abHome.findByPrimaryKey(icABKey); remoteTravelApplications = binding.getValue(); } catch (FinderException e) { try { IWBundle bundle = getIWMainApplication().getBundle("com.idega.block.trade"); String remoteTravelWebs = bundle.getProperty(REMOTE_TRAVEL_APPLICATION_URL_CSV_LIST,""); ICApplicationBinding binding = abHome.create(); binding.setKey(icABKey); binding.setBindingType("travel.binding"); binding.setValue(remoteTravelWebs); binding.store(); remoteTravelApplications = remoteTravelWebs; } catch (CreateException e1) { e1.printStackTrace(); } } } catch (IDOLookupException e) { e.printStackTrace(); } } return remoteTravelApplications; } public void executeRemoteService(String remoteDomainToExclude, String methodQuery) { executeRemoteService(remoteDomainToExclude, methodQuery, "/idegaweb/bundles/com.idega.block.trade.bundle/resources/services/IWTradeWS.jws"); } /** * <p> * Method for calling methods on remote domains * </p> * @param remoteDomainToExclude * @param methodQuery */ protected void executeRemoteService(String remoteDomainToExclude, String methodQuery, String webserviceURI) { String remoteTravelWebs = getRemoteTravelApplicationUrlCsvList(); if(!"".equals(remoteTravelWebs) && remoteTravelWebs != null){ // log("Invalidating REMOTE stored search results"); String prmCallingServer = "remoteCallingHostName"; String serverName = "unspecified"; try { serverName = AxisUtil.getHttpServletRequest().getServerName(); } catch (Exception e) { serverName = IWContext.getInstance().getRequest().getServerName(); } StringTokenizer tokenizer = new StringTokenizer(remoteTravelWebs,","); while(tokenizer.hasMoreTokens()){ String remoteWeb = tokenizer.nextToken(); if(remoteDomainToExclude == null || remoteWeb.indexOf(remoteDomainToExclude)==-1){ if(remoteWeb.endsWith("/")){ remoteWeb = remoteWeb.substring(0,remoteWeb.length()-1); } String response = FileUtil.getStringFromURL(remoteWeb+webserviceURI+"?method="+methodQuery+"&"+prmCallingServer+"="+serverName); if( response.indexOf("iwtravel-ok")==-1){ logError("Webservice method : "+methodQuery+" failed on : "+remoteWeb+" message was : "+response); } else{ log("Webservice method : "+methodQuery+" successful for :"+remoteWeb); } } else{ log("Skipping round-trip decaching for calling remote server : "+remoteDomainToExclude); } } } } }
false
true
public float getPrice(int productPriceId, int productId, int priceCategoryId, int currencyId, Timestamp time, int timeframeId, int addressId) throws SQLException, RemoteException { /**@todo: Implement this com.idega.block.trade.stockroom.business.SupplyManager method*/ /*skila ver�i ef PRICETYPE_PRICE annars ver�i me� tilliti til afsl�ttar*/ try { PriceCategory cat = ((com.idega.block.trade.stockroom.data.PriceCategoryHome)com.idega.data.IDOLookup.getHomeLegacy(PriceCategory.class)).findByPrimaryKeyLegacy(priceCategoryId); ProductPrice ppr = ((ProductPrice)com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getStaticInstanceIDO(ProductPrice.class)); TravelAddress taddr = ((TravelAddress) com.idega.block.trade.stockroom.data.TravelAddressBMPBean.getStaticInstance(TravelAddress.class)); Timeframe tfr = ((Timeframe) com.idega.block.trade.stockroom.data.TimeframeBMPBean.getStaticInstance(Timeframe.class)); String addrTable = EntityControl.getManyToManyRelationShipTableName(TravelAddress.class, ProductPrice.class); String tfrTable = EntityControl.getManyToManyRelationShipTableName(Timeframe.class, ProductPrice.class); String ppColName = ppr.getEntityDefinition().getPrimaryKeyDefinition().getField().getSQLFieldName(); String ppTable = ppr.getEntityDefinition().getSQLTableName(); if(cat.getType().equals(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_PRICE)){ StringBuffer buffer = new StringBuffer(); buffer.append("select p.* from "+ppTable+" p"); if (timeframeId != -1) { buffer.append(", "+tfrTable+" tm"); } if (addressId != -1) { buffer.append(", "+addrTable+" am"); } buffer.append(" where "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameProductId()+" = "+productId); if (timeframeId != -1) { buffer.append(" and "); buffer.append("tm."+tfr.getIDColumnName()+" = "+timeframeId); buffer.append(" and "); buffer.append("p."+ppColName+" = tm."+ppColName); } if (addressId != -1) { buffer.append(" and "); buffer.append("am."+taddr.getIDColumnName()+" = "+addressId); buffer.append(" and "); buffer.append("p."+ppColName+" = am."+ppColName); } if (productPriceId != -1) { buffer.append(" and "); buffer.append("p."+ppColName+" = "+productPriceId); } buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceCategoryId()+" = "+priceCategoryId); buffer.append(" and "); IWTimestamp stamp = new IWTimestamp(time); // buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameCurrencyId()+" = "+currencyId); // buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+" <= '"+stamp.toSQLString()+"'"); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceType()+" = "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.PRICETYPE_PRICE); //buffer.append(" and "); //buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameIsValid()+" = 'Y'"); buffer.append(" order by p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+ " desc"); // List result = EntityFinder.findAll(ppr,buffer.toString()); // List result = EntityFinder.findAll(ppr,buffer.toString()); ProductPriceHome ppHome = (ProductPriceHome) IDOLookup.getHome(ProductPrice.class); Collection result = ppHome.findBySQL(buffer.toString()); if(result != null && result.size() > 0){ Iterator iter = result.iterator(); ProductPrice price = (ProductPrice) iter.next(); CurrencyHolder iceCurr = CurrencyBusiness.getCurrencyHolder(CurrencyHolder.ICELANDIC_KRONA); if ( iceCurr != null && (price.getCurrencyId() == iceCurr.getCurrencyID())) { return new Float(Math.round( price.getPrice()) ).floatValue(); } else { return price.getPrice(); } }else{ System.err.println(buffer.toString()); throw new ProductPriceException("No Price Was Found"); } }else if(cat.getType().equals(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_DISCOUNT)){ StringBuffer buffer = new StringBuffer(); buffer.append("select p.* from "+ppTable+" p"); if (timeframeId != -1) { buffer.append(", "+tfrTable+" tm"); } if (addressId != -1) { buffer.append(", "+addrTable+" am"); } buffer.append(" where "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameProductId()+" = "+productId); if (timeframeId != -1) { buffer.append(" and "); buffer.append("tm."+tfr.getIDColumnName()+" = "+timeframeId); buffer.append(" and "); buffer.append("p."+ppColName+" = tm."+ppColName); } if (addressId != -1) { buffer.append(" and "); buffer.append("am."+taddr.getIDColumnName()+" = "+addressId); buffer.append(" and "); buffer.append("p."+ppColName+" = am."+ppColName); } buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceCategoryId()+" = "+priceCategoryId); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+" < '"+time.toString()+"'"); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceType()+" = "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.PRICETYPE_DISCOUNT); //buffer.append(" and "); //buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameIsValid()+" = 'Y'"); buffer.append(" order by p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+ " desc"); ProductPriceHome ppHome = (ProductPriceHome) IDOLookup.getHome(ProductPrice.class); Collection result = ppHome.findBySQL(buffer.toString()); // List result = EntityFinder.findAll(ppr,buffer.toString()); float disc = 0; if(result != null && result.size() > 0){ Iterator iter = result.iterator(); ProductPrice price = (ProductPrice) iter.next(); disc = price.getPrice(); } float pr = getPrice(-1, productId,cat.getParentId(),currencyId,time, timeframeId, addressId); return pr*((100-disc) /100); }else{ throw new ProductPriceException("No Price Was Found"); } } catch (FinderException e) { e.printStackTrace(System.err); return 0; } catch (IDOCompositePrimaryKeyException e) { e.printStackTrace(System.err); return 0; } }
public float getPrice(int productPriceId, int productId, int priceCategoryId, int currencyId, Timestamp time, int timeframeId, int addressId) throws SQLException, RemoteException { /**@todo: Implement this com.idega.block.trade.stockroom.business.SupplyManager method*/ /*skila ver�i ef PRICETYPE_PRICE annars ver�i me� tilliti til afsl�ttar*/ try { PriceCategory cat = ((com.idega.block.trade.stockroom.data.PriceCategoryHome)com.idega.data.IDOLookup.getHomeLegacy(PriceCategory.class)).findByPrimaryKeyLegacy(priceCategoryId); ProductPrice ppr = ((ProductPrice)com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getStaticInstanceIDO(ProductPrice.class)); TravelAddress taddr = ((TravelAddress) com.idega.block.trade.stockroom.data.TravelAddressBMPBean.getStaticInstance(TravelAddress.class)); Timeframe tfr = ((Timeframe) com.idega.block.trade.stockroom.data.TimeframeBMPBean.getStaticInstance(Timeframe.class)); String addrTable = EntityControl.getManyToManyRelationShipTableName(TravelAddress.class, ProductPrice.class); String tfrTable = EntityControl.getManyToManyRelationShipTableName(Timeframe.class, ProductPrice.class); String ppColName = ppr.getEntityDefinition().getPrimaryKeyDefinition().getField().getSQLFieldName(); String ppTable = ppr.getEntityDefinition().getSQLTableName(); if(cat.getType().equals(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_PRICE)){ StringBuffer buffer = new StringBuffer(); buffer.append("select p.* from "+ppTable+" p"); if (timeframeId != -1) { buffer.append(", "+tfrTable+" tm"); } if (addressId != -1) { buffer.append(", "+addrTable+" am"); } buffer.append(" where "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameProductId()+" = "+productId); if (timeframeId != -1) { buffer.append(" and "); buffer.append("tm."+tfr.getIDColumnName()+" = "+timeframeId); buffer.append(" and "); buffer.append("p."+ppColName+" = tm."+ppColName); } if (addressId != -1) { buffer.append(" and "); buffer.append("am."+taddr.getIDColumnName()+" = "+addressId); buffer.append(" and "); buffer.append("p."+ppColName+" = am."+ppColName); } if (productPriceId != -1) { buffer.append(" and "); buffer.append("p."+ppColName+" = "+productPriceId); } buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceCategoryId()+" = "+priceCategoryId); buffer.append(" and "); IWTimestamp stamp = new IWTimestamp(time); // buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameCurrencyId()+" = "+currencyId); // buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+" <= '"+stamp.toSQLString()+"'"); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceType()+" = "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.PRICETYPE_PRICE); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameCurrencyId()+" = "+currencyId); //buffer.append(" and "); //buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameIsValid()+" = 'Y'"); buffer.append(" order by p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+ " desc"); // List result = EntityFinder.findAll(ppr,buffer.toString()); // List result = EntityFinder.findAll(ppr,buffer.toString()); ProductPriceHome ppHome = (ProductPriceHome) IDOLookup.getHome(ProductPrice.class); Collection result = ppHome.findBySQL(buffer.toString()); if(result != null && result.size() > 0){ Iterator iter = result.iterator(); ProductPrice price = (ProductPrice) iter.next(); CurrencyHolder iceCurr = CurrencyBusiness.getCurrencyHolder(CurrencyHolder.ICELANDIC_KRONA); if ( iceCurr != null && (price.getCurrencyId() == iceCurr.getCurrencyID())) { return new Float(Math.round( price.getPrice()) ).floatValue(); } else { return price.getPrice(); } }else{ System.err.println(buffer.toString()); throw new ProductPriceException("No Price Was Found"); } }else if(cat.getType().equals(com.idega.block.trade.stockroom.data.PriceCategoryBMPBean.PRICETYPE_DISCOUNT)){ StringBuffer buffer = new StringBuffer(); buffer.append("select p.* from "+ppTable+" p"); if (timeframeId != -1) { buffer.append(", "+tfrTable+" tm"); } if (addressId != -1) { buffer.append(", "+addrTable+" am"); } buffer.append(" where "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameProductId()+" = "+productId); if (timeframeId != -1) { buffer.append(" and "); buffer.append("tm."+tfr.getIDColumnName()+" = "+timeframeId); buffer.append(" and "); buffer.append("p."+ppColName+" = tm."+ppColName); } if (addressId != -1) { buffer.append(" and "); buffer.append("am."+taddr.getIDColumnName()+" = "+addressId); buffer.append(" and "); buffer.append("p."+ppColName+" = am."+ppColName); } buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceCategoryId()+" = "+priceCategoryId); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+" < '"+time.toString()+"'"); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceType()+" = "+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.PRICETYPE_DISCOUNT); buffer.append(" and "); buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameCurrencyId()+" = "+currencyId); //buffer.append(" and "); //buffer.append("p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNameIsValid()+" = 'Y'"); buffer.append(" order by p."+com.idega.block.trade.stockroom.data.ProductPriceBMPBean.getColumnNamePriceDate()+ " desc"); ProductPriceHome ppHome = (ProductPriceHome) IDOLookup.getHome(ProductPrice.class); Collection result = ppHome.findBySQL(buffer.toString()); // List result = EntityFinder.findAll(ppr,buffer.toString()); float disc = 0; if(result != null && result.size() > 0){ Iterator iter = result.iterator(); ProductPrice price = (ProductPrice) iter.next(); disc = price.getPrice(); } float pr = getPrice(-1, productId,cat.getParentId(),currencyId,time, timeframeId, addressId); return pr*((100-disc) /100); }else{ throw new ProductPriceException("No Price Was Found"); } } catch (FinderException e) { e.printStackTrace(System.err); return 0; } catch (IDOCompositePrimaryKeyException e) { e.printStackTrace(System.err); return 0; } }
diff --git a/src/generator/org/hamcrest/generator/config/XmlConfigurator.java b/src/generator/org/hamcrest/generator/config/XmlConfigurator.java index f52f8d3..887cba0 100644 --- a/src/generator/org/hamcrest/generator/config/XmlConfigurator.java +++ b/src/generator/org/hamcrest/generator/config/XmlConfigurator.java @@ -1,104 +1,104 @@ package org.hamcrest.generator.config; import org.hamcrest.generator.HamcrestFactoryWriter; import org.hamcrest.generator.QuickReferenceWriter; import org.hamcrest.generator.ReflectiveFactoryReader; import org.hamcrest.generator.SugarConfiguration; import org.hamcrest.generator.SugarGenerator; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class XmlConfigurator { private final SugarConfiguration sugarConfiguration; private final ClassLoader classLoader; private final SAXParserFactory saxParserFactory; public XmlConfigurator(SugarConfiguration sugarConfiguration, ClassLoader classLoader) { this.sugarConfiguration = sugarConfiguration; this.classLoader = classLoader; saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setNamespaceAware(true); } public void load(InputSource inputSource) throws ParserConfigurationException, SAXException, IOException { SAXParser saxParser = saxParserFactory.newSAXParser(); saxParser.parse(inputSource, new DefaultHandler() { public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("factory")) { String className = attributes.getValue("class"); try { addClass(className); } catch (ClassNotFoundException e) { throw new SAXException("Cannot find Matcher class : " + className); } } } }); } private void addClass(String className) throws ClassNotFoundException { Class cls = classLoader.loadClass(className); sugarConfiguration.addFactoryMethods(new ReflectiveFactoryReader(cls)); } public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Args: config-file generated-class output-dir"); System.err.println(""); System.err.println(" config-file : Path to config file listing matchers to generate sugar for."); System.err.println(" e.g. path/to/matchers.xml"); System.err.println(""); System.err.println("generated-class : Full name of class to generate."); System.err.println(" e.g. org.myproject.MyMatchers"); System.err.println(""); System.err.println(" output-dir : Where to output generated code (package subdirs will be"); System.err.println(" automatically created)."); System.err.println(" e.g. build/generated-code"); System.exit(-1); } String configFile = args[0]; String fullClassName = args[1]; File outputDir = new File(args[2]); - String fileName = fullClassName.replaceAll("\\.", File.separator) + ".java"; + String fileName = fullClassName.replace('.', File.separatorChar) + ".java"; int dotIndex = fullClassName.lastIndexOf("."); String packageName = dotIndex == -1 ? "" : fullClassName.substring(0, dotIndex); String shortClassName = fullClassName.substring(dotIndex + 1); if (!outputDir.isDirectory()) { System.err.println("Output directory not found : " + outputDir.getAbsolutePath()); System.exit(-1); } File outputFile = new File(outputDir, fileName); outputFile.getParentFile().mkdirs(); SugarGenerator sugarGenerator = new SugarGenerator(); try { sugarGenerator.addWriter(new HamcrestFactoryWriter( packageName, shortClassName, new FileWriter(outputFile))); sugarGenerator.addWriter(new QuickReferenceWriter(System.out)); XmlConfigurator xmlConfigurator = new XmlConfigurator(sugarGenerator, XmlConfigurator.class.getClassLoader()); xmlConfigurator.load(new InputSource(configFile)); System.out.println("Generating " + fullClassName); sugarGenerator.generate(); } finally { sugarGenerator.close(); } } }
true
true
public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Args: config-file generated-class output-dir"); System.err.println(""); System.err.println(" config-file : Path to config file listing matchers to generate sugar for."); System.err.println(" e.g. path/to/matchers.xml"); System.err.println(""); System.err.println("generated-class : Full name of class to generate."); System.err.println(" e.g. org.myproject.MyMatchers"); System.err.println(""); System.err.println(" output-dir : Where to output generated code (package subdirs will be"); System.err.println(" automatically created)."); System.err.println(" e.g. build/generated-code"); System.exit(-1); } String configFile = args[0]; String fullClassName = args[1]; File outputDir = new File(args[2]); String fileName = fullClassName.replaceAll("\\.", File.separator) + ".java"; int dotIndex = fullClassName.lastIndexOf("."); String packageName = dotIndex == -1 ? "" : fullClassName.substring(0, dotIndex); String shortClassName = fullClassName.substring(dotIndex + 1); if (!outputDir.isDirectory()) { System.err.println("Output directory not found : " + outputDir.getAbsolutePath()); System.exit(-1); } File outputFile = new File(outputDir, fileName); outputFile.getParentFile().mkdirs(); SugarGenerator sugarGenerator = new SugarGenerator(); try { sugarGenerator.addWriter(new HamcrestFactoryWriter( packageName, shortClassName, new FileWriter(outputFile))); sugarGenerator.addWriter(new QuickReferenceWriter(System.out)); XmlConfigurator xmlConfigurator = new XmlConfigurator(sugarGenerator, XmlConfigurator.class.getClassLoader()); xmlConfigurator.load(new InputSource(configFile)); System.out.println("Generating " + fullClassName); sugarGenerator.generate(); } finally { sugarGenerator.close(); } }
public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Args: config-file generated-class output-dir"); System.err.println(""); System.err.println(" config-file : Path to config file listing matchers to generate sugar for."); System.err.println(" e.g. path/to/matchers.xml"); System.err.println(""); System.err.println("generated-class : Full name of class to generate."); System.err.println(" e.g. org.myproject.MyMatchers"); System.err.println(""); System.err.println(" output-dir : Where to output generated code (package subdirs will be"); System.err.println(" automatically created)."); System.err.println(" e.g. build/generated-code"); System.exit(-1); } String configFile = args[0]; String fullClassName = args[1]; File outputDir = new File(args[2]); String fileName = fullClassName.replace('.', File.separatorChar) + ".java"; int dotIndex = fullClassName.lastIndexOf("."); String packageName = dotIndex == -1 ? "" : fullClassName.substring(0, dotIndex); String shortClassName = fullClassName.substring(dotIndex + 1); if (!outputDir.isDirectory()) { System.err.println("Output directory not found : " + outputDir.getAbsolutePath()); System.exit(-1); } File outputFile = new File(outputDir, fileName); outputFile.getParentFile().mkdirs(); SugarGenerator sugarGenerator = new SugarGenerator(); try { sugarGenerator.addWriter(new HamcrestFactoryWriter( packageName, shortClassName, new FileWriter(outputFile))); sugarGenerator.addWriter(new QuickReferenceWriter(System.out)); XmlConfigurator xmlConfigurator = new XmlConfigurator(sugarGenerator, XmlConfigurator.class.getClassLoader()); xmlConfigurator.load(new InputSource(configFile)); System.out.println("Generating " + fullClassName); sugarGenerator.generate(); } finally { sugarGenerator.close(); } }
diff --git a/vlc-android/src/org/videolan/vlc/android/DatabaseManager.java b/vlc-android/src/org/videolan/vlc/android/DatabaseManager.java index 3a916b9d..3f96bcb8 100644 --- a/vlc-android/src/org/videolan/vlc/android/DatabaseManager.java +++ b/vlc-android/src/org/videolan/vlc/android/DatabaseManager.java @@ -1,440 +1,440 @@ package org.videolan.vlc.android; import java.io.ByteArrayOutputStream; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class DatabaseManager { public final static String TAG = "VLC/DatabaseManager"; private static DatabaseManager instance; private SQLiteDatabase mDb; private final String DB_NAME = "vlc_database"; private final int DB_VERSION = 5; private final String DIR_TABLE_NAME = "directories_table"; private final String DIR_ROW_PATH = "path"; private final String MEDIA_TABLE_NAME = "media_table"; private final String MEDIA_PATH = "path"; private final String MEDIA_TIME = "time"; private final String MEDIA_LENGTH = "length"; private final String MEDIA_TYPE = "type"; private final String MEDIA_PICTURE = "picture"; private final String MEDIA_TITLE = "title"; private final String MEDIA_ARTIST = "artist"; private final String MEDIA_GENRE = "genre"; private final String MEDIA_ALBUM = "album"; private final String PLAYLIST_TABLE_NAME = "playlist_table"; private final String PLAYLIST_NAME = "name"; private final String PLAYLIST_MEDIA_TABLE_NAME = "playlist_media_table"; private final String PLAYLIST_MEDIA_ID = "id"; private final String PLAYLIST_MEDIA_PLAYLISTNAME = "playlist_name"; private final String PLAYLIST_MEDIA_MEDIAPATH = "media_path"; private final String SEARCHHISTORY_TABLE_NAME = "searchhistory_table"; private final String SEARCHHISTORY_DATE = "date"; private final String SEARCHHISTORY_KEY = "key"; private Context mContext; public enum mediaColumn { MEDIA_TABLE_NAME, MEDIA_PATH, MEDIA_TIME, MEDIA_LENGTH, MEDIA_TYPE, MEDIA_PICTURE, MEDIA_TITLE, MEDIA_ARTIST, MEDIA_GENRE, MEDIA_ALBUM } /** * Constructor * * @param context */ private DatabaseManager(Context context) { mContext = context; // create or open database DatabaseHelper helper = new DatabaseHelper(context); this.mDb = helper.getWritableDatabase(); } public synchronized static DatabaseManager getInstance() { if (instance == null) { Context context = MainActivity.getInstance(); instance = new DatabaseManager(context); } return instance; } private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createDirTabelQuery = "CREATE TABLE IF NOT EXISTS " + DIR_TABLE_NAME + " (" + DIR_ROW_PATH + " TEXT PRIMARY KEY NOT NULL" + ");"; // Create the directories table db.execSQL(createDirTabelQuery); String createMediaTabelQuery = "CREATE TABLE IF NOT EXISTS " + MEDIA_TABLE_NAME + " (" + MEDIA_PATH + " TEXT PRIMARY KEY NOT NULL, " + MEDIA_TIME + " INTEGER, " + MEDIA_LENGTH + " INTEGER, " + MEDIA_TYPE + " INTEGER, " + MEDIA_PICTURE + " BLOB, " + MEDIA_TITLE + " VARCHAR(200), " + MEDIA_ARTIST + " VARCHAR(200), " + MEDIA_GENRE + " VARCHAR(200), " + MEDIA_ALBUM + " VARCHAR(200)" + ");"; // Create the media table db.execSQL(createMediaTabelQuery); String createPlaylistTableQuery = "CREATE TABLE IF NOT EXISTS " + PLAYLIST_TABLE_NAME + " (" + PLAYLIST_NAME + " VARCHAR(200) PRIMARY KEY NOT NULL);"; db.execSQL(createPlaylistTableQuery); - String createPlaylistMediaTableQuery = "CREATE TABLE IF NOT EXISTS " + + /*String createPlaylistMediaTableQuery = "CREATE TABLE IF NOT EXISTS " + PLAYLIST_MEDIA_TABLE_NAME + " (" + PLAYLIST_MEDIA_ID + " INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT, " + PLAYLIST_MEDIA_PLAYLISTNAME + " VARCHAR(200) NOT NULL," + PLAYLIST_MEDIA_MEDIAPATH + " TEXT NOT NULL);"; - db.execSQL(createPlaylistMediaTableQuery); + db.execSQL(createPlaylistMediaTableQuery);*/ String createSearchhistoryTabelQuery = "CREATE TABLE IF NOT EXISTS " + SEARCHHISTORY_TABLE_NAME + " (" + SEARCHHISTORY_KEY + " VARCHAR(200) PRIMARY KEY NOT NULL, " + SEARCHHISTORY_DATE + " DATETIME NOT NULL" + ");"; // Create the searchhistory table db.execSQL(createSearchhistoryTabelQuery); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO ?? } } /** * Get all playlists in the database * @return */ public String[] getPlaylists() { ArrayList<String> playlists = new ArrayList<String>(); Cursor cursor; cursor = mDb.query( PLAYLIST_TABLE_NAME, new String[] { PLAYLIST_NAME }, null, null, null, null, null); cursor.moveToFirst(); if (!cursor.isAfterLast()) { do { playlists.add(cursor.getString(10)); } while (cursor.moveToNext()); } cursor.close(); return (String[]) playlists.toArray(); } /** * Add new playlist * @param name * @return id of the new playlist */ public void addPlaylist(String name) { ContentValues values = new ContentValues(); values.put(PLAYLIST_NAME, name); mDb.insert(PLAYLIST_TABLE_NAME, "NULL", values); } public void deletePlaylist(String name) { mDb.delete(PLAYLIST_TABLE_NAME, PLAYLIST_NAME + "=?", new String[] { name }); } public void addMediaToPlaylist(String playlistName, String mediaPath) { ContentValues values = new ContentValues(); values.put(PLAYLIST_MEDIA_PLAYLISTNAME, playlistName); values.put(PLAYLIST_MEDIA_MEDIAPATH, mediaPath); } public void removeMediaFromPlaylist(String playlistName, String mediaPath) { mDb.delete(PLAYLIST_MEDIA_TABLE_NAME, PLAYLIST_MEDIA_PLAYLISTNAME + "=? " + PLAYLIST_MEDIA_MEDIAPATH + "=?", new String[] { playlistName, mediaPath}); } public Media[] getMediaFromPlaylist(String playlistName) { ArrayList<Media> media = new ArrayList<Media>(); Cursor cursor = mDb.query(PLAYLIST_MEDIA_PLAYLISTNAME, new String[] { PLAYLIST_MEDIA_MEDIAPATH }, PLAYLIST_MEDIA_PLAYLISTNAME + "=?", new String[]{ playlistName }, null, null, "ASC"); MediaLibrary mediaLibrary = MediaLibrary.getInstance(mContext); cursor.moveToFirst(); if (!cursor.isAfterLast()) { do { media.add(mediaLibrary.getMediaItem(cursor.getString(0))); } while (cursor.moveToNext()); } cursor.close(); return (Media[])media.toArray(); } /** * Add a new media to the database. The picture can only added by update. * @param meida which you like to add to the database */ public synchronized void addMedia(Media media) { ContentValues values = new ContentValues(); values.put(MEDIA_PATH, media.getPath()); values.put(MEDIA_TIME, media.getTime()); values.put(MEDIA_LENGTH, media.getLength()); values.put(MEDIA_TYPE, media.getType()); values.put(MEDIA_TITLE, media.getTitle()); values.put(MEDIA_ARTIST, media.getArtist()); values.put(MEDIA_GENRE, media.getGenre()); values.put(MEDIA_ALBUM, media.getAlbum()); mDb.replace(MEDIA_TABLE_NAME, "NULL", values); } // /** // * Check if the item already in the database // * @param path of the item (primary key) // * @return // */ // public synchronized boolean mediaItemExists(String path) { // Cursor cursor = mDb.query(MEDIA_TABLE_NAME, // new String[] { DIR_ROW_PATH }, // MEDIA_PATH + "=?", // new String[] { path }, // null, null, null); // boolean exists = cursor.moveToFirst(); // cursor.close(); // return exists; // } /** * Get all paths from the items in the database * @return list of File */ public synchronized List<File> getMediaFiles() { List<File> files = new ArrayList<File>(); Cursor cursor; cursor = mDb.query( MEDIA_TABLE_NAME, new String[] { MEDIA_PATH }, null, null, null, null, null); cursor.moveToFirst(); if (!cursor.isAfterLast()) { do { File file = new File(cursor.getString(0)); files.add(file); } while (cursor.moveToNext()); } cursor.close(); return files; } public synchronized Media getMedia(String path) { Cursor cursor; Media media = null; Bitmap picture = null; byte[] blob; cursor = mDb.query( MEDIA_TABLE_NAME, new String[] { MEDIA_TIME, //0 long MEDIA_LENGTH, //1 long MEDIA_TYPE, //2 int MEDIA_PICTURE, //3 Bitmap MEDIA_TITLE, //4 string MEDIA_ARTIST, //5 string MEDIA_GENRE, //6 string MEDIA_ALBUM //7 string }, MEDIA_PATH + "=?", new String[] { path }, null, null, null); if (cursor.moveToFirst()) { blob = cursor.getBlob(3); if (blob != null) { picture = BitmapFactory.decodeByteArray(blob, 0, blob.length); } media = new Media(mContext, new File(path), cursor.getLong(0), cursor.getLong(1), cursor.getInt(2), picture, cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7)); } return media; } public synchronized void removeMedia(String path) { mDb.delete(MEDIA_TABLE_NAME, MEDIA_PATH + "=?", new String[] { path }); } public synchronized void updateMedia(String path, mediaColumn col, Object object ) { ContentValues values = new ContentValues(); switch (col) { case MEDIA_PICTURE: Bitmap picture = (Bitmap)object; ByteArrayOutputStream out = new ByteArrayOutputStream(); picture.compress(Bitmap.CompressFormat.PNG, 100, out); values.put(MEDIA_PICTURE, out.toByteArray()); break; default: return; } mDb.update(MEDIA_TABLE_NAME, values, MEDIA_PATH +"=?", new String[] { path }); } /** * Add directory to the directories table * * @param path */ public synchronized void addDir(String path) { if (!mediaDirExists(path)) { ContentValues values = new ContentValues(); values.put(DIR_ROW_PATH, path); mDb.insert(DIR_TABLE_NAME, null, values); } } /** * Delete directory from directories table * * @param path */ public synchronized void removeDir(String path) { mDb.delete(DIR_TABLE_NAME, DIR_ROW_PATH + "=?", new String[] { path }); } /** * * @return */ public synchronized List<File> getMediaDirs() { List<File> paths = new ArrayList<File>(); Cursor cursor; cursor = mDb.query( DIR_TABLE_NAME, new String[] { DIR_ROW_PATH }, null, null, null, null, null); cursor.moveToFirst(); if (!cursor.isAfterLast()) { do { File dir = new File(cursor.getString(0)); paths.add(dir); } while (cursor.moveToNext()); } cursor.close(); return paths; } public synchronized boolean mediaDirExists(String path) { Cursor cursor = mDb.query(DIR_TABLE_NAME, new String[] { DIR_ROW_PATH }, DIR_ROW_PATH + "=?", new String[] { path }, null, null, null); boolean exists = cursor.moveToFirst(); cursor.close(); return exists; } /** * * @param key */ public synchronized void addSearchhistoryItem(String key) { // set the format to sql date time SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); ContentValues values = new ContentValues(); values.put(SEARCHHISTORY_KEY, key); values.put(SEARCHHISTORY_DATE, dateFormat.format(date)); mDb.replace(SEARCHHISTORY_TABLE_NAME, null, values); } public synchronized ArrayList<String> getSearchhistory(int size) { ArrayList<String> history = new ArrayList<String>(); Cursor cursor = mDb.query(SEARCHHISTORY_TABLE_NAME, new String[] { SEARCHHISTORY_KEY }, null, null, null, null, SEARCHHISTORY_DATE + " DESC", Integer.toString(size)); while(cursor.moveToNext()) { history.add(cursor.getString(0)); } cursor.close(); return history; } public synchronized void clearSearchhistory() { mDb.delete(SEARCHHISTORY_TABLE_NAME, null, null); } }
false
true
public void onCreate(SQLiteDatabase db) { String createDirTabelQuery = "CREATE TABLE IF NOT EXISTS " + DIR_TABLE_NAME + " (" + DIR_ROW_PATH + " TEXT PRIMARY KEY NOT NULL" + ");"; // Create the directories table db.execSQL(createDirTabelQuery); String createMediaTabelQuery = "CREATE TABLE IF NOT EXISTS " + MEDIA_TABLE_NAME + " (" + MEDIA_PATH + " TEXT PRIMARY KEY NOT NULL, " + MEDIA_TIME + " INTEGER, " + MEDIA_LENGTH + " INTEGER, " + MEDIA_TYPE + " INTEGER, " + MEDIA_PICTURE + " BLOB, " + MEDIA_TITLE + " VARCHAR(200), " + MEDIA_ARTIST + " VARCHAR(200), " + MEDIA_GENRE + " VARCHAR(200), " + MEDIA_ALBUM + " VARCHAR(200)" + ");"; // Create the media table db.execSQL(createMediaTabelQuery); String createPlaylistTableQuery = "CREATE TABLE IF NOT EXISTS " + PLAYLIST_TABLE_NAME + " (" + PLAYLIST_NAME + " VARCHAR(200) PRIMARY KEY NOT NULL);"; db.execSQL(createPlaylistTableQuery); String createPlaylistMediaTableQuery = "CREATE TABLE IF NOT EXISTS " + PLAYLIST_MEDIA_TABLE_NAME + " (" + PLAYLIST_MEDIA_ID + " INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT, " + PLAYLIST_MEDIA_PLAYLISTNAME + " VARCHAR(200) NOT NULL," + PLAYLIST_MEDIA_MEDIAPATH + " TEXT NOT NULL);"; db.execSQL(createPlaylistMediaTableQuery); String createSearchhistoryTabelQuery = "CREATE TABLE IF NOT EXISTS " + SEARCHHISTORY_TABLE_NAME + " (" + SEARCHHISTORY_KEY + " VARCHAR(200) PRIMARY KEY NOT NULL, " + SEARCHHISTORY_DATE + " DATETIME NOT NULL" + ");"; // Create the searchhistory table db.execSQL(createSearchhistoryTabelQuery); }
public void onCreate(SQLiteDatabase db) { String createDirTabelQuery = "CREATE TABLE IF NOT EXISTS " + DIR_TABLE_NAME + " (" + DIR_ROW_PATH + " TEXT PRIMARY KEY NOT NULL" + ");"; // Create the directories table db.execSQL(createDirTabelQuery); String createMediaTabelQuery = "CREATE TABLE IF NOT EXISTS " + MEDIA_TABLE_NAME + " (" + MEDIA_PATH + " TEXT PRIMARY KEY NOT NULL, " + MEDIA_TIME + " INTEGER, " + MEDIA_LENGTH + " INTEGER, " + MEDIA_TYPE + " INTEGER, " + MEDIA_PICTURE + " BLOB, " + MEDIA_TITLE + " VARCHAR(200), " + MEDIA_ARTIST + " VARCHAR(200), " + MEDIA_GENRE + " VARCHAR(200), " + MEDIA_ALBUM + " VARCHAR(200)" + ");"; // Create the media table db.execSQL(createMediaTabelQuery); String createPlaylistTableQuery = "CREATE TABLE IF NOT EXISTS " + PLAYLIST_TABLE_NAME + " (" + PLAYLIST_NAME + " VARCHAR(200) PRIMARY KEY NOT NULL);"; db.execSQL(createPlaylistTableQuery); /*String createPlaylistMediaTableQuery = "CREATE TABLE IF NOT EXISTS " + PLAYLIST_MEDIA_TABLE_NAME + " (" + PLAYLIST_MEDIA_ID + " INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT, " + PLAYLIST_MEDIA_PLAYLISTNAME + " VARCHAR(200) NOT NULL," + PLAYLIST_MEDIA_MEDIAPATH + " TEXT NOT NULL);"; db.execSQL(createPlaylistMediaTableQuery);*/ String createSearchhistoryTabelQuery = "CREATE TABLE IF NOT EXISTS " + SEARCHHISTORY_TABLE_NAME + " (" + SEARCHHISTORY_KEY + " VARCHAR(200) PRIMARY KEY NOT NULL, " + SEARCHHISTORY_DATE + " DATETIME NOT NULL" + ");"; // Create the searchhistory table db.execSQL(createSearchhistoryTabelQuery); }
diff --git a/src/java-client-framework/org/xins/client/CallTargetGroup.java b/src/java-client-framework/org/xins/client/CallTargetGroup.java index 4112e76a6..88358f797 100644 --- a/src/java-client-framework/org/xins/client/CallTargetGroup.java +++ b/src/java-client-framework/org/xins/client/CallTargetGroup.java @@ -1,594 +1,594 @@ /* * $Id$ */ package org.xins.client; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.HashMap; import java.util.Map; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.text.HexConverter; /** * Grouping of function callers. This grouping is of a certain type (see * {@link #getType()}) that sets the algorithm to be used to determine what * underlying actual function caller is used to call the remote API * implementation. A <code>CallTargetGroup</code> can contain other * <code>CallTargetGroup</code> instances. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>) * * @since XINS 0.41 */ public abstract class CallTargetGroup extends AbstractCompositeFunctionCaller { //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- /** * The <em>ordered</em> call target group type. The name of this type is: * <code>"ordered"</code>. */ public static final Type ORDERED_TYPE = new Type("ordered"); /** * The <em>random</em> call target group type. The name of this type is: * <code>"random"</code>. */ public static final Type RANDOM_TYPE = new Type("random"); //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- /** * Gets the type with the specified name. * * @param name * the name of the type, cannot be <code>null</code>. * * @return * the type with the specified name, or <code>null</code> if there is no * type with the specified name. * * @throws IllegalArgumentException * if <code>name == null</code>. * * @since XINS 0.45 */ public static final Type getTypeByName(String name) throws IllegalArgumentException { // Recognize existing types if (ORDERED_TYPE.getName().equals(name)) { return ORDERED_TYPE; } else if (RANDOM_TYPE.getName().equals(name)) { return RANDOM_TYPE; // Fail if name is null } else if (name == null) { throw new IllegalArgumentException("name == null"); // Otherwise: not found, return null } else { return null; } } /** * Creates a new <code>CallTargetGroup</code> of the specified type, using * the specified URL. The host name in the URL may resolve to multiple IP * addresses. Each one will be added as a member. * * @param type * the type, either {@link #ORDERED_TYPE}, or * {@link #RANDOM_TYPE}, cannot be <code>null</code>. * * @param url * the {@link URL} that is used to create {@link FunctionCaller} * members, one per resolved IP address, cannot be <code>null</code>. * * @return * the <code>CallTargetGroup</code>, cannot be <code>null</code>. * * @throws IllegalArgumentException * if <code>type == null || url == null</code>. * * @throws SecurityException * if a security manager does not allow the DNS lookup operation for the * host specified in the URL. * * @throws UnknownHostException * if no IP address could be found for the host specified in the URL. * * @since XINS 0.44 */ public final static CallTargetGroup create(Type type, URL url) throws IllegalArgumentException, SecurityException, UnknownHostException { // Check preconditions MandatoryArgumentChecker.check("type", type, "url", url); // TODO: Make sure there are no ActualFunctionCaller instances with duplicate CRC-32 values List members = new ArrayList(); String hostName = url.getHost(); InetAddress[] addresses = InetAddress.getAllByName(hostName); int addressCount = addresses.length; try { for (int i = 0; i < addressCount; i++) { URL afcURL = new URL(url.getProtocol(), // protocol addresses[i].getHostAddress(), // host url.getPort(), // port url.getFile()); // file members.add(new ActualFunctionCaller(afcURL, hostName)); } } catch (MalformedURLException mue) { throw new Error("Caught MalformedURLException for a protocol that was previously accepted: \"" + url.getProtocol() + "\"."); } catch (MultipleIPAddressesException miae) { throw new Error("Caught MultipleIPAddressesException while only using resolved IP addresses."); } return create(type, members); } /** * Creates a new <code>CallTargetGroup</code> of the specified type, with * the specified members. * * @param type * the type, either {@link #ORDERED_TYPE}, or {@link #RANDOM_TYPE}, * cannot be <code>null</code>. * * @param members * the {@link List} of {@link FunctionCaller} members, cannot be * <code>null</code>. * * @return * the <code>CallTargetGroup</code>, cannot be <code>null</code>. * * @throws IllegalArgumentException * if <code>type == null || members == null</code>. */ public final static CallTargetGroup create(Type type, List members) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("type", type, "members", members); // Return an instance of a CallTargetGroup subclass if (type == ORDERED_TYPE) { return new OrderedCallTargetGroup(members); } else if (type == RANDOM_TYPE) { return new RandomCallTargetGroup(members); } else { throw new Error("Type not recognized."); } } //------------------------------------------------------------------------- // Constructors //------------------------------------------------------------------------- /** * Constructs a new <code>CallTargetGroup</code>. * * @param type * the type, cannot be <code>null</code>. * * @param members * the members for this group, cannot be <code>null</code>. * * @throws IllegalArgumentException * if <code>type == null || members == null || !(members.get(<em>i</em>) * instanceof FunctionCaller)</code> (where 0 &lt;= <em>i</em> &lt; * <code>members.size()</code>). */ CallTargetGroup(Type type, List members) throws IllegalArgumentException { super(members); // Check preconditions MandatoryArgumentChecker.check("type", type); // Initialize fields _type = type; _actualFunctionCallers = new ArrayList(); _actualFunctionCallersByURL = new HashMap(); _actualFunctionCallersByURLChecksum = new HashMap(); _actualFunctionCallersByURLChecksumString = new HashMap(); addActualFunctionCallers(members); } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- /** * The type of this group. This field cannot be <code>null</code>. */ private final Type _type; /** * List of <code>ActualFunctionCaller</code> instances. This {@link List} * cannot be <code>null</code>. */ private final List _actualFunctionCallers; /** * Mappings from URLs to <code>ActualFunctionCaller</code>. The URLs are * stored as {@link String} instances. This {@link Map} cannot be * <code>null</code>. */ private final Map _actualFunctionCallersByURL; /** * Mappings from URL checksums to <code>ActualFunctionCaller</code>. The * checksums are stored as {@link Long} instances. This {@link Map} cannot be * <code>null</code>. */ private final Map _actualFunctionCallersByURLChecksum; /** * Mappings from URL checksum strings to <code>ActualFunctionCaller</code>. * The checksums are stored as {@link String} instances. This {@link Map} * cannot be <code>null</code>. */ private final Map _actualFunctionCallersByURLChecksumString; //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Stores all actual function callers by URL that are found in the * specified list of function callers. * * @param members * the list of function callers, can be <code>null</code>. * * @throws IllegalArgumentException * if <code>!(members.get(<em>i</em>) instanceof FunctionCaller)</code> * (where 0 &lt;= <em>i</em> &lt; <code>members.size()</code>). */ private final void addActualFunctionCallers(List members) throws IllegalArgumentException { int memberCount = members == null ? 0 : members.size(); for (int i = 0; i < memberCount; i++) { FunctionCaller member; // Get the member and make sure it is a FunctionCaller instance try { member = (FunctionCaller) members.get(i); if (member == null) { throw new IllegalArgumentException("members.get(" + i + ") == null"); } } catch (ClassCastException cce) { throw new IllegalArgumentException("members.get(" + i + ") is an instance of " + members.get(i).getClass().getName() + '.'); } // If the member is an actual function caller, store a reference if (member instanceof ActualFunctionCaller) { ActualFunctionCaller afc = (ActualFunctionCaller) member; // Store the ActualFunctionCaller self _actualFunctionCallers.add(afc); // Store the ActualFunctionCaller by URL String url = afc.getURL().toString(); _actualFunctionCallersByURL.put(url, afc); // Store the ActualFunctionCaller by URL checksum long checksum = afc.getCRC32(); Long l = new Long(checksum); ActualFunctionCaller afc0 = (ActualFunctionCaller) _actualFunctionCallersByURLChecksum.get(l); if (afc0 != null) { throw new IllegalArgumentException("List contains two ActualFunctionCaller instances that have the same CRC-32 checksum. URL of first is \"" + afc0.getURL().toString() + "\", URL of second is \"" + afc.getURL().toString() + '.'); } _actualFunctionCallersByURLChecksum.put(l, afc); // Store the ActualFunctionCaller by URL checksum string - _actualFunctionCallersByURLChecksumString.put(HexConverter.toHexString(checksum), afc); + _actualFunctionCallersByURLChecksumString.put(afc.getCRC32String(), afc); // If the member is composite, get all its members } else if (member instanceof CompositeFunctionCaller) { CompositeFunctionCaller cfc = (CompositeFunctionCaller) member; addActualFunctionCallers(cfc.getMembers()); } } } public List getActualFunctionCallers() { return Collections.unmodifiableList(_actualFunctionCallers); } /** * Returns the type of this group. * * @return * the type of this group, either {@link #ORDERED_TYPE}, or * {@link #RANDOM_TYPE}. */ public final Type getType() { return _type; } /** * Gets the actual function caller for the specified URL. * * @param url * the URL of the API to get the actual function caller for, not * <code>null</code>. * * @return * the actual function caller for the specified URL, or * <code>null</code> if there is no {@link ActualFunctionCaller} for the * specified URL in this group or any of the contained groups (if any). * * @throws IllegalArgumentException * if <code>url == null</code>. */ public final ActualFunctionCaller getActualFunctionCaller(String url) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("url", url); return (ActualFunctionCaller) _actualFunctionCallersByURL.get(url); } /** * Gets the actual function caller for the specified URL checksum. * * @param checksum * the CRC-32 checksum of the API URL. * * @return * the actual function caller for the specified checksum, or * <code>null</code> if there is no {@link ActualFunctionCaller} for the * specified URL checksum in this group or any of the contained groups * (if any). */ public final ActualFunctionCaller getActualFunctionCaller(long checksum) { return (ActualFunctionCaller) _actualFunctionCallersByURLChecksum.get(new Long(checksum)); } public final ActualFunctionCaller getActualFunctionCallerByCRC32(String crc32) throws IllegalArgumentException { return (ActualFunctionCaller) _actualFunctionCallersByURLChecksumString.get(crc32); } public final CallResult call(String sessionID, String functionName, Map parameters) throws IllegalArgumentException, CallIOException, InvalidCallResultException { // Check preconditions MandatoryArgumentChecker.check("functionName", functionName); // Pass control to callImpl(...) method return callImpl(sessionID, functionName, parameters); } /** * Calls the specified API function with the specified parameters (actual * implementation). The type (see {@link #getType()}) determines what * actual function caller will be used. * * @param sessionID * the session identifier, if any, or <code>null</code> if the function * is session-less. * * @param functionName * the name of the function to be called, guaranteed not to be * <code>null</code>. * * @param parameters * the parameters to be passed to that function, or * <code>null</code>; keys must be {@link String Strings}, values can be * of any class. * * @return * the call result, never <code>null</code>. * * @throws CallIOException * if the API could not be contacted due to an I/O error. * * @throws InvalidCallResultException * if the calling of the function failed or if the result from the * function was invalid. */ abstract CallResult callImpl(String sessionID, String functionName, Map parameters) throws CallIOException, InvalidCallResultException; /** * Attempts to call the specified <code>FunctionCaller</code>. If the call * succeeds, then the {@link CallResult} will be returned. If it fails, * then the {@link Throwable} exception will be returned. * * @param caller * the {@link FunctionCaller} to call, not <code>null</code>. * * @param sessionID * the session identifier, or <code>null</code>. * * @param functionName * the name of the function to call, not <code>null</code>. * * @param parameters * the parameters to be passed to the function, or <code>null</code>; * keys must be {@link String Strings}, values can be of any class. * * @return * a {@link Throwable} if * <code>caller.</code>{@link FunctionCaller#call(String,String,Map)} * throws an exception, otherwise the return value of that call, but * never <code>null</code>. * * @throws Error * if <code>caller.</code>{@link FunctionCaller#call(String,String,Map)} * returned <code>null</code>. */ final Object tryCall(FunctionCaller caller, String sessionID, String functionName, Map parameters) throws Error { // Perform the call CallResult result; try { result = caller.call(sessionID, functionName, parameters); // If there was an exception, return it... } catch (Throwable exception) { return exception; } // otherwise if the result was null, then throw an error... if (result == null) { throw new Error(caller.getClass().getName() + ".call(String,String,Map) returned null."); } // otherwise return the CallResult object return result; } /** * Returns the result of <code>tryCall()</code>. This utility method can be * called from {@link #callImpl(String,String,Map)} after * {@link #tryCall(FunctionCaller,String,String,Map)} has been called as * many times as necessary. * * <p>If the specified object is a <code>CallResult</code> object, then it * will be <em>returned</em>. If it is an exception, then that exception * will be <em>thrown</em>. * * @param result * the result from a call to * {@link #tryCall(FunctionCaller,String,String,Map)}, should not be * <code>null</code>. * * @return * the {@link CallResult}, if <code>result instanceof CallResult</code>. * * @throws IllegalArgumentException * if <code>result == null</code>. * * @throws CallIOException * if <code>result instanceof CallIOException</code>. * * @throws InvalidCallResultException * if <code>result instanceof InvalidCallResultException</code>. */ final CallResult callImplResult(Object result) throws IllegalArgumentException, CallIOException, InvalidCallResultException { // Check preconditions MandatoryArgumentChecker.check("result", result); // Determine behaviour based on result object if (result instanceof CallResult) { return (CallResult) result; } else if (result instanceof CallIOException) { throw (CallIOException) result; } else if (result instanceof InvalidCallResultException) { throw (InvalidCallResultException) result; } else if (result instanceof Error) { throw (Error) result; } else if (result instanceof RuntimeException) { throw (RuntimeException) result; } else { throw new Error("CallTargetGroup.tryCall() returned an instance of class " + result.getClass().getName() + ", which is unsupported."); } } //------------------------------------------------------------------------- // Inner classes //------------------------------------------------------------------------- /** * The type of a <code>CallTargetGroup</code>. The type determines the * algorithm to be used to determine what underlying actual function caller * is used to call the remote API implementation. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>) */ public static final class Type extends Object { //---------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------- /** * Constructs a new <code>Type</code>. * * @param name * the name of this type, not <code>null</code>. * * @throws IllegalArgumentException * if <code>name == null</code>. */ private Type(String name) throws IllegalArgumentException { MandatoryArgumentChecker.check("name", name); _name = name; } //---------------------------------------------------------------------- // Fields //---------------------------------------------------------------------- /** * The name of this type. */ private final String _name; //---------------------------------------------------------------------- // Methods //---------------------------------------------------------------------- /** * Returns the name of this type. The name uniquely identifies this * type. * * @return * the name of this type, not <code>null</code>. * * @since XINS 0.45 */ public String getName() { return _name; } public String toString() { return _name; } } }
true
true
private final void addActualFunctionCallers(List members) throws IllegalArgumentException { int memberCount = members == null ? 0 : members.size(); for (int i = 0; i < memberCount; i++) { FunctionCaller member; // Get the member and make sure it is a FunctionCaller instance try { member = (FunctionCaller) members.get(i); if (member == null) { throw new IllegalArgumentException("members.get(" + i + ") == null"); } } catch (ClassCastException cce) { throw new IllegalArgumentException("members.get(" + i + ") is an instance of " + members.get(i).getClass().getName() + '.'); } // If the member is an actual function caller, store a reference if (member instanceof ActualFunctionCaller) { ActualFunctionCaller afc = (ActualFunctionCaller) member; // Store the ActualFunctionCaller self _actualFunctionCallers.add(afc); // Store the ActualFunctionCaller by URL String url = afc.getURL().toString(); _actualFunctionCallersByURL.put(url, afc); // Store the ActualFunctionCaller by URL checksum long checksum = afc.getCRC32(); Long l = new Long(checksum); ActualFunctionCaller afc0 = (ActualFunctionCaller) _actualFunctionCallersByURLChecksum.get(l); if (afc0 != null) { throw new IllegalArgumentException("List contains two ActualFunctionCaller instances that have the same CRC-32 checksum. URL of first is \"" + afc0.getURL().toString() + "\", URL of second is \"" + afc.getURL().toString() + '.'); } _actualFunctionCallersByURLChecksum.put(l, afc); // Store the ActualFunctionCaller by URL checksum string _actualFunctionCallersByURLChecksumString.put(HexConverter.toHexString(checksum), afc); // If the member is composite, get all its members } else if (member instanceof CompositeFunctionCaller) { CompositeFunctionCaller cfc = (CompositeFunctionCaller) member; addActualFunctionCallers(cfc.getMembers()); } } }
private final void addActualFunctionCallers(List members) throws IllegalArgumentException { int memberCount = members == null ? 0 : members.size(); for (int i = 0; i < memberCount; i++) { FunctionCaller member; // Get the member and make sure it is a FunctionCaller instance try { member = (FunctionCaller) members.get(i); if (member == null) { throw new IllegalArgumentException("members.get(" + i + ") == null"); } } catch (ClassCastException cce) { throw new IllegalArgumentException("members.get(" + i + ") is an instance of " + members.get(i).getClass().getName() + '.'); } // If the member is an actual function caller, store a reference if (member instanceof ActualFunctionCaller) { ActualFunctionCaller afc = (ActualFunctionCaller) member; // Store the ActualFunctionCaller self _actualFunctionCallers.add(afc); // Store the ActualFunctionCaller by URL String url = afc.getURL().toString(); _actualFunctionCallersByURL.put(url, afc); // Store the ActualFunctionCaller by URL checksum long checksum = afc.getCRC32(); Long l = new Long(checksum); ActualFunctionCaller afc0 = (ActualFunctionCaller) _actualFunctionCallersByURLChecksum.get(l); if (afc0 != null) { throw new IllegalArgumentException("List contains two ActualFunctionCaller instances that have the same CRC-32 checksum. URL of first is \"" + afc0.getURL().toString() + "\", URL of second is \"" + afc.getURL().toString() + '.'); } _actualFunctionCallersByURLChecksum.put(l, afc); // Store the ActualFunctionCaller by URL checksum string _actualFunctionCallersByURLChecksumString.put(afc.getCRC32String(), afc); // If the member is composite, get all its members } else if (member instanceof CompositeFunctionCaller) { CompositeFunctionCaller cfc = (CompositeFunctionCaller) member; addActualFunctionCallers(cfc.getMembers()); } } }
diff --git a/src/main/java/org/lastbamboo/common/ice/GeneralIceMediaStreamFactoryImpl.java b/src/main/java/org/lastbamboo/common/ice/GeneralIceMediaStreamFactoryImpl.java index 5cdc557..3d1cd78 100644 --- a/src/main/java/org/lastbamboo/common/ice/GeneralIceMediaStreamFactoryImpl.java +++ b/src/main/java/org/lastbamboo/common/ice/GeneralIceMediaStreamFactoryImpl.java @@ -1,171 +1,171 @@ package org.lastbamboo.common.ice; import java.util.Collection; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoServiceListener; import org.apache.mina.filter.codec.ProtocolCodecFactory; import org.lastbamboo.common.ice.candidate.IceCandidate; import org.lastbamboo.common.ice.candidate.IceCandidateGatherer; import org.lastbamboo.common.ice.candidate.IceCandidateGathererImpl; import org.lastbamboo.common.ice.transport.IceTcpConnector; import org.lastbamboo.common.ice.transport.IceUdpConnector; import org.lastbamboo.common.stun.client.StunClient; import org.lastbamboo.common.stun.stack.StunDemuxableProtocolCodecFactory; import org.lastbamboo.common.stun.stack.StunIoHandler; import org.lastbamboo.common.stun.stack.message.StunMessage; import org.lastbamboo.common.stun.stack.message.StunMessageVisitorFactory; import org.lastbamboo.common.stun.stack.transaction.StunTransactionTracker; import org.lastbamboo.common.stun.stack.transaction.StunTransactionTrackerImpl; import org.lastbamboo.common.tcp.frame.TcpFrameCodecFactory; import org.lastbamboo.common.turn.client.StunTcpFrameTurnClientListener; import org.lastbamboo.common.turn.client.TcpTurnClient; import org.lastbamboo.common.turn.client.TurnClientListener; import org.lastbamboo.common.turn.client.TurnStunDemuxableProtocolCodecFactory; import org.lastbamboo.common.upnp.UpnpManager; import org.lastbamboo.common.util.mina.DemuxableProtocolCodecFactory; import org.lastbamboo.common.util.mina.DemuxingIoHandler; import org.lastbamboo.common.util.mina.DemuxingProtocolCodecFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Factory for creating media streams. This factory offers a more complex * API intended for specialized ICE implementations of the simpler * {@link IceMediaStreamFactory} interface to use behind the scenes. */ public class GeneralIceMediaStreamFactoryImpl implements GeneralIceMediaStreamFactory { private final Logger m_log = LoggerFactory.getLogger(getClass()); public <T> IceMediaStream newIceMediaStream( final IceMediaStreamDesc streamDesc, final IceAgent iceAgent, final DemuxableProtocolCodecFactory protocolCodecFactory, final Class<T> protocolMessageClass, final IoHandler udpProtocolIoHandler, final TurnClientListener delegateTurnClientListener, final UpnpManager upnpManager, final IoServiceListener udpServiceListener) { final DemuxableProtocolCodecFactory stunCodecFactory = new StunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory demuxingCodecFactory = - new DemuxingProtocolCodecFactory(protocolCodecFactory, - stunCodecFactory); + new DemuxingProtocolCodecFactory( + stunCodecFactory, protocolCodecFactory); final StunTransactionTracker<StunMessage> transactionTracker = new StunTransactionTrackerImpl(); final IceStunCheckerFactory checkerFactory = new IceStunCheckerFactoryImpl(transactionTracker); final StunMessageVisitorFactory messageVisitorFactory = new IceStunConnectivityCheckerFactoryImpl<StunMessage>(iceAgent, transactionTracker, checkerFactory); final IoHandler stunIoHandler = new StunIoHandler<StunMessage>(messageVisitorFactory); final IoHandler udpIoHandler = new DemuxingIoHandler<StunMessage, T>( StunMessage.class, stunIoHandler, protocolMessageClass, udpProtocolIoHandler); final StunClient udpStunPeer; if (streamDesc.isUdp()) { udpStunPeer = new IceStunUdpPeer(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling(), transactionTracker); udpStunPeer.addIoServiceListener(udpServiceListener); } else { udpStunPeer = null; } // This class just decodes the TCP frames. final IceStunTcpPeer tcpStunPeer; if (streamDesc.isTcp()) { final TurnClientListener turnClientListener = new StunTcpFrameTurnClientListener(messageVisitorFactory, delegateTurnClientListener); final DemuxableProtocolCodecFactory tcpFramingCodecFactory = new TcpFrameCodecFactory(); final TurnStunDemuxableProtocolCodecFactory mapper = new TurnStunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory codecFactory = new DemuxingProtocolCodecFactory(mapper, tcpFramingCodecFactory); // We should only start a TURN client on the answerer to // save resources. final StunClient tcpTurnClient = new TcpTurnClient(turnClientListener, codecFactory); tcpStunPeer = new IceStunTcpPeer(tcpTurnClient, messageVisitorFactory, iceAgent.isControlling(), upnpManager); } else { tcpStunPeer = null; } final IceCandidateGatherer gatherer = new IceCandidateGathererImpl(tcpStunPeer, udpStunPeer, iceAgent.isControlling(), streamDesc); final IceMediaStreamImpl stream = new IceMediaStreamImpl(iceAgent, streamDesc, gatherer); if (tcpStunPeer != null) { tcpStunPeer.addIoServiceListener(stream); } if (udpStunPeer != null) { udpStunPeer.addIoServiceListener(stream); } m_log.debug("Added media stream as listener...connecting..."); if (tcpStunPeer != null) { tcpStunPeer.connect(); } if (udpStunPeer != null) { udpStunPeer.connect(); } final Collection<IceCandidate> localCandidates = gatherer.gatherCandidates(); final IceUdpConnector udpConnector = new IceUdpConnector(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling()); udpConnector.addIoServiceListener(stream); udpConnector.addIoServiceListener(udpServiceListener); final IceTcpConnector tcpConnector = new IceTcpConnector(messageVisitorFactory, iceAgent.isControlling()); tcpConnector.addIoServiceListener(stream); final IceCandidatePairFactory candidatePairFactory = new IceCandidatePairFactoryImpl( checkerFactory, udpConnector, tcpConnector); final IceCheckList checkList = new IceCheckListImpl(candidatePairFactory, localCandidates); final ExistingSessionIceCandidatePairFactory existingSessionPairFactory = new ExistingSessionIceCandidatePairFactoryImpl(checkerFactory); final IceCheckScheduler scheduler = new IceCheckSchedulerImpl(iceAgent, stream, checkList, existingSessionPairFactory); stream.start(checkList, localCandidates, scheduler); return stream; } }
true
true
public <T> IceMediaStream newIceMediaStream( final IceMediaStreamDesc streamDesc, final IceAgent iceAgent, final DemuxableProtocolCodecFactory protocolCodecFactory, final Class<T> protocolMessageClass, final IoHandler udpProtocolIoHandler, final TurnClientListener delegateTurnClientListener, final UpnpManager upnpManager, final IoServiceListener udpServiceListener) { final DemuxableProtocolCodecFactory stunCodecFactory = new StunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory demuxingCodecFactory = new DemuxingProtocolCodecFactory(protocolCodecFactory, stunCodecFactory); final StunTransactionTracker<StunMessage> transactionTracker = new StunTransactionTrackerImpl(); final IceStunCheckerFactory checkerFactory = new IceStunCheckerFactoryImpl(transactionTracker); final StunMessageVisitorFactory messageVisitorFactory = new IceStunConnectivityCheckerFactoryImpl<StunMessage>(iceAgent, transactionTracker, checkerFactory); final IoHandler stunIoHandler = new StunIoHandler<StunMessage>(messageVisitorFactory); final IoHandler udpIoHandler = new DemuxingIoHandler<StunMessage, T>( StunMessage.class, stunIoHandler, protocolMessageClass, udpProtocolIoHandler); final StunClient udpStunPeer; if (streamDesc.isUdp()) { udpStunPeer = new IceStunUdpPeer(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling(), transactionTracker); udpStunPeer.addIoServiceListener(udpServiceListener); } else { udpStunPeer = null; } // This class just decodes the TCP frames. final IceStunTcpPeer tcpStunPeer; if (streamDesc.isTcp()) { final TurnClientListener turnClientListener = new StunTcpFrameTurnClientListener(messageVisitorFactory, delegateTurnClientListener); final DemuxableProtocolCodecFactory tcpFramingCodecFactory = new TcpFrameCodecFactory(); final TurnStunDemuxableProtocolCodecFactory mapper = new TurnStunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory codecFactory = new DemuxingProtocolCodecFactory(mapper, tcpFramingCodecFactory); // We should only start a TURN client on the answerer to // save resources. final StunClient tcpTurnClient = new TcpTurnClient(turnClientListener, codecFactory); tcpStunPeer = new IceStunTcpPeer(tcpTurnClient, messageVisitorFactory, iceAgent.isControlling(), upnpManager); } else { tcpStunPeer = null; } final IceCandidateGatherer gatherer = new IceCandidateGathererImpl(tcpStunPeer, udpStunPeer, iceAgent.isControlling(), streamDesc); final IceMediaStreamImpl stream = new IceMediaStreamImpl(iceAgent, streamDesc, gatherer); if (tcpStunPeer != null) { tcpStunPeer.addIoServiceListener(stream); } if (udpStunPeer != null) { udpStunPeer.addIoServiceListener(stream); } m_log.debug("Added media stream as listener...connecting..."); if (tcpStunPeer != null) { tcpStunPeer.connect(); } if (udpStunPeer != null) { udpStunPeer.connect(); } final Collection<IceCandidate> localCandidates = gatherer.gatherCandidates(); final IceUdpConnector udpConnector = new IceUdpConnector(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling()); udpConnector.addIoServiceListener(stream); udpConnector.addIoServiceListener(udpServiceListener); final IceTcpConnector tcpConnector = new IceTcpConnector(messageVisitorFactory, iceAgent.isControlling()); tcpConnector.addIoServiceListener(stream); final IceCandidatePairFactory candidatePairFactory = new IceCandidatePairFactoryImpl( checkerFactory, udpConnector, tcpConnector); final IceCheckList checkList = new IceCheckListImpl(candidatePairFactory, localCandidates); final ExistingSessionIceCandidatePairFactory existingSessionPairFactory = new ExistingSessionIceCandidatePairFactoryImpl(checkerFactory); final IceCheckScheduler scheduler = new IceCheckSchedulerImpl(iceAgent, stream, checkList, existingSessionPairFactory); stream.start(checkList, localCandidates, scheduler); return stream; }
public <T> IceMediaStream newIceMediaStream( final IceMediaStreamDesc streamDesc, final IceAgent iceAgent, final DemuxableProtocolCodecFactory protocolCodecFactory, final Class<T> protocolMessageClass, final IoHandler udpProtocolIoHandler, final TurnClientListener delegateTurnClientListener, final UpnpManager upnpManager, final IoServiceListener udpServiceListener) { final DemuxableProtocolCodecFactory stunCodecFactory = new StunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory demuxingCodecFactory = new DemuxingProtocolCodecFactory( stunCodecFactory, protocolCodecFactory); final StunTransactionTracker<StunMessage> transactionTracker = new StunTransactionTrackerImpl(); final IceStunCheckerFactory checkerFactory = new IceStunCheckerFactoryImpl(transactionTracker); final StunMessageVisitorFactory messageVisitorFactory = new IceStunConnectivityCheckerFactoryImpl<StunMessage>(iceAgent, transactionTracker, checkerFactory); final IoHandler stunIoHandler = new StunIoHandler<StunMessage>(messageVisitorFactory); final IoHandler udpIoHandler = new DemuxingIoHandler<StunMessage, T>( StunMessage.class, stunIoHandler, protocolMessageClass, udpProtocolIoHandler); final StunClient udpStunPeer; if (streamDesc.isUdp()) { udpStunPeer = new IceStunUdpPeer(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling(), transactionTracker); udpStunPeer.addIoServiceListener(udpServiceListener); } else { udpStunPeer = null; } // This class just decodes the TCP frames. final IceStunTcpPeer tcpStunPeer; if (streamDesc.isTcp()) { final TurnClientListener turnClientListener = new StunTcpFrameTurnClientListener(messageVisitorFactory, delegateTurnClientListener); final DemuxableProtocolCodecFactory tcpFramingCodecFactory = new TcpFrameCodecFactory(); final TurnStunDemuxableProtocolCodecFactory mapper = new TurnStunDemuxableProtocolCodecFactory(); final ProtocolCodecFactory codecFactory = new DemuxingProtocolCodecFactory(mapper, tcpFramingCodecFactory); // We should only start a TURN client on the answerer to // save resources. final StunClient tcpTurnClient = new TcpTurnClient(turnClientListener, codecFactory); tcpStunPeer = new IceStunTcpPeer(tcpTurnClient, messageVisitorFactory, iceAgent.isControlling(), upnpManager); } else { tcpStunPeer = null; } final IceCandidateGatherer gatherer = new IceCandidateGathererImpl(tcpStunPeer, udpStunPeer, iceAgent.isControlling(), streamDesc); final IceMediaStreamImpl stream = new IceMediaStreamImpl(iceAgent, streamDesc, gatherer); if (tcpStunPeer != null) { tcpStunPeer.addIoServiceListener(stream); } if (udpStunPeer != null) { udpStunPeer.addIoServiceListener(stream); } m_log.debug("Added media stream as listener...connecting..."); if (tcpStunPeer != null) { tcpStunPeer.connect(); } if (udpStunPeer != null) { udpStunPeer.connect(); } final Collection<IceCandidate> localCandidates = gatherer.gatherCandidates(); final IceUdpConnector udpConnector = new IceUdpConnector(demuxingCodecFactory, udpIoHandler, iceAgent.isControlling()); udpConnector.addIoServiceListener(stream); udpConnector.addIoServiceListener(udpServiceListener); final IceTcpConnector tcpConnector = new IceTcpConnector(messageVisitorFactory, iceAgent.isControlling()); tcpConnector.addIoServiceListener(stream); final IceCandidatePairFactory candidatePairFactory = new IceCandidatePairFactoryImpl( checkerFactory, udpConnector, tcpConnector); final IceCheckList checkList = new IceCheckListImpl(candidatePairFactory, localCandidates); final ExistingSessionIceCandidatePairFactory existingSessionPairFactory = new ExistingSessionIceCandidatePairFactoryImpl(checkerFactory); final IceCheckScheduler scheduler = new IceCheckSchedulerImpl(iceAgent, stream, checkList, existingSessionPairFactory); stream.start(checkList, localCandidates, scheduler); return stream; }
diff --git a/esmska/src/esmska/gui/EditContactPanel.java b/esmska/src/esmska/gui/EditContactPanel.java index 3b0f1cb5..378717e6 100644 --- a/esmska/src/esmska/gui/EditContactPanel.java +++ b/esmska/src/esmska/gui/EditContactPanel.java @@ -1,414 +1,414 @@ /* * EditContactPanel.java * * Created on 26. červenec 2007, 11:50 */ package esmska.gui; import esmska.data.Config; import esmska.data.Contact; import esmska.data.CountryPrefix; import esmska.data.Keyring; import esmska.data.Links; import esmska.data.Operator; import esmska.data.event.AbstractDocumentListener; import esmska.utils.L10N; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.text.MessageFormat; import java.util.Collection; import java.util.ResourceBundle; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.SwingConstants; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import org.apache.commons.lang.StringUtils; import org.openide.awt.Mnemonics; /** Add new or edit current contact * * @author ripper */ public class EditContactPanel extends javax.swing.JPanel { private static final ResourceBundle l10n = L10N.l10nBundle; private static final Border fieldBorder = new JTextField().getBorder(); private static final Border lineRedBorder = BorderFactory.createLineBorder(Color.RED); private Config config = Config.getInstance(); private Keyring keyring = Keyring.getInstance(); private boolean multiMode; //edit multiple contacts private boolean userSet; //whether operator was set by user or by program private Action suggestOperatorAction; /** * Creates new form EditContactPanel */ public EditContactPanel() { initComponents(); //if not Substance LaF, add clipboard popup menu to text components if (!config.getLookAndFeel().equals(ThemeManager.LAF.SUBSTANCE)) { ClipboardPopupMenu.register(nameTextField); ClipboardPopupMenu.register(numberTextField); } //set up button for suggesting operator suggestOperatorAction = Actions.getSuggestOperatorAction(operatorComboBox, numberTextField); suggestOperatorButton.setAction(suggestOperatorAction); //listen for changes in number and guess operator numberTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { if (!userSet) { operatorComboBox.selectSuggestedOperator(numberTextField.getText()); userSet = false; } updateCountryInfoLabel(); } }); //update components operatorComboBoxItemStateChanged(null); } /** 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. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { nameTextField = new JTextField(); nameTextField.requestFocusInWindow(); numberTextField = new JTextField() { @Override public String getText() { String text = super.getText(); - if (!text.startsWith("+")) + if (StringUtils.isNotEmpty(text) && !text.startsWith("+")) text = config.getCountryPrefix() + text; return text; } } ; operatorComboBox = new OperatorComboBox(); nameLabel = new JLabel(); numberLabel = new JLabel(); gatewayLabel = new JLabel(); suggestOperatorButton = new JButton(); jPanel1 = new JPanel(); countryInfoLabel = new InfoLabel(); credentialsInfoLabel = new InfoLabel(); nameTextField.setToolTipText(l10n.getString("EditContactPanel.nameTextField.toolTipText")); // NOI18N nameTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { nameTextFieldFocusLost(evt); } }); numberTextField.setColumns(13); numberTextField.setToolTipText(l10n.getString("EditContactPanel.numberTextField.toolTipText")); // NOI18N numberTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { numberTextFieldFocusLost(evt); } }); operatorComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { operatorComboBoxItemStateChanged(evt); } }); nameLabel.setLabelFor(nameTextField); Mnemonics.setLocalizedText(nameLabel, l10n.getString("EditContactPanel.nameLabel.text")); // NOI18N nameLabel.setToolTipText(nameTextField.getToolTipText()); numberLabel.setLabelFor(numberTextField); Mnemonics.setLocalizedText(numberLabel, l10n.getString("EditContactPanel.numberLabel.text")); // NOI18N numberLabel.setToolTipText(numberTextField.getToolTipText()); gatewayLabel.setLabelFor(operatorComboBox); Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("EditContactPanel.gatewayLabel.text")); // NOI18N gatewayLabel.setToolTipText(operatorComboBox.getToolTipText()); suggestOperatorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { suggestOperatorButtonActionPerformed(evt); } }); Mnemonics.setLocalizedText(countryInfoLabel, l10n.getString("EditContactPanel.countryInfoLabel.text")); // NOI18N countryInfoLabel.setVisible(false); Mnemonics.setLocalizedText(credentialsInfoLabel,l10n.getString( "EditContactPanel.credentialsInfoLabel.text")); credentialsInfoLabel.setText(MessageFormat.format( l10n.getString("EditContactPanel.credentialsInfoLabel.text"), Links.CONFIG_CREDENTIALS)); credentialsInfoLabel.setVisible(false); GroupLayout jPanel1Layout = new GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE) .addComponent(countryInfoLabel) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(credentialsInfoLabel) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(countryInfoLabel)) ); GroupLayout layout = new GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(numberLabel) .addComponent(nameLabel) .addComponent(gatewayLabel)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.LEADING) .addGroup(Alignment.TRAILING, layout.createSequentialGroup() .addComponent(operatorComboBox, GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(suggestOperatorButton)) .addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE) .addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)))) .addContainerGap()) ); layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, nameLabel, numberLabel}); layout.setVerticalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(nameLabel) .addComponent(nameTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(numberLabel) .addComponent(numberTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(gatewayLabel) .addComponent(operatorComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addComponent(suggestOperatorButton)) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(74, Short.MAX_VALUE)) ); layout.linkSize(SwingConstants.VERTICAL, new Component[] {nameTextField, numberTextField}); }// </editor-fold>//GEN-END:initComponents /** Check if the form is valid */ public boolean validateForm() { boolean valid = true; boolean focusTransfered = false; JComponent[] comps; if (multiMode) { comps = new JComponent[] {}; } else { comps = new JComponent[] {nameTextField, numberTextField}; } for (JComponent c : comps) { valid = checkValid(c) && valid; if (!valid && !focusTransfered) { c.requestFocusInWindow(); focusTransfered = true; } } return valid; } /** checks if component's content is valid */ private boolean checkValid(JComponent c) { boolean valid = true; if (c == nameTextField) { valid = StringUtils.isNotEmpty(nameTextField.getText()); updateBorder(c, valid); } else if (c == numberTextField) { valid = Contact.isValidNumber(numberTextField.getText()); updateBorder(c, valid); } return valid; } /** sets highlighted border on non-valid components and regular border on valid ones */ private void updateBorder(JComponent c, boolean valid) { if (valid) { c.setBorder(fieldBorder); } else { c.setBorder(lineRedBorder); } } /** Enable or disable multi-editing mode */ private void setMultiMode(boolean multiMode) { this.multiMode = multiMode; nameTextField.setEnabled(!multiMode); numberTextField.setEnabled(!multiMode); suggestOperatorAction.setEnabled(!multiMode); } /** Show warning if user selected gateway which does not send * messages to country from which is the number */ private void updateCountryInfoLabel() { countryInfoLabel.setVisible(false); //ensure that fields are sufficiently filled in Operator operator = operatorComboBox.getSelectedOperator(); String number = numberTextField.getText(); if (operator == null || !Contact.isValidNumber(number)) { return; } String prefix = CountryPrefix.extractCountryPrefix(number); String numberCountryCode = CountryPrefix.getCountryCode(prefix); if (StringUtils.isEmpty(numberCountryCode)) { return; } //skip on INT gateways String gwCountryCode = CountryPrefix.extractCountryCode(operator.getName()); if (gwCountryCode == null || CountryPrefix.INTERNATIONAL_CODE.equals(gwCountryCode)) { return; } if (!numberCountryCode.equals(gwCountryCode)) { String text = MessageFormat.format(l10n.getString("EditContactPanel.countryInfoLabel.text"), gwCountryCode, numberCountryCode); countryInfoLabel.setText(text); countryInfoLabel.setVisible(true); } } private void nameTextFieldFocusLost(FocusEvent evt) {//GEN-FIRST:event_nameTextFieldFocusLost checkValid(nameTextField); }//GEN-LAST:event_nameTextFieldFocusLost private void numberTextFieldFocusLost(FocusEvent evt) {//GEN-FIRST:event_numberTextFieldFocusLost checkValid(numberTextField); }//GEN-LAST:event_numberTextFieldFocusLost private void suggestOperatorButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_suggestOperatorButtonActionPerformed userSet = false; }//GEN-LAST:event_suggestOperatorButtonActionPerformed private void operatorComboBoxItemStateChanged(ItemEvent evt) {//GEN-FIRST:event_operatorComboBoxItemStateChanged userSet = true; //show warning if user selected gateway requiring registration //and no credentials are filled in Operator operator = operatorComboBox.getSelectedOperator(); if (operator != null && operator.isLoginRequired() && keyring.getKey(operator.getName()) == null) { credentialsInfoLabel.setVisible(true); } else { credentialsInfoLabel.setVisible(false); } //also update countryInfoLabel updateCountryInfoLabel(); }//GEN-LAST:event_operatorComboBoxItemStateChanged /** Set contact to be edited or use null for new one */ public void setContact(Contact contact) { setMultiMode(false); if (contact == null) { nameTextField.setText(null); numberTextField.setText(config.getCountryPrefix()); operatorComboBox.selectSuggestedOperator(numberTextField.getText()); } else { nameTextField.setText(contact.getName()); numberTextField.setText(contact.getNumber()); operatorComboBox.setSelectedOperator(contact.getOperator()); } userSet = false; } /** Set contacts for collective editing. May not be null. */ public void setContacts(Collection<Contact> contacts) { if (contacts.size() <= 1) { setContact(contacts.size() <= 0 ? null : contacts.iterator().next()); return; } setMultiMode(true); operatorComboBox.setSelectedOperator(contacts.iterator().next().getOperator()); } /** Get currently edited contact */ public Contact getContact() { String name = nameTextField.getText(); String number = numberTextField.getText(); String operator = operatorComboBox.getSelectedOperatorName(); if (!multiMode && (StringUtils.isEmpty(name) || StringUtils.isEmpty(number) || StringUtils.isEmpty(operator))) { return null; } else { return new Contact(name, number, operator); } } /** Improve focus etc. before displaying panel */ public void prepareForShow() { //no operator, try to suggest one if (operatorComboBox.getSelectedOperator() == null) { suggestOperatorAction.actionPerformed(null); } //give focus if (multiMode) { operatorComboBox.requestFocusInWindow(); } else { nameTextField.requestFocusInWindow(); nameTextField.selectAll(); } } // Variables declaration - do not modify//GEN-BEGIN:variables private InfoLabel countryInfoLabel; private InfoLabel credentialsInfoLabel; private JLabel gatewayLabel; private JPanel jPanel1; private JLabel nameLabel; private JTextField nameTextField; private JLabel numberLabel; private JTextField numberTextField; private OperatorComboBox operatorComboBox; private JButton suggestOperatorButton; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { nameTextField = new JTextField(); nameTextField.requestFocusInWindow(); numberTextField = new JTextField() { @Override public String getText() { String text = super.getText(); if (!text.startsWith("+")) text = config.getCountryPrefix() + text; return text; } } ; operatorComboBox = new OperatorComboBox(); nameLabel = new JLabel(); numberLabel = new JLabel(); gatewayLabel = new JLabel(); suggestOperatorButton = new JButton(); jPanel1 = new JPanel(); countryInfoLabel = new InfoLabel(); credentialsInfoLabel = new InfoLabel(); nameTextField.setToolTipText(l10n.getString("EditContactPanel.nameTextField.toolTipText")); // NOI18N nameTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { nameTextFieldFocusLost(evt); } }); numberTextField.setColumns(13); numberTextField.setToolTipText(l10n.getString("EditContactPanel.numberTextField.toolTipText")); // NOI18N numberTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { numberTextFieldFocusLost(evt); } }); operatorComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { operatorComboBoxItemStateChanged(evt); } }); nameLabel.setLabelFor(nameTextField); Mnemonics.setLocalizedText(nameLabel, l10n.getString("EditContactPanel.nameLabel.text")); // NOI18N nameLabel.setToolTipText(nameTextField.getToolTipText()); numberLabel.setLabelFor(numberTextField); Mnemonics.setLocalizedText(numberLabel, l10n.getString("EditContactPanel.numberLabel.text")); // NOI18N numberLabel.setToolTipText(numberTextField.getToolTipText()); gatewayLabel.setLabelFor(operatorComboBox); Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("EditContactPanel.gatewayLabel.text")); // NOI18N gatewayLabel.setToolTipText(operatorComboBox.getToolTipText()); suggestOperatorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { suggestOperatorButtonActionPerformed(evt); } }); Mnemonics.setLocalizedText(countryInfoLabel, l10n.getString("EditContactPanel.countryInfoLabel.text")); // NOI18N countryInfoLabel.setVisible(false); Mnemonics.setLocalizedText(credentialsInfoLabel,l10n.getString( "EditContactPanel.credentialsInfoLabel.text")); credentialsInfoLabel.setText(MessageFormat.format( l10n.getString("EditContactPanel.credentialsInfoLabel.text"), Links.CONFIG_CREDENTIALS)); credentialsInfoLabel.setVisible(false); GroupLayout jPanel1Layout = new GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE) .addComponent(countryInfoLabel) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(credentialsInfoLabel) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(countryInfoLabel)) ); GroupLayout layout = new GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(numberLabel) .addComponent(nameLabel) .addComponent(gatewayLabel)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.LEADING) .addGroup(Alignment.TRAILING, layout.createSequentialGroup() .addComponent(operatorComboBox, GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(suggestOperatorButton)) .addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE) .addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)))) .addContainerGap()) ); layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, nameLabel, numberLabel}); layout.setVerticalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(nameLabel) .addComponent(nameTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(numberLabel) .addComponent(numberTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(gatewayLabel) .addComponent(operatorComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addComponent(suggestOperatorButton)) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(74, Short.MAX_VALUE)) ); layout.linkSize(SwingConstants.VERTICAL, new Component[] {nameTextField, numberTextField}); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { nameTextField = new JTextField(); nameTextField.requestFocusInWindow(); numberTextField = new JTextField() { @Override public String getText() { String text = super.getText(); if (StringUtils.isNotEmpty(text) && !text.startsWith("+")) text = config.getCountryPrefix() + text; return text; } } ; operatorComboBox = new OperatorComboBox(); nameLabel = new JLabel(); numberLabel = new JLabel(); gatewayLabel = new JLabel(); suggestOperatorButton = new JButton(); jPanel1 = new JPanel(); countryInfoLabel = new InfoLabel(); credentialsInfoLabel = new InfoLabel(); nameTextField.setToolTipText(l10n.getString("EditContactPanel.nameTextField.toolTipText")); // NOI18N nameTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { nameTextFieldFocusLost(evt); } }); numberTextField.setColumns(13); numberTextField.setToolTipText(l10n.getString("EditContactPanel.numberTextField.toolTipText")); // NOI18N numberTextField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent evt) { numberTextFieldFocusLost(evt); } }); operatorComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { operatorComboBoxItemStateChanged(evt); } }); nameLabel.setLabelFor(nameTextField); Mnemonics.setLocalizedText(nameLabel, l10n.getString("EditContactPanel.nameLabel.text")); // NOI18N nameLabel.setToolTipText(nameTextField.getToolTipText()); numberLabel.setLabelFor(numberTextField); Mnemonics.setLocalizedText(numberLabel, l10n.getString("EditContactPanel.numberLabel.text")); // NOI18N numberLabel.setToolTipText(numberTextField.getToolTipText()); gatewayLabel.setLabelFor(operatorComboBox); Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("EditContactPanel.gatewayLabel.text")); // NOI18N gatewayLabel.setToolTipText(operatorComboBox.getToolTipText()); suggestOperatorButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { suggestOperatorButtonActionPerformed(evt); } }); Mnemonics.setLocalizedText(countryInfoLabel, l10n.getString("EditContactPanel.countryInfoLabel.text")); // NOI18N countryInfoLabel.setVisible(false); Mnemonics.setLocalizedText(credentialsInfoLabel,l10n.getString( "EditContactPanel.credentialsInfoLabel.text")); credentialsInfoLabel.setText(MessageFormat.format( l10n.getString("EditContactPanel.credentialsInfoLabel.text"), Links.CONFIG_CREDENTIALS)); credentialsInfoLabel.setVisible(false); GroupLayout jPanel1Layout = new GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE) .addComponent(countryInfoLabel) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(credentialsInfoLabel) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(countryInfoLabel)) ); GroupLayout layout = new GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.LEADING) .addComponent(numberLabel) .addComponent(nameLabel) .addComponent(gatewayLabel)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.LEADING) .addGroup(Alignment.TRAILING, layout.createSequentialGroup() .addComponent(operatorComboBox, GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(suggestOperatorButton)) .addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE) .addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)))) .addContainerGap()) ); layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, nameLabel, numberLabel}); layout.setVerticalGroup( layout.createParallelGroup(Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(nameLabel) .addComponent(nameTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(numberLabel) .addComponent(numberTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(Alignment.TRAILING) .addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(gatewayLabel) .addComponent(operatorComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addComponent(suggestOperatorButton)) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addContainerGap(74, Short.MAX_VALUE)) ); layout.linkSize(SwingConstants.VERTICAL, new Component[] {nameTextField, numberTextField}); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/main/java/com/intelix/digihdmi/app/actions/PresetActions.java b/src/main/java/com/intelix/digihdmi/app/actions/PresetActions.java index 826a0fb..63604d9 100644 --- a/src/main/java/com/intelix/digihdmi/app/actions/PresetActions.java +++ b/src/main/java/com/intelix/digihdmi/app/actions/PresetActions.java @@ -1,79 +1,79 @@ package com.intelix.digihdmi.app.actions; import com.intelix.digihdmi.app.DigiHdmiApp; import com.intelix.digihdmi.app.tasks.ApplyPresetTask; import com.intelix.digihdmi.app.tasks.LoadPresetsListTask; import com.intelix.digihdmi.app.tasks.SavePresetTask; import com.intelix.digihdmi.app.tasks.SavePresetsListTask; import com.intelix.digihdmi.app.views.dialogs.NameChangeDlg; import java.awt.event.ActionEvent; import javax.swing.AbstractButton; import javax.swing.JOptionPane; import javax.swing.JTextField; import org.jdesktop.application.Action; import org.jdesktop.application.Application; import org.jdesktop.application.Task; public class PresetActions { DigiHdmiApp appInstance = null; public PresetActions() { appInstance = (DigiHdmiApp) Application.getInstance(); } @Action (block=Task.BlockingScope.WINDOW) public Task showPresetListForLoad() { Task t = new LoadPresetsListTask(Application.getInstance()); t.setInputBlocker(appInstance.new BusyInputBlocker(t)); return t; } @Action public Task showPresetListForSave() { Task t = new SavePresetsListTask(Application.getInstance()); t.setInputBlocker(appInstance.new BusyInputBlocker(t)); return t; } @Action (block=Task.BlockingScope.WINDOW) public Task applyPresetAndShowMatrixView(ActionEvent ev) { AbstractButton b = (AbstractButton) ev.getSource(); int index = b.getName().lastIndexOf('_') + 1; int presetNumber = Integer.parseInt(b.getName().substring(index)); // show the matrix view appInstance.showMatrixView(); // populate the matrix view with results from preset application Task t = new ApplyPresetTask(appInstance, presetNumber); t.setInputBlocker(appInstance.new BusyInputBlocker(t)); return t; } @Action (block=Task.BlockingScope.WINDOW) public Task savePresetAndShowMatrixView(ActionEvent ev) { AbstractButton b = (AbstractButton) ev.getSource(); int index = b.getName().lastIndexOf('_') + 1; int presetNumber = Integer.parseInt(b.getName().substring(index)); // Get the new name of the preset NameChangeDlg dlg = new NameChangeDlg(appInstance.getMainFrame(), - "",appInstance.getDevice().getIONameLength()); + "Enter new name for preset "+(presetNumber+1),appInstance.getDevice().getPresetNameLength()); dlg.setVisible(true); appInstance.showMatrixView(); String newName = dlg.getTheName(); if (!dlg.isCancelled() && newName.length() > 0) { // populate the matrix view with results from preset application Task t = new SavePresetTask(appInstance, presetNumber, newName); t.setInputBlocker(appInstance.new BusyInputBlocker(t)); return t; } else { // show the matrix view return null; } } }
true
true
public Task savePresetAndShowMatrixView(ActionEvent ev) { AbstractButton b = (AbstractButton) ev.getSource(); int index = b.getName().lastIndexOf('_') + 1; int presetNumber = Integer.parseInt(b.getName().substring(index)); // Get the new name of the preset NameChangeDlg dlg = new NameChangeDlg(appInstance.getMainFrame(), "",appInstance.getDevice().getIONameLength()); dlg.setVisible(true); appInstance.showMatrixView(); String newName = dlg.getTheName(); if (!dlg.isCancelled() && newName.length() > 0) { // populate the matrix view with results from preset application Task t = new SavePresetTask(appInstance, presetNumber, newName); t.setInputBlocker(appInstance.new BusyInputBlocker(t)); return t; } else { // show the matrix view return null; } }
public Task savePresetAndShowMatrixView(ActionEvent ev) { AbstractButton b = (AbstractButton) ev.getSource(); int index = b.getName().lastIndexOf('_') + 1; int presetNumber = Integer.parseInt(b.getName().substring(index)); // Get the new name of the preset NameChangeDlg dlg = new NameChangeDlg(appInstance.getMainFrame(), "Enter new name for preset "+(presetNumber+1),appInstance.getDevice().getPresetNameLength()); dlg.setVisible(true); appInstance.showMatrixView(); String newName = dlg.getTheName(); if (!dlg.isCancelled() && newName.length() > 0) { // populate the matrix view with results from preset application Task t = new SavePresetTask(appInstance, presetNumber, newName); t.setInputBlocker(appInstance.new BusyInputBlocker(t)); return t; } else { // show the matrix view return null; } }
diff --git a/src/main/org/jboss/messaging/core/plugin/ClusteredPostOfficeService.java b/src/main/org/jboss/messaging/core/plugin/ClusteredPostOfficeService.java index 3e192fd85..01769857c 100644 --- a/src/main/org/jboss/messaging/core/plugin/ClusteredPostOfficeService.java +++ b/src/main/org/jboss/messaging/core/plugin/ClusteredPostOfficeService.java @@ -1,420 +1,420 @@ /* * JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt 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.messaging.core.plugin; import javax.management.ObjectName; import javax.management.NotificationListener; import javax.management.NotificationFilter; import javax.management.ListenerNotFoundException; import javax.management.MBeanNotificationInfo; import javax.transaction.TransactionManager; import org.jboss.jms.selector.SelectorFactory; import org.jboss.jms.server.JMSConditionFactory; import org.jboss.jms.server.QueuedExecutorPool; import org.jboss.jms.server.ServerPeer; import org.jboss.jms.util.ExceptionUtil; import org.jboss.messaging.core.FilterFactory; import org.jboss.messaging.core.plugin.contract.ConditionFactory; import org.jboss.messaging.core.plugin.contract.FailoverMapper; import org.jboss.messaging.core.plugin.contract.MessageStore; import org.jboss.messaging.core.plugin.contract.MessagingComponent; import org.jboss.messaging.core.plugin.contract.PersistenceManager; import org.jboss.messaging.core.plugin.postoffice.cluster.ClusterRouterFactory; import org.jboss.messaging.core.plugin.postoffice.cluster.DefaultClusteredPostOffice; import org.jboss.messaging.core.plugin.postoffice.cluster.DefaultFailoverMapper; import org.jboss.messaging.core.plugin.postoffice.cluster.MessagePullPolicy; import org.jboss.messaging.core.plugin.postoffice.cluster.Peer; import org.jboss.messaging.core.plugin.postoffice.cluster.jchannelfactory.JChannelFactory; import org.jboss.messaging.core.plugin.postoffice.cluster.jchannelfactory.MultiplexerJChannelFactory; import org.jboss.messaging.core.plugin.postoffice.cluster.jchannelfactory.XMLJChannelFactory; import org.jboss.messaging.core.tx.TransactionRepository; import org.w3c.dom.Element; import java.util.Set; import java.util.Collections; /** * A ClusteredPostOfficeService * * MBean wrapper for a clustered post office * * @author <a href="mailto:[email protected]">Tim Fox</a> * @author <a href="mailto:[email protected]">Ovidiu Feodorov</a> * @version <tt>$Revision$</tt> * * $Id$ * */ public class ClusteredPostOfficeService extends JDBCServiceSupport implements Peer { // Constants ----------------------------------------------------- // Static -------------------------------------------------------- // Attributes ---------------------------------------------------- private boolean started; // This group of properties is used on JGroups Channel configuration private Element syncChannelConfig; private Element asyncChannelConfig; private ObjectName channelFactoryName; private String syncChannelName; private String asyncChannelName; private String channelPartitionName; private ObjectName serverPeerObjectName; private String officeName; private long stateTimeout = 5000; private long castTimeout = 5000; private String groupName; private long statsSendPeriod = 1000; private String clusterRouterFactory; private String messagePullPolicy; private DefaultClusteredPostOffice postOffice; // Constructors -------------------------------------------------- // ServerPlugin implementation ----------------------------------- public MessagingComponent getInstance() { return postOffice; } // Peer implementation ------------------------------------------- public Set getNodeIDView() { if (postOffice == null) { return Collections.EMPTY_SET; } return postOffice.getNodeIDView(); } // NotificationBroadcaster implementation ------------------------ public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws IllegalArgumentException { postOffice.addNotificationListener(listener, filter, object); } public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { postOffice.removeNotificationListener(listener); } public MBeanNotificationInfo[] getNotificationInfo() { return postOffice.getNotificationInfo(); } // MBean attributes ---------------------------------------------- public synchronized ObjectName getServerPeer() { return serverPeerObjectName; } public synchronized void setServerPeer(ObjectName on) { if (started) { log.warn("Cannot set attribute when service is started"); return; } this.serverPeerObjectName = on; } public synchronized String getPostOfficeName() { return officeName; } public synchronized void setPostOfficeName(String name) { if (started) { log.warn("Cannot set attribute when service is started"); return; } this.officeName = name; } public ObjectName getChannelFactoryName() { return channelFactoryName; } public void setChannelFactoryName(ObjectName channelFactoryName) { this.channelFactoryName = channelFactoryName; } public String getSyncChannelName() { return syncChannelName; } public void setSyncChannelName(String syncChannelName) { this.syncChannelName = syncChannelName; } public String getAsyncChannelName() { return asyncChannelName; } public void setAsyncChannelName(String asyncChannelName) { this.asyncChannelName = asyncChannelName; } public String getChannelPartitionName() { return channelPartitionName; } public void setChannelPartitionName(String channelPartitionName) { this.channelPartitionName = channelPartitionName; } public void setSyncChannelConfig(Element config) throws Exception { syncChannelConfig = config; } public Element getSyncChannelConfig() { return syncChannelConfig; } public void setAsyncChannelConfig(Element config) throws Exception { asyncChannelConfig = config; } public Element getAsyncChannelConfig() { return asyncChannelConfig; } public void setStateTimeout(long timeout) { this.stateTimeout = timeout; } public long getStateTimeout() { return stateTimeout; } public void setCastTimeout(long timeout) { this.castTimeout = timeout; } public long getCastTimeout() { return castTimeout; } public void setGroupName(String groupName) { this.groupName = groupName; } public String getGroupName() { return groupName; } public void setStatsSendPeriod(long period) { this.statsSendPeriod = period; } public long getStatsSendPeriod() { return statsSendPeriod; } public String getClusterRouterFactory() { return clusterRouterFactory; } public String getMessagePullPolicy() { return messagePullPolicy; } public void setClusterRouterFactory(String clusterRouterFactory) { this.clusterRouterFactory = clusterRouterFactory; } public void setMessagePullPolicy(String messagePullPolicy) { this.messagePullPolicy = messagePullPolicy; } public String listBindings() { return postOffice.printBindingInformation(); } // Public -------------------------------------------------------- // Package protected --------------------------------------------- // ServiceMBeanSupport overrides --------------------------------- protected synchronized void startService() throws Exception { if (started) { throw new IllegalStateException("Service is already started"); } super.startService(); try { TransactionManager tm = getTransactionManagerReference(); ServerPeer serverPeer = (ServerPeer)server.getAttribute(serverPeerObjectName, "Instance"); MessageStore ms = serverPeer.getMessageStore(); TransactionRepository tr = serverPeer.getTxRepository(); PersistenceManager pm = serverPeer.getPersistenceManagerInstance(); QueuedExecutorPool pool = serverPeer.getQueuedExecutorPool(); int nodeId = serverPeer.getServerPeerID(); Class clazz = Class.forName(messagePullPolicy); MessagePullPolicy pullPolicy = (MessagePullPolicy)clazz.newInstance(); clazz = Class.forName(clusterRouterFactory); ClusterRouterFactory rf = (ClusterRouterFactory)clazz.newInstance(); ConditionFactory cf = new JMSConditionFactory(); FilterFactory ff = new SelectorFactory(); FailoverMapper mapper = new DefaultFailoverMapper(); JChannelFactory jChannelFactory = null; if (channelFactoryName != null) { Object info = null; try { info = server.getMBeanInfo(channelFactoryName); } catch (Exception e) { - log.error("Error", e); + // log.error("Error", e); // noop... means we couldn't find the channel hence we should use regular XMLChannelFactories } if (info!=null) { log.debug(this + " uses MultiplexerJChannelFactory"); jChannelFactory = new MultiplexerJChannelFactory(server, channelFactoryName, channelPartitionName, syncChannelName, asyncChannelName); } else { log.debug(this + " uses XMLJChannelFactory"); jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig); } } else { log.debug(this + " uses XMLJChannelFactory"); jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig); } postOffice = new DefaultClusteredPostOffice(ds, tm, sqlProperties, createTablesOnStartup, nodeId, officeName, ms, pm, tr, ff, cf, pool, groupName, jChannelFactory, stateTimeout, castTimeout, pullPolicy, rf, mapper, statsSendPeriod); postOffice.start(); started = true; } catch (Throwable t) { throw ExceptionUtil.handleJMXInvocation(t, this + " startService"); } } protected void stopService() throws Exception { if (!started) { throw new IllegalStateException("Service is not started"); } super.stopService(); try { postOffice.stop(); postOffice = null; started = false; log.debug(this + " stopped"); } catch (Throwable t) { throw ExceptionUtil.handleJMXInvocation(t, this + " startService"); } } // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- }
true
true
protected synchronized void startService() throws Exception { if (started) { throw new IllegalStateException("Service is already started"); } super.startService(); try { TransactionManager tm = getTransactionManagerReference(); ServerPeer serverPeer = (ServerPeer)server.getAttribute(serverPeerObjectName, "Instance"); MessageStore ms = serverPeer.getMessageStore(); TransactionRepository tr = serverPeer.getTxRepository(); PersistenceManager pm = serverPeer.getPersistenceManagerInstance(); QueuedExecutorPool pool = serverPeer.getQueuedExecutorPool(); int nodeId = serverPeer.getServerPeerID(); Class clazz = Class.forName(messagePullPolicy); MessagePullPolicy pullPolicy = (MessagePullPolicy)clazz.newInstance(); clazz = Class.forName(clusterRouterFactory); ClusterRouterFactory rf = (ClusterRouterFactory)clazz.newInstance(); ConditionFactory cf = new JMSConditionFactory(); FilterFactory ff = new SelectorFactory(); FailoverMapper mapper = new DefaultFailoverMapper(); JChannelFactory jChannelFactory = null; if (channelFactoryName != null) { Object info = null; try { info = server.getMBeanInfo(channelFactoryName); } catch (Exception e) { log.error("Error", e); // noop... means we couldn't find the channel hence we should use regular XMLChannelFactories } if (info!=null) { log.debug(this + " uses MultiplexerJChannelFactory"); jChannelFactory = new MultiplexerJChannelFactory(server, channelFactoryName, channelPartitionName, syncChannelName, asyncChannelName); } else { log.debug(this + " uses XMLJChannelFactory"); jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig); } } else { log.debug(this + " uses XMLJChannelFactory"); jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig); } postOffice = new DefaultClusteredPostOffice(ds, tm, sqlProperties, createTablesOnStartup, nodeId, officeName, ms, pm, tr, ff, cf, pool, groupName, jChannelFactory, stateTimeout, castTimeout, pullPolicy, rf, mapper, statsSendPeriod); postOffice.start(); started = true; } catch (Throwable t) { throw ExceptionUtil.handleJMXInvocation(t, this + " startService"); } }
protected synchronized void startService() throws Exception { if (started) { throw new IllegalStateException("Service is already started"); } super.startService(); try { TransactionManager tm = getTransactionManagerReference(); ServerPeer serverPeer = (ServerPeer)server.getAttribute(serverPeerObjectName, "Instance"); MessageStore ms = serverPeer.getMessageStore(); TransactionRepository tr = serverPeer.getTxRepository(); PersistenceManager pm = serverPeer.getPersistenceManagerInstance(); QueuedExecutorPool pool = serverPeer.getQueuedExecutorPool(); int nodeId = serverPeer.getServerPeerID(); Class clazz = Class.forName(messagePullPolicy); MessagePullPolicy pullPolicy = (MessagePullPolicy)clazz.newInstance(); clazz = Class.forName(clusterRouterFactory); ClusterRouterFactory rf = (ClusterRouterFactory)clazz.newInstance(); ConditionFactory cf = new JMSConditionFactory(); FilterFactory ff = new SelectorFactory(); FailoverMapper mapper = new DefaultFailoverMapper(); JChannelFactory jChannelFactory = null; if (channelFactoryName != null) { Object info = null; try { info = server.getMBeanInfo(channelFactoryName); } catch (Exception e) { // log.error("Error", e); // noop... means we couldn't find the channel hence we should use regular XMLChannelFactories } if (info!=null) { log.debug(this + " uses MultiplexerJChannelFactory"); jChannelFactory = new MultiplexerJChannelFactory(server, channelFactoryName, channelPartitionName, syncChannelName, asyncChannelName); } else { log.debug(this + " uses XMLJChannelFactory"); jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig); } } else { log.debug(this + " uses XMLJChannelFactory"); jChannelFactory = new XMLJChannelFactory(syncChannelConfig, asyncChannelConfig); } postOffice = new DefaultClusteredPostOffice(ds, tm, sqlProperties, createTablesOnStartup, nodeId, officeName, ms, pm, tr, ff, cf, pool, groupName, jChannelFactory, stateTimeout, castTimeout, pullPolicy, rf, mapper, statsSendPeriod); postOffice.start(); started = true; } catch (Throwable t) { throw ExceptionUtil.handleJMXInvocation(t, this + " startService"); } }
diff --git a/src/com/uncc/gameday/activities/Search.java b/src/com/uncc/gameday/activities/Search.java index 3c825ff..f93a6ac 100644 --- a/src/com/uncc/gameday/activities/Search.java +++ b/src/com/uncc/gameday/activities/Search.java @@ -1,69 +1,69 @@ package com.uncc.gameday.activities; import java.util.Collections; import java.util.Comparator; import java.util.List; import retrofit.RetrofitError; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.uncc.gameday.R; import com.uncc.gameday.registration.Attendee; import com.uncc.gameday.registration.RegistrationClient; public class Search extends MenuActivity { List<Attendee> rsvpList; boolean listFetched = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_rsvp); new fetchAttendeesThread(this).start(); } private class fetchAttendeesThread extends Thread { Context c; public fetchAttendeesThread(Context c) { this.c = c; } public void run() { try { RegistrationClient client = new RegistrationClient(this.c); rsvpList = client.listAttendees(); listFetched = true; } catch (RetrofitError e) { Toast.makeText(c, R.string.internet_down_error, Toast.LENGTH_SHORT).show(); Log.e("Search", e.getLocalizedMessage()); } //sorts RSVPList alphabetically by last name Collections.sort(rsvpList, new Comparator<Attendee>() { @Override public int compare(Attendee a1, Attendee a2) { String compareName = a1.getLastName(); String thisName = a2.getLastName(); return compareName.compareTo(thisName); } }); //function to display RSVPList onto listView runOnUiThread(new Runnable() { @Override public void run() { - ListView listView = (ListView)findViewById(R.id.RSVPListView); + ListView listView = (ListView)findViewById(R.id.textView1); ArrayAdapter<Attendee> adapter = new ArrayAdapter<Attendee>(c,android.R.layout.simple_list_item_1, rsvpList); listView.setAdapter(adapter); } }); } } }
true
true
public void run() { try { RegistrationClient client = new RegistrationClient(this.c); rsvpList = client.listAttendees(); listFetched = true; } catch (RetrofitError e) { Toast.makeText(c, R.string.internet_down_error, Toast.LENGTH_SHORT).show(); Log.e("Search", e.getLocalizedMessage()); } //sorts RSVPList alphabetically by last name Collections.sort(rsvpList, new Comparator<Attendee>() { @Override public int compare(Attendee a1, Attendee a2) { String compareName = a1.getLastName(); String thisName = a2.getLastName(); return compareName.compareTo(thisName); } }); //function to display RSVPList onto listView runOnUiThread(new Runnable() { @Override public void run() { ListView listView = (ListView)findViewById(R.id.RSVPListView); ArrayAdapter<Attendee> adapter = new ArrayAdapter<Attendee>(c,android.R.layout.simple_list_item_1, rsvpList); listView.setAdapter(adapter); } }); }
public void run() { try { RegistrationClient client = new RegistrationClient(this.c); rsvpList = client.listAttendees(); listFetched = true; } catch (RetrofitError e) { Toast.makeText(c, R.string.internet_down_error, Toast.LENGTH_SHORT).show(); Log.e("Search", e.getLocalizedMessage()); } //sorts RSVPList alphabetically by last name Collections.sort(rsvpList, new Comparator<Attendee>() { @Override public int compare(Attendee a1, Attendee a2) { String compareName = a1.getLastName(); String thisName = a2.getLastName(); return compareName.compareTo(thisName); } }); //function to display RSVPList onto listView runOnUiThread(new Runnable() { @Override public void run() { ListView listView = (ListView)findViewById(R.id.textView1); ArrayAdapter<Attendee> adapter = new ArrayAdapter<Attendee>(c,android.R.layout.simple_list_item_1, rsvpList); listView.setAdapter(adapter); } }); }
diff --git a/plugins/org.jboss.tools.ws.ui/src/org/jboss/tools/ws/ui/views/WSDLBrowseDialog.java b/plugins/org.jboss.tools.ws.ui/src/org/jboss/tools/ws/ui/views/WSDLBrowseDialog.java index 4b42f8df..49704cfc 100644 --- a/plugins/org.jboss.tools.ws.ui/src/org/jboss/tools/ws/ui/views/WSDLBrowseDialog.java +++ b/plugins/org.jboss.tools.ws.ui/src/org/jboss/tools/ws/ui/views/WSDLBrowseDialog.java @@ -1,653 +1,659 @@ /******************************************************************************* * Copyright (c) 2010 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.ws.ui.views; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import javax.wsdl.Binding; import javax.wsdl.Definition; import javax.wsdl.Operation; import javax.wsdl.Port; import javax.wsdl.PortType; import javax.wsdl.Service; import javax.wsdl.WSDLException; import javax.wsdl.extensions.soap.SOAPBinding; import javax.wsdl.extensions.soap12.SOAP12Binding; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.jboss.tools.ws.core.utils.StatusUtils; import org.jboss.tools.ws.ui.JBossWSUIPlugin; import org.jboss.tools.ws.ui.messages.JBossWSUIMessages; import org.jboss.tools.ws.ui.utils.TesterWSDLUtils; /** * @author bfitzpat * */ public class WSDLBrowseDialog extends TitleAreaDialog { private Label locationLabel = null; private Combo locationCombo = null; private Button workspaceBrowseButton = null; private Button fsBrowseButton = null; private Button urlBrowseButton = null; private static String wsdlTextValue = null; private static String[] oldValues = null; private String serviceTextValue = null; private String portTextValue = null; private String operationTextValue = null; private String initialOperationTextValue = null; private String bindingValue = null; private Definition wsdlDefinition = null; private Label serviceLabel; private Combo serviceCombo; private Combo portCombo; private Label operationLabel; private List opList; private Group group; private Label portLabel; private boolean showServicePortOperaton = true; public WSDLBrowseDialog(Shell parentShell) { super(parentShell); setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE ); } public void setShowServicePortOperation (boolean flag ){ this.showServicePortOperaton = flag; } public boolean getShowServicePortOperation() { return this.showServicePortOperaton; } public String getWSDLText(){ return WSDLBrowseDialog.wsdlTextValue; } public String getBindingValue() { return bindingValue; } public String getServiceTextValue() { return serviceTextValue; } public String getPortTextValue() { return portTextValue; } public String getOperationTextValue() { return operationTextValue; } public void setInitialOperationTextValue( String value ) { initialOperationTextValue = value; } public Definition getWSDLDefinition(){ return this.wsdlDefinition; } public void setURLText(String urlText) { wsdlTextValue = urlText; } @SuppressWarnings("unchecked") @Override protected void okPressed() { WSDLBrowseDialog.wsdlTextValue = locationCombo.getText(); ArrayList<String> uriList = new ArrayList<String>(); if (WSDLBrowseDialog.oldValues != null) { @SuppressWarnings("rawtypes") java.util.List tempList = (java.util.List) Arrays.asList(WSDLBrowseDialog.oldValues); uriList.addAll(tempList); } if (!uriList.contains(locationCombo.getText())) { uriList.add(locationCombo.getText()); } WSDLBrowseDialog.oldValues = uriList.toArray(new String[uriList.size()]); super.okPressed(); } @Override protected Control createDialogArea(Composite parent) { setTitle(JBossWSUIMessages.WSDLBrowseDialog_Title); setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); Composite mainComposite = new Composite (parent,SWT.NONE); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 2; mainComposite.setLayoutData(gridData); GridLayout gridLayout = new GridLayout(2, false); mainComposite.setLayout(gridLayout); locationLabel = new Label(mainComposite, SWT.NONE); locationLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_WSDL_URI_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); locationCombo = new Combo(mainComposite, SWT.BORDER | SWT.DROP_DOWN ); locationCombo.setLayoutData(gridData); locationCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); IStatus status = validate(false); if (status != Status.OK_STATUS) { setMessage(status.getMessage(), IMessageProvider.WARNING); if (showServicePortOperaton) setGroupEnabled(false); } else { setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); if (showServicePortOperaton) setGroupEnabled(true); } } }); if (WSDLBrowseDialog.oldValues != null && WSDLBrowseDialog.oldValues.length > 0) { for (int i = 0; i < oldValues.length; i++) { locationCombo.add(WSDLBrowseDialog.oldValues[i]); } } Composite buttonBar = new Composite ( mainComposite, SWT.NONE); GridData buttonBarGD = new GridData(SWT.END, SWT.NONE, true, false); buttonBarGD.horizontalSpan = 2; buttonBar.setLayoutData(buttonBarGD); buttonBar.setLayout(new RowLayout()); workspaceBrowseButton = new Button(buttonBar, SWT.NONE); workspaceBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse); workspaceBrowseButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent arg0) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider()); dialog.setTitle(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Title); dialog.setMessage(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Msg); dialog.setInput(ResourcesPlugin.getWorkspace().getRoot()); dialog.setAllowMultiple(false); dialog.setEmptyListMessage(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Msg); dialog.setStatusLineAboveButtons(true); dialog.setValidator(new ISelectionStatusValidator() { public IStatus validate(Object[] arg0) { if (arg0.length > 0 && arg0[0] instanceof IFile) { IFile resource = (IFile) arg0[0]; if (resource.getFileExtension().equals("wsdl")) { //$NON-NLS-1$ return Status.OK_STATUS; } } return StatusUtils.errorStatus(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Msg); } }); int rtnCode = dialog.open(); if (rtnCode == Window.OK) { Object[] objects = dialog.getResult(); //fileDialog.getResult(); if (objects != null && objects.length > 0){ if (objects[0] instanceof IFile) { IFile resource = (IFile) objects[0]; File tempFile = new File(resource.getRawLocationURI()); try { URL testURL = tempFile.toURI().toURL(); locationCombo.setText(testURL.toExternalForm()); wsdlDefinition = TesterWSDLUtils.readWSDLURL(testURL); if (showServicePortOperaton) updateServiceCombo(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (WSDLException e) { e.printStackTrace(); } } } } } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); fsBrowseButton = new Button(buttonBar, SWT.NONE); fsBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_FS_Browse); fsBrowseButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent arg0) { FileDialog fileDialog = new FileDialog(getShell()); String[] filterExt = { "*.wsdl", "*.xml", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ fileDialog.setFilterExtensions(filterExt); if (locationCombo.getText().trim().length() > 0) { try { URI uri = new URI(locationCombo.getText()); File temp = new File(uri); String parentPath = temp.getParent(); fileDialog.setFilterPath(parentPath); fileDialog.setFileName(temp.getName()); } catch (URISyntaxException e1) { } catch (IllegalArgumentException e2) { } } String fileText = fileDialog.open(); if (fileText != null){ File tempFile = new File(fileText); try { URL testURL = tempFile.toURI().toURL(); locationCombo.setText(testURL.toExternalForm()); wsdlDefinition = TesterWSDLUtils.readWSDLURL(testURL); if (showServicePortOperaton) updateServiceCombo(); } catch (MalformedURLException e) { JBossWSUIPlugin.log(e); } catch (WSDLException e) { JBossWSUIPlugin.log(e); } } } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); urlBrowseButton = new Button(buttonBar, SWT.NONE); urlBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_URL_Browse); urlBrowseButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } public void widgetDefaultSelected(SelectionEvent arg0) { InputDialog inDialog = null; if (locationCombo.getText().trim().length() > 0) { inDialog = new InputDialog (getShell(), JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Dialog_Title, JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Prompt, locationCombo.getText(), null); } else { inDialog = new InputDialog (getShell(), JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Dialog_Title, JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Prompt, "", null); //$NON-NLS-1$ } int rtnCode = inDialog.open(); if (rtnCode == Window.OK) { locationCombo.setText(inDialog.getValue()); try { final URL testURL = new URL(inDialog.getValue()); locationCombo.setText(testURL.toExternalForm()); - IStatus status = parseWSDLFromURL(testURL, true); + IStatus status = validate(false); if (status != null && !status.isOK()) { - setMessage(status.getMessage()); + setMessage(status.getMessage(), IMessageProvider.WARNING); } else { - setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); - if (showServicePortOperaton) - updateServiceCombo(); + status = parseWSDLFromURL(testURL, true); + if (status != null && !status.isOK()) { + setMessage(status.getMessage(), IMessageProvider.WARNING); + } else { + setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); + if (showServicePortOperaton) { + updateServiceCombo(); + } + } } } catch (MalformedURLException e) { JBossWSUIPlugin.log(e); ErrorDialog.openError(getShell(), JBossWSUIMessages.WSDLBrowseDialog_Error_Retrieving_WSDL, JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Invalid_URL, StatusUtils.errorStatus(e)); } } } }); if (this.showServicePortOperaton) { group = new Group(mainComposite, SWT.NONE); group.setText(JBossWSUIMessages.WSDLBrowseDialog_Group_Title); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 2; group.setLayoutData(gridData); group.setLayout(new GridLayout(2, false)); serviceLabel = new Label(group, SWT.NONE); serviceLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Service_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); serviceCombo = new Combo(group, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY ); serviceCombo.setLayoutData(gridData); serviceCombo.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { updatePortCombo(); } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); portLabel = new Label(group, SWT.NONE); portLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Port_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); portCombo = new Combo(group, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY); portCombo.setLayoutData(gridData); portCombo.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { updateOperationList(); } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); operationLabel = new Label(group, SWT.NONE); operationLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Operation_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.verticalSpan = 3; gridData.heightHint = 50; opList = new List(group, SWT.BORDER | SWT.V_SCROLL ); opList.setLayoutData(gridData); opList.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { WSDLBrowseDialog.this.operationTextValue = opList.getSelection()[0]; } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); } mainComposite.pack(); return mainComposite; } class ReadWSDLProgress implements IRunnableWithProgress { private URL testURL = null; private IStatus result = null; public void setTestURL ( URL url ) { this.testURL = url; } public IStatus getResult() { return this.result; } public void run(IProgressMonitor monitor) { monitor .beginTask(JBossWSUIMessages.WSDLBrowseDialog_Status_ParsingWSDLFromURL, 100); try { IStatus testStatus = TesterWSDLUtils.isWSDLAccessible(testURL); if (testStatus.getSeverity() != IStatus.OK){ result = testStatus; } wsdlDefinition = TesterWSDLUtils.readWSDLURL(testURL); } catch (WSDLException e) { result = StatusUtils.errorStatus( JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Parse_Error, e); } monitor.done(); } } private IStatus parseWSDLFromURL ( final URL testURL, boolean showProgress) { if (showProgress) { ProgressMonitorDialog dialog = new ProgressMonitorDialog(Display.getCurrent().getActiveShell()); try { ReadWSDLProgress readWSDLProgress = new ReadWSDLProgress(); readWSDLProgress.setTestURL(testURL); dialog.run(true, true, readWSDLProgress); return readWSDLProgress.getResult(); } catch (InvocationTargetException e) { return StatusUtils.errorStatus( JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Parse_Error, e); } catch (InterruptedException e) { return StatusUtils.errorStatus( JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Parse_Error, e); } catch (NullPointerException e) { return StatusUtils.errorStatus( JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Parse_Error, e); } } else { try { IStatus testStatus = TesterWSDLUtils.isWSDLAccessible(testURL); if (testStatus.getSeverity() != IStatus.OK) { return StatusUtils.errorStatus(testStatus.getMessage(), testStatus.getException()); } wsdlDefinition = TesterWSDLUtils.readWSDLURL(testURL); } catch (WSDLException e) { return StatusUtils.errorStatus( JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Parse_Error, e); } catch (NullPointerException e) { return StatusUtils.errorStatus( JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Parse_Error, e); } } return Status.OK_STATUS; } private void updateOperationList(){ if (portCombo.getSelectionIndex() > -1) { String text = portCombo.getItem(portCombo.getSelectionIndex()); portTextValue = text; Port port = (Port) portCombo.getData(text); opList.removeAll(); Binding wsdlBinding = port.getBinding(); this.bindingValue = wsdlBinding.getQName().getLocalPart(); PortType portType = wsdlBinding.getPortType(); @SuppressWarnings("rawtypes") java.util.List operations = portType.getOperations(); @SuppressWarnings("unchecked") Operation[] operationsArray = (Operation[]) operations.toArray(new Operation[operations.size()]); Arrays.sort(operationsArray, new WSDLOperationComparator()); for (int i = 0; i < operationsArray.length; i++) { Operation operation = (Operation) operationsArray[i];//iter.next(); opList.add(operation.getName()); opList.setData(operation.getName(), operation); } if (opList.getItemCount() > 0) { boolean foundIt = false; if (initialOperationTextValue != null) { String[] thelist = opList.getItems(); for (int i = 0; i < thelist.length; i++) { if (thelist[i].contentEquals(initialOperationTextValue)) { opList.select(i); foundIt = true; break; } } } if (!foundIt) opList.select(0); this.operationTextValue = opList.getSelection()[0]; } } } class WSDLOperationComparator implements Comparator<Operation>{ public int compare(Operation o1, Operation o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } } private void updatePortCombo(){ if (serviceCombo.getSelectionIndex() > -1) { String text = serviceCombo.getItem(serviceCombo.getSelectionIndex()); serviceTextValue = text; Service service = (Service) serviceCombo.getData(text); portCombo.removeAll(); opList.removeAll(); Iterator<?> iter = service.getPorts().values().iterator(); while (iter.hasNext()) { Port port = (Port) iter.next(); if (port.getBinding() != null && port.getBinding().getExtensibilityElements() != null) { @SuppressWarnings("rawtypes") java.util.List elements = port.getBinding().getExtensibilityElements(); for (int i = 0; i < elements.size(); i++) { if (elements.get(i) instanceof SOAPBinding || elements.get(i) instanceof SOAP12Binding ) { portCombo.add(port.getName()); portCombo.setData(port.getName(), port); } } } } if (portCombo.getItemCount() > 0) { portCombo.select(0); portTextValue = portCombo.getText(); } updateOperationList(); } } private void updateServiceCombo () { serviceCombo.removeAll(); portCombo.removeAll(); opList.removeAll(); if (wsdlDefinition != null && wsdlDefinition.getServices() != null && !wsdlDefinition.getServices().isEmpty()) { Iterator<?> iter = wsdlDefinition.getServices().values().iterator(); while (iter.hasNext()) { Service service = (Service) iter.next(); serviceCombo.add(service.getQName().getLocalPart()); serviceCombo.setData(service.getQName().getLocalPart(), service); } if (serviceCombo.getItemCount() > 0) { serviceCombo.select(0); serviceTextValue = serviceCombo.getText(); } updatePortCombo(); } } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText(JBossWSUIMessages.WSDLBrowseDialog_Dialog_Title); } private void setGroupEnabled ( boolean flag ) { group.setEnabled(flag); operationLabel.setEnabled(flag); opList.setEnabled(flag); portCombo.setEnabled(flag); portLabel.setEnabled(flag); serviceCombo.setEnabled(flag); serviceLabel.setEnabled(flag); if (getButton(IDialogConstants.OK_ID) != null) { getButton(IDialogConstants.OK_ID).setEnabled(flag); } if (!flag) { opList.removeAll(); portCombo.removeAll(); portCombo.setText(""); //$NON-NLS-1$ serviceCombo.removeAll(); serviceCombo.setText(""); //$NON-NLS-1$ } } private IStatus validate(boolean showProgress){ String urlText = locationCombo.getText(); try { final URL testURL = new URL(urlText); IStatus status = parseWSDLFromURL(testURL, false); if (status != null && !status.isOK()) { return status; } // parseWSDLFromURL(testURL); // wsdlDefinition = // TesterWSDLUtils.readWSDLURL(testURL); if (showServicePortOperaton) updateServiceCombo(); } catch (MalformedURLException e) { return StatusUtils.errorStatus(JBossWSUIMessages.WSDLBrowseDialog_Status_Invalid_URL, e); // } catch (WSDLException e) { // return StatusUtils.errorStatus(JBossWSUIMessages.WSDLBrowseDialog_Status_WSDL_Unavailable, e); } return Status.OK_STATUS; } @Override protected Control createContents(Composite parent) { Control control = super.createContents(parent); if (showServicePortOperaton) setGroupEnabled(false); if (WSDLBrowseDialog.wsdlTextValue != null) { this.locationCombo.setText(wsdlTextValue); IStatus status = validate(false); if (status != Status.OK_STATUS) { if (showServicePortOperaton) setGroupEnabled(false); } else { if (showServicePortOperaton) setGroupEnabled(true); } } control.pack(true); return control; } }
false
true
protected Control createDialogArea(Composite parent) { setTitle(JBossWSUIMessages.WSDLBrowseDialog_Title); setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); Composite mainComposite = new Composite (parent,SWT.NONE); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 2; mainComposite.setLayoutData(gridData); GridLayout gridLayout = new GridLayout(2, false); mainComposite.setLayout(gridLayout); locationLabel = new Label(mainComposite, SWT.NONE); locationLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_WSDL_URI_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); locationCombo = new Combo(mainComposite, SWT.BORDER | SWT.DROP_DOWN ); locationCombo.setLayoutData(gridData); locationCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); IStatus status = validate(false); if (status != Status.OK_STATUS) { setMessage(status.getMessage(), IMessageProvider.WARNING); if (showServicePortOperaton) setGroupEnabled(false); } else { setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); if (showServicePortOperaton) setGroupEnabled(true); } } }); if (WSDLBrowseDialog.oldValues != null && WSDLBrowseDialog.oldValues.length > 0) { for (int i = 0; i < oldValues.length; i++) { locationCombo.add(WSDLBrowseDialog.oldValues[i]); } } Composite buttonBar = new Composite ( mainComposite, SWT.NONE); GridData buttonBarGD = new GridData(SWT.END, SWT.NONE, true, false); buttonBarGD.horizontalSpan = 2; buttonBar.setLayoutData(buttonBarGD); buttonBar.setLayout(new RowLayout()); workspaceBrowseButton = new Button(buttonBar, SWT.NONE); workspaceBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse); workspaceBrowseButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent arg0) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider()); dialog.setTitle(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Title); dialog.setMessage(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Msg); dialog.setInput(ResourcesPlugin.getWorkspace().getRoot()); dialog.setAllowMultiple(false); dialog.setEmptyListMessage(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Msg); dialog.setStatusLineAboveButtons(true); dialog.setValidator(new ISelectionStatusValidator() { public IStatus validate(Object[] arg0) { if (arg0.length > 0 && arg0[0] instanceof IFile) { IFile resource = (IFile) arg0[0]; if (resource.getFileExtension().equals("wsdl")) { //$NON-NLS-1$ return Status.OK_STATUS; } } return StatusUtils.errorStatus(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Msg); } }); int rtnCode = dialog.open(); if (rtnCode == Window.OK) { Object[] objects = dialog.getResult(); //fileDialog.getResult(); if (objects != null && objects.length > 0){ if (objects[0] instanceof IFile) { IFile resource = (IFile) objects[0]; File tempFile = new File(resource.getRawLocationURI()); try { URL testURL = tempFile.toURI().toURL(); locationCombo.setText(testURL.toExternalForm()); wsdlDefinition = TesterWSDLUtils.readWSDLURL(testURL); if (showServicePortOperaton) updateServiceCombo(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (WSDLException e) { e.printStackTrace(); } } } } } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); fsBrowseButton = new Button(buttonBar, SWT.NONE); fsBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_FS_Browse); fsBrowseButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent arg0) { FileDialog fileDialog = new FileDialog(getShell()); String[] filterExt = { "*.wsdl", "*.xml", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ fileDialog.setFilterExtensions(filterExt); if (locationCombo.getText().trim().length() > 0) { try { URI uri = new URI(locationCombo.getText()); File temp = new File(uri); String parentPath = temp.getParent(); fileDialog.setFilterPath(parentPath); fileDialog.setFileName(temp.getName()); } catch (URISyntaxException e1) { } catch (IllegalArgumentException e2) { } } String fileText = fileDialog.open(); if (fileText != null){ File tempFile = new File(fileText); try { URL testURL = tempFile.toURI().toURL(); locationCombo.setText(testURL.toExternalForm()); wsdlDefinition = TesterWSDLUtils.readWSDLURL(testURL); if (showServicePortOperaton) updateServiceCombo(); } catch (MalformedURLException e) { JBossWSUIPlugin.log(e); } catch (WSDLException e) { JBossWSUIPlugin.log(e); } } } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); urlBrowseButton = new Button(buttonBar, SWT.NONE); urlBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_URL_Browse); urlBrowseButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } public void widgetDefaultSelected(SelectionEvent arg0) { InputDialog inDialog = null; if (locationCombo.getText().trim().length() > 0) { inDialog = new InputDialog (getShell(), JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Dialog_Title, JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Prompt, locationCombo.getText(), null); } else { inDialog = new InputDialog (getShell(), JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Dialog_Title, JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Prompt, "", null); //$NON-NLS-1$ } int rtnCode = inDialog.open(); if (rtnCode == Window.OK) { locationCombo.setText(inDialog.getValue()); try { final URL testURL = new URL(inDialog.getValue()); locationCombo.setText(testURL.toExternalForm()); IStatus status = parseWSDLFromURL(testURL, true); if (status != null && !status.isOK()) { setMessage(status.getMessage()); } else { setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); if (showServicePortOperaton) updateServiceCombo(); } } catch (MalformedURLException e) { JBossWSUIPlugin.log(e); ErrorDialog.openError(getShell(), JBossWSUIMessages.WSDLBrowseDialog_Error_Retrieving_WSDL, JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Invalid_URL, StatusUtils.errorStatus(e)); } } } }); if (this.showServicePortOperaton) { group = new Group(mainComposite, SWT.NONE); group.setText(JBossWSUIMessages.WSDLBrowseDialog_Group_Title); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 2; group.setLayoutData(gridData); group.setLayout(new GridLayout(2, false)); serviceLabel = new Label(group, SWT.NONE); serviceLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Service_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); serviceCombo = new Combo(group, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY ); serviceCombo.setLayoutData(gridData); serviceCombo.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { updatePortCombo(); } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); portLabel = new Label(group, SWT.NONE); portLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Port_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); portCombo = new Combo(group, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY); portCombo.setLayoutData(gridData); portCombo.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { updateOperationList(); } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); operationLabel = new Label(group, SWT.NONE); operationLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Operation_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.verticalSpan = 3; gridData.heightHint = 50; opList = new List(group, SWT.BORDER | SWT.V_SCROLL ); opList.setLayoutData(gridData); opList.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { WSDLBrowseDialog.this.operationTextValue = opList.getSelection()[0]; } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); } mainComposite.pack(); return mainComposite; }
protected Control createDialogArea(Composite parent) { setTitle(JBossWSUIMessages.WSDLBrowseDialog_Title); setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); Composite mainComposite = new Composite (parent,SWT.NONE); GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 2; mainComposite.setLayoutData(gridData); GridLayout gridLayout = new GridLayout(2, false); mainComposite.setLayout(gridLayout); locationLabel = new Label(mainComposite, SWT.NONE); locationLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_WSDL_URI_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); locationCombo = new Combo(mainComposite, SWT.BORDER | SWT.DROP_DOWN ); locationCombo.setLayoutData(gridData); locationCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); IStatus status = validate(false); if (status != Status.OK_STATUS) { setMessage(status.getMessage(), IMessageProvider.WARNING); if (showServicePortOperaton) setGroupEnabled(false); } else { setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); if (showServicePortOperaton) setGroupEnabled(true); } } }); if (WSDLBrowseDialog.oldValues != null && WSDLBrowseDialog.oldValues.length > 0) { for (int i = 0; i < oldValues.length; i++) { locationCombo.add(WSDLBrowseDialog.oldValues[i]); } } Composite buttonBar = new Composite ( mainComposite, SWT.NONE); GridData buttonBarGD = new GridData(SWT.END, SWT.NONE, true, false); buttonBarGD.horizontalSpan = 2; buttonBar.setLayoutData(buttonBarGD); buttonBar.setLayout(new RowLayout()); workspaceBrowseButton = new Button(buttonBar, SWT.NONE); workspaceBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse); workspaceBrowseButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent arg0) { ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider()); dialog.setTitle(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Title); dialog.setMessage(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Msg); dialog.setInput(ResourcesPlugin.getWorkspace().getRoot()); dialog.setAllowMultiple(false); dialog.setEmptyListMessage(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Msg); dialog.setStatusLineAboveButtons(true); dialog.setValidator(new ISelectionStatusValidator() { public IStatus validate(Object[] arg0) { if (arg0.length > 0 && arg0[0] instanceof IFile) { IFile resource = (IFile) arg0[0]; if (resource.getFileExtension().equals("wsdl")) { //$NON-NLS-1$ return Status.OK_STATUS; } } return StatusUtils.errorStatus(JBossWSUIMessages.WSDLBrowseDialog_WS_Browse_Select_WSDL_Msg); } }); int rtnCode = dialog.open(); if (rtnCode == Window.OK) { Object[] objects = dialog.getResult(); //fileDialog.getResult(); if (objects != null && objects.length > 0){ if (objects[0] instanceof IFile) { IFile resource = (IFile) objects[0]; File tempFile = new File(resource.getRawLocationURI()); try { URL testURL = tempFile.toURI().toURL(); locationCombo.setText(testURL.toExternalForm()); wsdlDefinition = TesterWSDLUtils.readWSDLURL(testURL); if (showServicePortOperaton) updateServiceCombo(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (WSDLException e) { e.printStackTrace(); } } } } } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); fsBrowseButton = new Button(buttonBar, SWT.NONE); fsBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_FS_Browse); fsBrowseButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent arg0) { FileDialog fileDialog = new FileDialog(getShell()); String[] filterExt = { "*.wsdl", "*.xml", "*.*" }; //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$ fileDialog.setFilterExtensions(filterExt); if (locationCombo.getText().trim().length() > 0) { try { URI uri = new URI(locationCombo.getText()); File temp = new File(uri); String parentPath = temp.getParent(); fileDialog.setFilterPath(parentPath); fileDialog.setFileName(temp.getName()); } catch (URISyntaxException e1) { } catch (IllegalArgumentException e2) { } } String fileText = fileDialog.open(); if (fileText != null){ File tempFile = new File(fileText); try { URL testURL = tempFile.toURI().toURL(); locationCombo.setText(testURL.toExternalForm()); wsdlDefinition = TesterWSDLUtils.readWSDLURL(testURL); if (showServicePortOperaton) updateServiceCombo(); } catch (MalformedURLException e) { JBossWSUIPlugin.log(e); } catch (WSDLException e) { JBossWSUIPlugin.log(e); } } } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); urlBrowseButton = new Button(buttonBar, SWT.NONE); urlBrowseButton.setText(JBossWSUIMessages.WSDLBrowseDialog_URL_Browse); urlBrowseButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } public void widgetDefaultSelected(SelectionEvent arg0) { InputDialog inDialog = null; if (locationCombo.getText().trim().length() > 0) { inDialog = new InputDialog (getShell(), JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Dialog_Title, JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Prompt, locationCombo.getText(), null); } else { inDialog = new InputDialog (getShell(), JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Dialog_Title, JBossWSUIMessages.WSDLBrowseDialog_WSDL_URL_Prompt, "", null); //$NON-NLS-1$ } int rtnCode = inDialog.open(); if (rtnCode == Window.OK) { locationCombo.setText(inDialog.getValue()); try { final URL testURL = new URL(inDialog.getValue()); locationCombo.setText(testURL.toExternalForm()); IStatus status = validate(false); if (status != null && !status.isOK()) { setMessage(status.getMessage(), IMessageProvider.WARNING); } else { status = parseWSDLFromURL(testURL, true); if (status != null && !status.isOK()) { setMessage(status.getMessage(), IMessageProvider.WARNING); } else { setMessage(JBossWSUIMessages.WSDLBrowseDialog_Message); if (showServicePortOperaton) { updateServiceCombo(); } } } } catch (MalformedURLException e) { JBossWSUIPlugin.log(e); ErrorDialog.openError(getShell(), JBossWSUIMessages.WSDLBrowseDialog_Error_Retrieving_WSDL, JBossWSUIMessages.WSDLBrowseDialog_Error_Msg_Invalid_URL, StatusUtils.errorStatus(e)); } } } }); if (this.showServicePortOperaton) { group = new Group(mainComposite, SWT.NONE); group.setText(JBossWSUIMessages.WSDLBrowseDialog_Group_Title); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.horizontalSpan = 2; group.setLayoutData(gridData); group.setLayout(new GridLayout(2, false)); serviceLabel = new Label(group, SWT.NONE); serviceLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Service_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); serviceCombo = new Combo(group, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY ); serviceCombo.setLayoutData(gridData); serviceCombo.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { updatePortCombo(); } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); portLabel = new Label(group, SWT.NONE); portLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Port_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); portCombo = new Combo(group, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY); portCombo.setLayoutData(gridData); portCombo.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { updateOperationList(); } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); operationLabel = new Label(group, SWT.NONE); operationLabel.setText(JBossWSUIMessages.WSDLBrowseDialog_Operation_Field); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridData.verticalSpan = 3; gridData.heightHint = 50; opList = new List(group, SWT.BORDER | SWT.V_SCROLL ); opList.setLayoutData(gridData); opList.addSelectionListener(new SelectionListener(){ public void widgetDefaultSelected(SelectionEvent arg0) { WSDLBrowseDialog.this.operationTextValue = opList.getSelection()[0]; } public void widgetSelected(SelectionEvent arg0) { widgetDefaultSelected(arg0); } }); } mainComposite.pack(); return mainComposite; }
diff --git a/src/openmap/com/bbn/openmap/gui/time/TimeSliderLayer.java b/src/openmap/com/bbn/openmap/gui/time/TimeSliderLayer.java index 0ea6e3a1..48123867 100644 --- a/src/openmap/com/bbn/openmap/gui/time/TimeSliderLayer.java +++ b/src/openmap/com/bbn/openmap/gui/time/TimeSliderLayer.java @@ -1,1042 +1,1042 @@ // ********************************************************************** // // <copyright> // // BBN Technologies, a Verizon Company // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // </copyright> package com.bbn.openmap.gui.time; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Polygon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import com.bbn.openmap.Environment; import com.bbn.openmap.I18n; import com.bbn.openmap.MapBean; import com.bbn.openmap.MapHandler; import com.bbn.openmap.event.CenterListener; import com.bbn.openmap.event.CenterSupport; import com.bbn.openmap.event.MapMouseListener; import com.bbn.openmap.event.ZoomEvent; import com.bbn.openmap.event.ZoomListener; import com.bbn.openmap.event.ZoomSupport; import com.bbn.openmap.layer.OMGraphicHandlerLayer; import com.bbn.openmap.omGraphics.DrawingAttributes; import com.bbn.openmap.omGraphics.OMGraphicList; import com.bbn.openmap.omGraphics.OMLine; import com.bbn.openmap.omGraphics.OMPoly; import com.bbn.openmap.omGraphics.OMRect; import com.bbn.openmap.omGraphics.OMScalingIcon; import com.bbn.openmap.proj.Cartesian; import com.bbn.openmap.proj.Projection; import com.bbn.openmap.time.Clock; import com.bbn.openmap.time.TimeBounds; import com.bbn.openmap.time.TimeBoundsEvent; import com.bbn.openmap.time.TimeBoundsListener; import com.bbn.openmap.time.TimeEvent; import com.bbn.openmap.time.TimeEventListener; import com.bbn.openmap.time.TimerStatus; import com.bbn.openmap.tools.icon.BasicIconPart; import com.bbn.openmap.tools.icon.IconPart; import com.bbn.openmap.tools.icon.OMIconFactory; /** * Timeline layer * * Render events and allow for their selection on a variable-scale timeline */ public class TimeSliderLayer extends OMGraphicHandlerLayer implements PropertyChangeListener, MapMouseListener, ComponentListener, TimeBoundsListener, TimeEventListener { protected static Logger logger = Logger.getLogger("com.bbn.openmap.gui.time.TimeSliderLayer"); protected I18n i18n = Environment.getI18n(); protected CenterSupport centerDelegate; protected ZoomSupport zoomDelegate; long currentTime = 0; long gameStartTime = 0; long gameEndTime = 0; // KMTODO package this up into a standalone widget? // Times are generally in minutes double selectionWidthMinutes = 1.0; double maxSelectionWidthMinutes = 1.0; double selectionCenter = 0; OMRect boundsRectLeftHandle; // handles for scaling selection OMRect boundsRectRightHandle; OMLine baseLine; // thick line along middle OMPoly contextPoly; // lines that relate time slider to timeline above. int sliderPointHalfWidth = 5; TimelinePanel timelinePanel; TimelineLayer timelineLayer; public static double magicScaleFactor = 100000000; // KMTODO (Don? I guess // this is to // address a precision issue?) Clock clock; LabelPanel labelPanel; private boolean isNoTime = true; // In realTimeMode, gameEndTime is the origin, rather than gameStartTime private final boolean realTimeMode; // Used to refrain from re-scaling every TimeBoundsUpdate (in realTimeMode // only) private boolean userHasChangedScale = false; private final List<ITimeBoundsUserActionsListener> timeBoundsUserActionsListeners = new ArrayList<ITimeBoundsUserActionsListener>(); private final JButton zoomToSelection = new JButton("Zoom to Selection"); private final JButton renderFixedSelection = new JButton("Show Entire Selection"); /** * Construct the TimelineLayer. * * @param realTimeMode TODO */ public TimeSliderLayer(boolean realTimeMode) { this.realTimeMode = realTimeMode; setName("TimeSlider"); // This is how to set the ProjectionChangePolicy, which // dictates how the layer behaves when a new projection is // received. setProjectionChangePolicy(new com.bbn.openmap.layer.policy.StandardPCPolicy(this, false)); // Making the setting so this layer receives events from the // SelectMouseMode, which has a modeID of "Gestures". Other // IDs can be added as needed. setMouseModeIDsForEvents(new String[] { "Gestures" }); centerDelegate = new CenterSupport(this); zoomDelegate = new ZoomSupport(this); addComponentListener(this); } public void findAndInit(Object someObj) { if (someObj instanceof Clock) { clock = ((Clock) someObj); clock.addTimeEventListener(this); clock.addTimeBoundsListener(this); gameStartTime = ((Clock) someObj).getStartTime(); gameEndTime = ((Clock) someObj).getEndTime(); // Just in case we missed an early TimeBoundEvent updateTimeBounds(gameStartTime, gameEndTime); } if (someObj instanceof CenterListener) { centerDelegate.add((CenterListener) someObj); } if (someObj instanceof ZoomListener) { zoomDelegate.add((ZoomListener) someObj); } if (someObj instanceof TimelinePanel.Wrapper) { timelinePanel = ((TimelinePanel.Wrapper) someObj).getTimelinePanel(); timelinePanel.getMapBean().addPropertyChangeListener(this); timelineLayer = timelinePanel.getTimelineLayer(); } } /** * Called with the projection changes, should just generate the current * markings for the new projection. */ public synchronized OMGraphicList prepare() { OMGraphicList list = getList(); if (list == null) { list = new OMGraphicList(); } else { list.clear(); } TimeDrape drape = new TimeDrape(0, 0, -1, -1); drape.setVisible(isNoTime); drape.setFillPaint(Color.gray); drape.generate(getProjection()); list.add(drape); list.add(getControlWidgetList(getProjection())); return list; } /** * All we want to do here is reset the current position of all of the * widgets, and generate them with the projection for the new position. After * this call, the widgets are ready to paint. */ public synchronized OMGraphicList getControlWidgetList(Projection proj) { Projection projection = getProjection(); OMGraphicList controlWidgetList = new OMGraphicList(); // triangle indicating center of selection ImageIcon selectionPointImage; DrawingAttributes da = new DrawingAttributes(); da.setFillPaint(TimelineLayer.tint); da.setLinePaint(TimelineLayer.tint); IconPart ip = new BasicIconPart(new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { 10, 90, 90, 10 }, 4), da); selectionPointImage = OMIconFactory.getIcon(32, 32, ip); - OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, -5, 6, selectionPointImage, 1.0f); + OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, 0, 6, selectionPointImage, 1.0f); final float selectionPointScale = 1.8f; selectionPoint.setMaxScale(selectionPointScale); selectionPoint.setMinScale(selectionPointScale); controlWidgetList.add(selectionPoint); boundsRectLeftHandle = new OMRect(0, 0, 0, 0); boundsRectLeftHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectLeftHandle); boundsRectRightHandle = new OMRect(0, 0, 0, 0); boundsRectRightHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectRightHandle); int[] xs = new int[8]; int[] ys = new int[8]; contextPoly = new OMPoly(xs, ys); contextPoly.setFillPaint(Color.white); controlWidgetList.add(contextPoly); baseLine = new OMLine(0, 0, 0, 0); baseLine.setLinePaint(Color.BLACK); baseLine.setStroke(new BasicStroke(2)); controlWidgetList.add(baseLine); if (projection == null) { return controlWidgetList; // Huhn? } double screenWidth = projection.getWidth(); float scale = (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); Point2D projCenter = projection.getCenter(); // TODO reconsider proper test here - for the moment, just brute-force // reproject always if (projCenter.getX() > selectionWidthMinutes || scale != projection.getScale()) { double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; projCenter.setLocation(nCenterLon, 0); projection = new Cartesian(projCenter, scale, projection.getWidth(), projection.getHeight()); setProjection(projection); } // Reset primary handle int contextBuffer = (int) (projection.getHeight() * .4); // If 'selectionCenter' is outside current time bounds, first attempt to // recompute from currentTime if (selectionCenter * 60.0 * TimeUnit.SECONDS.toMillis(1) > (gameEndTime - gameStartTime) || selectionCenter < 0) { selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); } // And if _that_ fails, just clamp // DFD changed from TimeUnit.MINUTE.toMillis(1) to MILLISECONDS because // Java 5 doesn't have MINUTE if (selectionCenter * TimeUnit.MILLISECONDS.toMillis(60000) > (gameEndTime - gameStartTime)) { selectionCenter = (gameEndTime - gameStartTime) / TimeUnit.MILLISECONDS.toMillis(60000); } if (selectionCenter < 0) { selectionCenter = 0; } int x = (int) projection.forward(0, selectionCenter).getX(); // Reset bounds and handles Point2D sliderEndPoint = projection.forward(0, selectionWidthMinutes); Point2D origin = projection.forward(0, 0); int selectionHalfWidth = (int) ((sliderEndPoint.getX() - origin.getX()) / 2); int north = contextBuffer; int west = x - selectionHalfWidth; int south = projection.getHeight() - 1; int east = x + selectionHalfWidth; int mid = contextBuffer + 1 + (south - contextBuffer) / 2; if (logger.isLoggable(Level.FINE)) { logger.fine("selectionCenter:" + selectionCenter + ", selectionWidthMinutes:" + selectionWidthMinutes + ", x:" + x + ", origin:" + origin); logger.fine(" projection:" + projection); } selectionPoint.setLon((float) selectionCenter); selectionPoint.generate(projection); // and the two handles for the bounds int handleWest = west - sliderPointHalfWidth; int handleEast = west + sliderPointHalfWidth; final int sliderPointHalfHeight = 2; boundsRectLeftHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectLeftHandle.generate(projection); handleWest = east - sliderPointHalfWidth; handleEast = east + sliderPointHalfWidth; boundsRectRightHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectRightHandle.generate(projection); // and the context lines, that show how the current selection maps to // the timeline above xs = contextPoly.getXs(); ys = contextPoly.getYs(); xs[0] = 0; ys[0] = -1; xs[1] = 0; ys[1] = north; xs[2] = west; ys[2] = north; xs[3] = west; ys[3] = south; xs[4] = east; ys[4] = south; xs[5] = east; ys[5] = north; xs[6] = projection.getWidth() - 1; ys[6] = north; xs[7] = projection.getWidth() - 1; ys[7] = -1; contextPoly.generate(projection); baseLine.setPts(new int[] { 0, mid, projection.getWidth(), mid }); baseLine.generate(projection); return controlWidgetList; } protected void updateTimeline() { if (timelinePanel != null) { float scale = (float) (magicScaleFactor * selectionWidthMinutes / getProjection().getWidth()); if (logger.isLoggable(Level.FINE)) { logger.fine("Updating timeline with scale: " + scale); } timelinePanel.getMapBean().setScale(scale); } } public String getName() { return "TimelineLayer"; } /** * Updates zoom and center listeners with new projection information. * */ protected void finalizeProjection() { Projection projection = getProjection(); Cartesian cartesian = (projection instanceof Cartesian) ? (Cartesian) projection : null; if (cartesian != null) { double screenWidth = cartesian.getWidth(); cartesian.setLeftLimit(TimelineLayer.forwardProjectMillis(gameStartTime)); cartesian.setRightLimit(TimelineLayer.forwardProjectMillis(gameEndTime)); cartesian.setLimitAnchorPoint(new Point2D.Double(TimelineLayer.forwardProjectMillis(-gameStartTime), 0)); float scale = (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); zoomDelegate.fireZoom(ZoomEvent.ABSOLUTE, scale); double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; logger.fine("Telling the center delegate that the new center is 0, " + nCenterLon); centerDelegate.fireCenter(0, nCenterLon); // We are getting really large values for the center point of the // projection that the layer knows about. The MapBean projection // gets set OK, but then the projection held by the layer wrong, and // it throws the whole widget out of wack. If we set // the center of the projection to what it should be (the center // point between the start and end times), then everything settles // out. double x = cartesian.getCenter().getX(); if (x != nCenterLon) { ((MapBean) ((MapHandler) getBeanContext()).get(MapBean.class)).setCenter(0, nCenterLon); } repaint(); } } public void updateTime(TimeEvent te) { if (checkAndSetForNoTime(te)) { return; } TimerStatus timerStatus = te.getTimerStatus(); if (timerStatus.equals(TimerStatus.STEP_FORWARD) || timerStatus.equals(TimerStatus.STEP_BACKWARD) || timerStatus.equals(TimerStatus.UPDATE)) { currentTime = te.getSystemTime(); currentTime -= gameStartTime; selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); doPrepare(); } if (timerStatus.equals(TimerStatus.FORWARD) || timerStatus.equals(TimerStatus.BACKWARD) || timerStatus.equals(TimerStatus.STOPPED)) { if (logger.isLoggable(Level.FINE)) { logger.fine("updated time: " + te); } // Checking for a running clock prevents a time status // update after the clock is stopped. The // AudioFileHandlers don't care about the current time // if it isn't running. if (realTimeMode || ((Clock) te.getSource()).isRunning()) { // update(te.getSystemTime()); currentTime = te.getSystemTime(); currentTime -= gameStartTime; selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); doPrepare(); } } } /* * @seejava.beans.PropertyChangeListener#propertyChange(java.beans. * PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if (propertyName == MapBean.ProjectionProperty) { // This property should be from the TimelineLayer's MapBean, solely // for the scale measurement. logger.fine(propertyName + " from " + evt.getSource()); Projection timeLineProj = (Projection) evt.getNewValue(); // Need to solve for selectionWidthMinutes if (!realTimeMode || !userHasChangedScale) { selectionWidthMinutes = timeLineProj.getScale() * getProjection().getWidth() / magicScaleFactor; } if (selectionWidthMinutes > maxSelectionWidthMinutes + .0001 /* || selectionWidthMinutes < .0001 */) { if (logger.isLoggable(Level.FINE)) { logger.fine("resetting selectionWidthMinutes to max (projection change property change), was " + selectionWidthMinutes + ", now " + maxSelectionWidthMinutes); } selectionWidthMinutes = maxSelectionWidthMinutes; } doPrepare(); } } public boolean getUserHasChangedScale() { return userHasChangedScale; } public void setUserHasChangedScale(boolean userHasChangedScale) { this.userHasChangedScale = userHasChangedScale; } protected boolean checkAndSetForNoTime(TimeEvent te) { isNoTime = te == TimeEvent.NO_TIME; return isNoTime; } public MapMouseListener getMapMouseListener() { return this; } public String[] getMouseModeServiceList() { return getMouseModeIDsForEvents(); } enum DragState { NONE, PRIMARY_HANDLE, LEFT_HANDLE, RIGHT_HANDLE } DragState dragState = DragState.NONE; public boolean mousePressed(MouseEvent e) { updateMouseTimeDisplay(e); clearFixedRenderRange(); int x = e.getPoint().x; int y = e.getPoint().y; if (boundsRectLeftHandle.contains(x, y)) { dragState = DragState.LEFT_HANDLE; userHasChangedScale = true; } else if (boundsRectRightHandle.contains(x, y)) { dragState = DragState.RIGHT_HANDLE; userHasChangedScale = true; } else { dragState = DragState.PRIMARY_HANDLE; Projection projection = getProjection(); if (projection != null) { Point2D invPnt = projection.inverse(x, y); setSelectionCenter(invPnt.getX()); updateTimeline(); } } return true; } public boolean mouseReleased(MouseEvent e) { updateMouseTimeDisplay(e); dragState = DragState.NONE; return false; } public boolean mouseClicked(MouseEvent e) { updateMouseTimeDisplay(e); return false; } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { timelineLayer.updateMouseTimeDisplay(new Long(-1)); } void setSelectionCenter(double newCenter) { selectionCenter = newCenter; if (selectionCenter < 0) { selectionCenter = 0; } double offsetEnd = (double) (gameEndTime - gameStartTime) / 1000.0 / 60.0; if (selectionCenter > offsetEnd) { selectionCenter = offsetEnd; } clock.setTime(gameStartTime + (long) (selectionCenter * 60 * 1000)); } public boolean mouseDragged(MouseEvent e) { updateMouseTimeDisplay(e); Projection projection = getProjection(); if (projection == null) { return false; // Huhn? } double worldMouse; Point2D invPnt; int x = e.getPoint().x; int y = e.getPoint().y; int selectionCenterX = (int) projection.forward(0, selectionCenter).getX(); boolean scaleChange = false; switch (dragState) { case PRIMARY_HANDLE: invPnt = projection.inverse(x, y); setSelectionCenter(invPnt.getX()); break; case LEFT_HANDLE: if (x >= selectionCenterX - sliderPointHalfWidth) { x = selectionCenterX - sliderPointHalfWidth; } invPnt = projection.inverse(x, y); worldMouse = invPnt.getX(); selectionWidthMinutes = 2 * (selectionCenter - worldMouse); scaleChange = true; break; case RIGHT_HANDLE: if (x <= selectionCenterX + sliderPointHalfWidth) { x = selectionCenterX + sliderPointHalfWidth; } invPnt = projection.inverse(x, y); worldMouse = invPnt.getX(); selectionWidthMinutes = 2 * (worldMouse - selectionCenter); scaleChange = true; break; } if(scaleChange) { if (selectionWidthMinutes > maxSelectionWidthMinutes) { if (logger.isLoggable(Level.FINE)) { logger.fine("resetting selectionWidthMinutes to max, was " + selectionWidthMinutes + ", now " + maxSelectionWidthMinutes); } selectionWidthMinutes = maxSelectionWidthMinutes; } updateTimeline(); timelineLayer.doPrepare(); } doPrepare(); return true; } public boolean mouseMoved(MouseEvent e) { updateMouseTimeDisplay(e); return true; } public void mouseMoved() { } protected double updateMouseTimeDisplay(MouseEvent e) { Projection proj = getProjection(); Point2D latLong = proj.inverse(e.getPoint()); double lon = latLong.getX(); double endTime = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime); if (lon < 0) { lon = 0; } else if (lon > endTime) { lon = endTime; } long offsetMillis = TimelineLayer.inverseProjectMillis(lon); timelineLayer.updateMouseTimeDisplay(new Long(offsetMillis)); return lon; } public void componentHidden(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentResized(ComponentEvent e) { finalizeProjection(); } public void componentShown(ComponentEvent e) { } public LabelPanel getTimeLabels() { if (labelPanel == null) { labelPanel = new LabelPanel(); } return labelPanel; } public void updateTimeLabels(long startTime, long endTime) { LabelPanel lp = getTimeLabels(); lp.updateTimeLabels(startTime, endTime); } class LabelPanel extends JPanel implements com.bbn.openmap.gui.MapPanelChild { protected JComponent timeStartLabel; protected JComponent timeEndLabel; public final static String NO_TIME_STRING = "--/--/-- (--:--:--)"; public LabelPanel() { GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); setLayout(gridbag); if (realTimeMode) { JButton timeStartLabelButton = new JButton(NO_TIME_STRING); timeStartLabelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.invokeDateSelectionGUI(false); } } }); timeStartLabel = timeStartLabelButton; Font f = timeStartLabel.getFont(); f = new Font(f.getFamily(), f.getStyle(), f.getSize() - 1); timeStartLabel.setFont(f); gridbag.setConstraints(timeStartLabel, c); add(timeStartLabel); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; JLabel buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); renderFixedSelection.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { long selectionStart = timelineLayer.getSelectionStart(); long selectionEnd = timelineLayer.getSelectionEnd(); if (selectionStart > 0 && selectionEnd > 0) { for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.setFixedRenderRange(selectionStart, selectionEnd); } } } }); renderFixedSelection.setEnabled(false); renderFixedSelection.setFont(f); c.weightx = 0f; gridbag.setConstraints(renderFixedSelection, c); add(renderFixedSelection); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); zoomToSelection.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { long selectionStart = timelineLayer.getSelectionStart(); long selectionEnd = timelineLayer.getSelectionEnd(); if (selectionStart > 0 && selectionEnd > 0) { timelineLayer.clearSelection(); userHasChangedScale = false; for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.setTimeBounds(selectionStart, selectionEnd); } updateTimeBounds(selectionStart, selectionEnd); updateTimeline(); } } }); zoomToSelection.setEnabled(false); zoomToSelection.setFont(f); c.weightx = 0f; gridbag.setConstraints(zoomToSelection, c); add(zoomToSelection); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); JButton jumpToRealTime = new JButton("Jump to Real Time"); jumpToRealTime.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { userHasChangedScale = false; for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.jumpToRealTime(); } updateTimeline(); } }); jumpToRealTime.setFont(f); c.weightx = 0f; gridbag.setConstraints(jumpToRealTime, c); add(jumpToRealTime); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); c.fill = GridBagConstraints.NONE; c.weightx = 0f; JButton timeEndLabelButton = new JButton(NO_TIME_STRING); timeEndLabelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.invokeDateSelectionGUI(true); } } }); timeEndLabel = timeEndLabelButton; timeEndLabel.setFont(f); gridbag.setConstraints(timeEndLabel, c); add(timeEndLabel); } else { timeStartLabel = new JLabel(NO_TIME_STRING); Font f = timeStartLabel.getFont(); f = new Font(f.getFamily(), f.getStyle(), f.getSize() - 1); timeStartLabel.setFont(f); gridbag.setConstraints(timeStartLabel, c); add(timeStartLabel); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0f; JLabel buffer = new JLabel(); gridbag.setConstraints(buffer, c); add(buffer); c.fill = GridBagConstraints.NONE; c.weightx = 0f; timeEndLabel = new JLabel(NO_TIME_STRING, JLabel.RIGHT); timeEndLabel.setFont(f); gridbag.setConstraints(timeEndLabel, c); add(timeEndLabel); } } public String getPreferredLocation() { return BorderLayout.SOUTH; } public void setPreferredLocation(String string) { } public void updateTimeLabels(long startTime, long endTime) { if (realTimeMode) { ((JButton) timeStartLabel).setText(getLabelStringForTime(startTime)); ((JButton) timeEndLabel).setText(getLabelStringForTime(endTime)); } else { ((JLabel) timeStartLabel).setText(getLabelStringForTime(startTime)); ((JLabel) timeEndLabel).setText(getLabelStringForTime(endTime)); } } public String getLabelStringForTime(long time) { String ret = NO_TIME_STRING; if (time != Long.MAX_VALUE && time != Long.MIN_VALUE) { Date date = new Date(time); ret = TimePanel.dateFormat.format(date); } return ret; } public String getParentName() { // TODO Auto-generated method stub return null; } } public void paint(Graphics g) { try { super.paint(g); } catch (Exception e) { if (logger.isLoggable(Level.FINE)) { logger.warning(e.getMessage()); e.printStackTrace(); } } } public static class TimeDrape extends OMRect { int lo; int to; int ro; int bo; public TimeDrape(int leftOffset, int topOffset, int rightOffset, int bottomOffset) { super(0, 0, 0, 0); lo = leftOffset; to = topOffset; ro = rightOffset; bo = bottomOffset; } public boolean generate(Projection proj) { setLocation(0 + lo, 0 + to, proj.getWidth() + ro, proj.getHeight() + bo); return super.generate(proj); } } public void updateTimeBounds(TimeBoundsEvent tbe) { if (logger.isLoggable(Level.FINE)) { logger.fine("updating time bounds: " + tbe); } TimeBounds timeBounds = (TimeBounds) tbe.getNewTimeBounds(); if (timeBounds != null) { updateTimeBounds(timeBounds.getStartTime(), timeBounds.getEndTime()); } else { // TODO handle when time bounds are null, meaning when no time // bounds providers are active. } } public void updateTimeBounds(long start, long end) { // Recall that currentTime is in relative space (assumes start == 0) long boundsStartOffset = start - gameStartTime; currentTime -= boundsStartOffset; selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); gameStartTime = start; gameEndTime = end; updateTimeLabels(gameStartTime, gameEndTime); // DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy // HH:mm:ss"); // Date date = new Date(gameStartTime); // String sts = dateFormat.format(date); // date.setTime(gameEndTime); // String ets = dateFormat.format(date); maxSelectionWidthMinutes = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime); if (realTimeMode && !userHasChangedScale) { selectionWidthMinutes = maxSelectionWidthMinutes; } else { if (selectionWidthMinutes > maxSelectionWidthMinutes || selectionWidthMinutes < .0001) { if (logger.isLoggable(Level.FINE)) { logger.fine("resetting selectionWidthMinutes to max (time bounds property change), was " + selectionWidthMinutes + ", now " + maxSelectionWidthMinutes); } selectionWidthMinutes = maxSelectionWidthMinutes; } } finalizeProjection(); updateTimeline(); doPrepare(); repaint(); } /** * Treat mouse wheel rotations like slider-handle drags. * * @param rot The number of rotation clicks (positive for zoom in, negative * for zoom out). */ public void adjustZoomFromMouseWheel(int rot) { Projection projection = getProjection(); if (projection == null) { return; // Huhn? } setUserHasChangedScale(true); // Determine the effect of growing / shrinking the slider scale by 'rot' // pixels // So given current selection width (in minutes) and minutes-per-pixel, // just // apply rot as a delta Point2D minutesPnt0 = projection.inverse(0, 0); Point2D minutesPnt1 = projection.inverse(1, 0); double minutesPerPixel = minutesPnt1.getX() - minutesPnt0.getX(); double minSelectionWidthMinutes = minutesPerPixel * sliderPointHalfWidth * 2; double selectionWidthPixels = selectionWidthMinutes / minutesPerPixel; double multiplier = selectionWidthPixels / 40; // Use a multiplier selectionWidthMinutes += rot * minutesPerPixel * multiplier; if (selectionWidthMinutes < minSelectionWidthMinutes) { selectionWidthMinutes = minSelectionWidthMinutes; } if (selectionWidthMinutes > maxSelectionWidthMinutes) { selectionWidthMinutes = maxSelectionWidthMinutes; } updateTimeline(); doPrepare(); } public void addTimeBoundsUserActionsListener(ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { timeBoundsUserActionsListeners.add(timeBoundsUserActionsListener); } public void removeTimeBoundsUserActionsListener(ITimeBoundsUserActionsListener timeBoundsUserActionsListener) { timeBoundsUserActionsListeners.remove(timeBoundsUserActionsListener); } public void clearFixedRenderRange() { for (ITimeBoundsUserActionsListener listener : timeBoundsUserActionsListeners) { listener.clearFixedRenderRange(); } } void setSelectionValid(boolean valid) { zoomToSelection.setEnabled(valid); renderFixedSelection.setEnabled(valid); } }
true
true
public synchronized OMGraphicList getControlWidgetList(Projection proj) { Projection projection = getProjection(); OMGraphicList controlWidgetList = new OMGraphicList(); // triangle indicating center of selection ImageIcon selectionPointImage; DrawingAttributes da = new DrawingAttributes(); da.setFillPaint(TimelineLayer.tint); da.setLinePaint(TimelineLayer.tint); IconPart ip = new BasicIconPart(new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { 10, 90, 90, 10 }, 4), da); selectionPointImage = OMIconFactory.getIcon(32, 32, ip); OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, -5, 6, selectionPointImage, 1.0f); final float selectionPointScale = 1.8f; selectionPoint.setMaxScale(selectionPointScale); selectionPoint.setMinScale(selectionPointScale); controlWidgetList.add(selectionPoint); boundsRectLeftHandle = new OMRect(0, 0, 0, 0); boundsRectLeftHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectLeftHandle); boundsRectRightHandle = new OMRect(0, 0, 0, 0); boundsRectRightHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectRightHandle); int[] xs = new int[8]; int[] ys = new int[8]; contextPoly = new OMPoly(xs, ys); contextPoly.setFillPaint(Color.white); controlWidgetList.add(contextPoly); baseLine = new OMLine(0, 0, 0, 0); baseLine.setLinePaint(Color.BLACK); baseLine.setStroke(new BasicStroke(2)); controlWidgetList.add(baseLine); if (projection == null) { return controlWidgetList; // Huhn? } double screenWidth = projection.getWidth(); float scale = (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); Point2D projCenter = projection.getCenter(); // TODO reconsider proper test here - for the moment, just brute-force // reproject always if (projCenter.getX() > selectionWidthMinutes || scale != projection.getScale()) { double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; projCenter.setLocation(nCenterLon, 0); projection = new Cartesian(projCenter, scale, projection.getWidth(), projection.getHeight()); setProjection(projection); } // Reset primary handle int contextBuffer = (int) (projection.getHeight() * .4); // If 'selectionCenter' is outside current time bounds, first attempt to // recompute from currentTime if (selectionCenter * 60.0 * TimeUnit.SECONDS.toMillis(1) > (gameEndTime - gameStartTime) || selectionCenter < 0) { selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); } // And if _that_ fails, just clamp // DFD changed from TimeUnit.MINUTE.toMillis(1) to MILLISECONDS because // Java 5 doesn't have MINUTE if (selectionCenter * TimeUnit.MILLISECONDS.toMillis(60000) > (gameEndTime - gameStartTime)) { selectionCenter = (gameEndTime - gameStartTime) / TimeUnit.MILLISECONDS.toMillis(60000); } if (selectionCenter < 0) { selectionCenter = 0; } int x = (int) projection.forward(0, selectionCenter).getX(); // Reset bounds and handles Point2D sliderEndPoint = projection.forward(0, selectionWidthMinutes); Point2D origin = projection.forward(0, 0); int selectionHalfWidth = (int) ((sliderEndPoint.getX() - origin.getX()) / 2); int north = contextBuffer; int west = x - selectionHalfWidth; int south = projection.getHeight() - 1; int east = x + selectionHalfWidth; int mid = contextBuffer + 1 + (south - contextBuffer) / 2; if (logger.isLoggable(Level.FINE)) { logger.fine("selectionCenter:" + selectionCenter + ", selectionWidthMinutes:" + selectionWidthMinutes + ", x:" + x + ", origin:" + origin); logger.fine(" projection:" + projection); } selectionPoint.setLon((float) selectionCenter); selectionPoint.generate(projection); // and the two handles for the bounds int handleWest = west - sliderPointHalfWidth; int handleEast = west + sliderPointHalfWidth; final int sliderPointHalfHeight = 2; boundsRectLeftHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectLeftHandle.generate(projection); handleWest = east - sliderPointHalfWidth; handleEast = east + sliderPointHalfWidth; boundsRectRightHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectRightHandle.generate(projection); // and the context lines, that show how the current selection maps to // the timeline above xs = contextPoly.getXs(); ys = contextPoly.getYs(); xs[0] = 0; ys[0] = -1; xs[1] = 0; ys[1] = north; xs[2] = west; ys[2] = north; xs[3] = west; ys[3] = south; xs[4] = east; ys[4] = south; xs[5] = east; ys[5] = north; xs[6] = projection.getWidth() - 1; ys[6] = north; xs[7] = projection.getWidth() - 1; ys[7] = -1; contextPoly.generate(projection); baseLine.setPts(new int[] { 0, mid, projection.getWidth(), mid }); baseLine.generate(projection); return controlWidgetList; }
public synchronized OMGraphicList getControlWidgetList(Projection proj) { Projection projection = getProjection(); OMGraphicList controlWidgetList = new OMGraphicList(); // triangle indicating center of selection ImageIcon selectionPointImage; DrawingAttributes da = new DrawingAttributes(); da.setFillPaint(TimelineLayer.tint); da.setLinePaint(TimelineLayer.tint); IconPart ip = new BasicIconPart(new Polygon(new int[] { 50, 90, 10, 50 }, new int[] { 10, 90, 90, 10 }, 4), da); selectionPointImage = OMIconFactory.getIcon(32, 32, ip); OMScalingIcon selectionPoint = new OMScalingIcon(0f, 0f, 0, 6, selectionPointImage, 1.0f); final float selectionPointScale = 1.8f; selectionPoint.setMaxScale(selectionPointScale); selectionPoint.setMinScale(selectionPointScale); controlWidgetList.add(selectionPoint); boundsRectLeftHandle = new OMRect(0, 0, 0, 0); boundsRectLeftHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectLeftHandle); boundsRectRightHandle = new OMRect(0, 0, 0, 0); boundsRectRightHandle.setFillPaint(Color.black); controlWidgetList.add(boundsRectRightHandle); int[] xs = new int[8]; int[] ys = new int[8]; contextPoly = new OMPoly(xs, ys); contextPoly.setFillPaint(Color.white); controlWidgetList.add(contextPoly); baseLine = new OMLine(0, 0, 0, 0); baseLine.setLinePaint(Color.BLACK); baseLine.setStroke(new BasicStroke(2)); controlWidgetList.add(baseLine); if (projection == null) { return controlWidgetList; // Huhn? } double screenWidth = projection.getWidth(); float scale = (float) (magicScaleFactor * (double) TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / screenWidth); Point2D projCenter = projection.getCenter(); // TODO reconsider proper test here - for the moment, just brute-force // reproject always if (projCenter.getX() > selectionWidthMinutes || scale != projection.getScale()) { double nCenterLon = TimelineLayer.forwardProjectMillis(gameEndTime - gameStartTime) / 2f; projCenter.setLocation(nCenterLon, 0); projection = new Cartesian(projCenter, scale, projection.getWidth(), projection.getHeight()); setProjection(projection); } // Reset primary handle int contextBuffer = (int) (projection.getHeight() * .4); // If 'selectionCenter' is outside current time bounds, first attempt to // recompute from currentTime if (selectionCenter * 60.0 * TimeUnit.SECONDS.toMillis(1) > (gameEndTime - gameStartTime) || selectionCenter < 0) { selectionCenter = TimelineLayer.forwardProjectMillis(currentTime); } // And if _that_ fails, just clamp // DFD changed from TimeUnit.MINUTE.toMillis(1) to MILLISECONDS because // Java 5 doesn't have MINUTE if (selectionCenter * TimeUnit.MILLISECONDS.toMillis(60000) > (gameEndTime - gameStartTime)) { selectionCenter = (gameEndTime - gameStartTime) / TimeUnit.MILLISECONDS.toMillis(60000); } if (selectionCenter < 0) { selectionCenter = 0; } int x = (int) projection.forward(0, selectionCenter).getX(); // Reset bounds and handles Point2D sliderEndPoint = projection.forward(0, selectionWidthMinutes); Point2D origin = projection.forward(0, 0); int selectionHalfWidth = (int) ((sliderEndPoint.getX() - origin.getX()) / 2); int north = contextBuffer; int west = x - selectionHalfWidth; int south = projection.getHeight() - 1; int east = x + selectionHalfWidth; int mid = contextBuffer + 1 + (south - contextBuffer) / 2; if (logger.isLoggable(Level.FINE)) { logger.fine("selectionCenter:" + selectionCenter + ", selectionWidthMinutes:" + selectionWidthMinutes + ", x:" + x + ", origin:" + origin); logger.fine(" projection:" + projection); } selectionPoint.setLon((float) selectionCenter); selectionPoint.generate(projection); // and the two handles for the bounds int handleWest = west - sliderPointHalfWidth; int handleEast = west + sliderPointHalfWidth; final int sliderPointHalfHeight = 2; boundsRectLeftHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectLeftHandle.generate(projection); handleWest = east - sliderPointHalfWidth; handleEast = east + sliderPointHalfWidth; boundsRectRightHandle.setLocation(handleWest, north + sliderPointHalfHeight, handleEast, south - sliderPointHalfHeight); boundsRectRightHandle.generate(projection); // and the context lines, that show how the current selection maps to // the timeline above xs = contextPoly.getXs(); ys = contextPoly.getYs(); xs[0] = 0; ys[0] = -1; xs[1] = 0; ys[1] = north; xs[2] = west; ys[2] = north; xs[3] = west; ys[3] = south; xs[4] = east; ys[4] = south; xs[5] = east; ys[5] = north; xs[6] = projection.getWidth() - 1; ys[6] = north; xs[7] = projection.getWidth() - 1; ys[7] = -1; contextPoly.generate(projection); baseLine.setPts(new int[] { 0, mid, projection.getWidth(), mid }); baseLine.generate(projection); return controlWidgetList; }
diff --git a/src/com/zavteam/plugins/Commands.java b/src/com/zavteam/plugins/Commands.java index 468c1b4..16fa46b 100644 --- a/src/com/zavteam/plugins/Commands.java +++ b/src/com/zavteam/plugins/Commands.java @@ -1,282 +1,282 @@ package com.zavteam.plugins; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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.util.ChatPaginator; import com.zavteam.plugins.messageshandler.MessagesHandler; public class Commands implements CommandExecutor { private final static String noPerm = ChatColor.RED + "You do not have permission to do this."; public ZavAutoMessager plugin; public Commands(ZavAutoMessager instance) { plugin = instance; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String freeVariable; if (args.length == 0 || args[0].equalsIgnoreCase("help")) { if (sender.hasPermission("zavautomessager.view")) { if (args.length == 1 || args.length == 0) { MessagesHandler.listHelpPage(1, sender); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You need to enter a valid page number to do this."); } if (Integer.parseInt(args[1]) > 0 && Integer.parseInt(args[1]) < 4) { MessagesHandler.listHelpPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(ChatColor.RED + "That is not a valid page number"); } } } else { sender.sendMessage(noPerm); } } else if (args.length >= 1) { if (args[0].equalsIgnoreCase("reload")) { if (sender.hasPermission("zavautomessager.reload")) { plugin.messageIt = 0; plugin.mainConfig.saveConfig(); plugin.ignoreConfig.saveConfig(); plugin.autoReload(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager's config has been reloaded."); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("on")) { if (sender.hasPermission("zavautomessager.toggle")) { if ((Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already enabled"); } else { plugin.mainConfig.set("enabled", true); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now on"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("off")) { if (sender.hasPermission("zavautomessager.toggle")) { if (!(Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already disabled"); } else { plugin.mainConfig.set("enabled", false); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now off"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("add")) { if (sender.hasPermission("zavautomessager.add")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a chat message to add."); } else { freeVariable = ""; for (int i = 1; i < args.length; i++) { freeVariable = freeVariable + args[i] + " "; } freeVariable = freeVariable.trim(); plugin.messageIt = 0; plugin.MessagesHandler.addMessage(freeVariable); sender.sendMessage(ChatColor.GREEN + "Your message has been added to the message list."); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("ignore")) { if (sender instanceof Player) { if (sender.hasPermission("zavautomessager.ignore")) { List<String> ignorePlayers = new ArrayList<String>(); ignorePlayers = plugin.ignoreConfig.getConfig().getStringList("players"); if (ignorePlayers.contains(sender.getName())) { ignorePlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer ignoring automatic messages"); } else { ignorePlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now ignoring automatic messages"); } plugin.ignoreConfig.set("players", ignorePlayers); plugin.ignoreConfig.saveConfig(); } else { sender.sendMessage(noPerm); } } else { ZavAutoMessager.log.info("The console cannot use this command."); } } else if (args[0].equalsIgnoreCase("broadcast")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); cutBroadcastList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cutBroadcastList[0]); cutBroadcastList[0] = cutBroadcastList[0].replace("&", "\u00A7"); - cutBroadcastList = ChatPaginator.wordWrap(cutBroadcastList[0], 53); + cutBroadcastList = ChatPaginator.paginate(cutBroadcastList[0], 1).getLines(); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("about")) { if (sender.hasPermission("zavautomessager.about")) { sender.sendMessage(ChatColor.GOLD + "You are currently running ZavAutoMessage Version " + plugin.getDescription().getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "The latest version is currently version " + plugin.VersionConfig.getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "This plugin was developed by the ZavCodingTeam."); sender.sendMessage(ChatColor.GOLD + "Please visit our Bukkit Dev Page for complete details on this plugin."); sender.sendMessage(ChatColor.GOLD + "http://dev.bukkit.org/server-mods/zavautomessager/"); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("remove")) { if (sender.hasPermission("zavautomessager.remove")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a message number to delete."); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You have to enter a round number to remove."); return false; } if (Integer.parseInt(args[1]) < 0 || Integer.parseInt(args[1]) > plugin.messages.size() || plugin.messages.size() == 1) { sender.sendMessage(ChatColor.RED + "This is not a valid message number"); sender.sendMessage(ChatColor.RED + "Use /automessager list for a list of messages"); } else { plugin.messages.remove(Integer.parseInt(args[1]) - 1); sender.sendMessage(ChatColor.GREEN + "Your message has been removed."); Map<String, List<String>> list = new HashMap<String, List<String>>(); for (ChatMessage cm : plugin.messages) { if (list.containsKey(cm.getPermission())) { list.get(cm.getPermission()).add(cm.getMessage()); } else { List<String> mList = new ArrayList<String>(); mList.add(cm.getMessage()); list.put(cm.getPermission(), mList); } } plugin.mainConfig.set("messages", list); plugin.mainConfig.saveConfig(); plugin.messageIt = 0; plugin.autoReload(); } } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("list")) { if (sender.hasPermission("zavautomessager.list")) { if (args.length < 2) { plugin.MessagesHandler.listPage(1, sender); return true; } try { plugin.messages.get((5 * Integer.parseInt(args[1])) - 5); } catch (IndexOutOfBoundsException e) { sender.sendMessage(ChatColor.RED + "You do not have that any messages on that page"); return false; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "You have to enter an invalid number to show help page."); return false; } plugin.MessagesHandler.listPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("set")) { if (sender.hasPermission("zavautomessager.set")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "A minimum of two parameters are required to set any configuration section."); return false; } if (ConfigSection.contains(args[1].toUpperCase())) { Boolean b = false; switch (ConfigSection.valueOf(args[1].toUpperCase())) { case DONTREPEATRANDOMMESSAGES:// Intentional fallthrough since all are pretty much the same case ENABLED: case MESSAGEINRANDOMORDER: case MESSAGESINCONSOLE: case PERMISSIONSENABLED: case REQUIREPLAYERSONLINE: case UPDATECHECKING: case WORDWRAP: try { plugin.mainConfig.set(args[1].toLowerCase(), Boolean.parseBoolean(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of boolean (true or false)."); } break; case DELAY: try { plugin.mainConfig.set(args[1].toLowerCase(), Integer.parseInt(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of Integer."); } break; default: break; } if (b) { sender.sendMessage(ChatColor.GOLD + args[1] + " has been set to " + args[2] + "."); } plugin.mainConfig.saveConfig(); plugin.ignoreConfig.saveConfig(); plugin.autoReload(); return true; } else if (args[1].equalsIgnoreCase("list")) { String s = ""; for (ConfigSection cs : ConfigSection.values()) { s = s + " " + cs.name().toLowerCase(); } s = s + "."; s = s.trim(); sender.sendMessage(ChatColor.GOLD + "Config Sections: " + s); } else { sender.sendMessage(ChatColor.RED + "That is an invalid configuration section"); return false; } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("raw")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } }else { sender.sendMessage(ChatColor.RED + "ZavAutoMessager did not recognize this command."); sender.sendMessage(ChatColor.RED + "Use /automessager help to get a list of commands!"); } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String freeVariable; if (args.length == 0 || args[0].equalsIgnoreCase("help")) { if (sender.hasPermission("zavautomessager.view")) { if (args.length == 1 || args.length == 0) { MessagesHandler.listHelpPage(1, sender); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You need to enter a valid page number to do this."); } if (Integer.parseInt(args[1]) > 0 && Integer.parseInt(args[1]) < 4) { MessagesHandler.listHelpPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(ChatColor.RED + "That is not a valid page number"); } } } else { sender.sendMessage(noPerm); } } else if (args.length >= 1) { if (args[0].equalsIgnoreCase("reload")) { if (sender.hasPermission("zavautomessager.reload")) { plugin.messageIt = 0; plugin.mainConfig.saveConfig(); plugin.ignoreConfig.saveConfig(); plugin.autoReload(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager's config has been reloaded."); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("on")) { if (sender.hasPermission("zavautomessager.toggle")) { if ((Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already enabled"); } else { plugin.mainConfig.set("enabled", true); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now on"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("off")) { if (sender.hasPermission("zavautomessager.toggle")) { if (!(Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already disabled"); } else { plugin.mainConfig.set("enabled", false); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now off"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("add")) { if (sender.hasPermission("zavautomessager.add")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a chat message to add."); } else { freeVariable = ""; for (int i = 1; i < args.length; i++) { freeVariable = freeVariable + args[i] + " "; } freeVariable = freeVariable.trim(); plugin.messageIt = 0; plugin.MessagesHandler.addMessage(freeVariable); sender.sendMessage(ChatColor.GREEN + "Your message has been added to the message list."); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("ignore")) { if (sender instanceof Player) { if (sender.hasPermission("zavautomessager.ignore")) { List<String> ignorePlayers = new ArrayList<String>(); ignorePlayers = plugin.ignoreConfig.getConfig().getStringList("players"); if (ignorePlayers.contains(sender.getName())) { ignorePlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer ignoring automatic messages"); } else { ignorePlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now ignoring automatic messages"); } plugin.ignoreConfig.set("players", ignorePlayers); plugin.ignoreConfig.saveConfig(); } else { sender.sendMessage(noPerm); } } else { ZavAutoMessager.log.info("The console cannot use this command."); } } else if (args[0].equalsIgnoreCase("broadcast")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); cutBroadcastList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cutBroadcastList[0]); cutBroadcastList[0] = cutBroadcastList[0].replace("&", "\u00A7"); cutBroadcastList = ChatPaginator.wordWrap(cutBroadcastList[0], 53); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("about")) { if (sender.hasPermission("zavautomessager.about")) { sender.sendMessage(ChatColor.GOLD + "You are currently running ZavAutoMessage Version " + plugin.getDescription().getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "The latest version is currently version " + plugin.VersionConfig.getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "This plugin was developed by the ZavCodingTeam."); sender.sendMessage(ChatColor.GOLD + "Please visit our Bukkit Dev Page for complete details on this plugin."); sender.sendMessage(ChatColor.GOLD + "http://dev.bukkit.org/server-mods/zavautomessager/"); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("remove")) { if (sender.hasPermission("zavautomessager.remove")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a message number to delete."); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You have to enter a round number to remove."); return false; } if (Integer.parseInt(args[1]) < 0 || Integer.parseInt(args[1]) > plugin.messages.size() || plugin.messages.size() == 1) { sender.sendMessage(ChatColor.RED + "This is not a valid message number"); sender.sendMessage(ChatColor.RED + "Use /automessager list for a list of messages"); } else { plugin.messages.remove(Integer.parseInt(args[1]) - 1); sender.sendMessage(ChatColor.GREEN + "Your message has been removed."); Map<String, List<String>> list = new HashMap<String, List<String>>(); for (ChatMessage cm : plugin.messages) { if (list.containsKey(cm.getPermission())) { list.get(cm.getPermission()).add(cm.getMessage()); } else { List<String> mList = new ArrayList<String>(); mList.add(cm.getMessage()); list.put(cm.getPermission(), mList); } } plugin.mainConfig.set("messages", list); plugin.mainConfig.saveConfig(); plugin.messageIt = 0; plugin.autoReload(); } } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("list")) { if (sender.hasPermission("zavautomessager.list")) { if (args.length < 2) { plugin.MessagesHandler.listPage(1, sender); return true; } try { plugin.messages.get((5 * Integer.parseInt(args[1])) - 5); } catch (IndexOutOfBoundsException e) { sender.sendMessage(ChatColor.RED + "You do not have that any messages on that page"); return false; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "You have to enter an invalid number to show help page."); return false; } plugin.MessagesHandler.listPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("set")) { if (sender.hasPermission("zavautomessager.set")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "A minimum of two parameters are required to set any configuration section."); return false; } if (ConfigSection.contains(args[1].toUpperCase())) { Boolean b = false; switch (ConfigSection.valueOf(args[1].toUpperCase())) { case DONTREPEATRANDOMMESSAGES:// Intentional fallthrough since all are pretty much the same case ENABLED: case MESSAGEINRANDOMORDER: case MESSAGESINCONSOLE: case PERMISSIONSENABLED: case REQUIREPLAYERSONLINE: case UPDATECHECKING: case WORDWRAP: try { plugin.mainConfig.set(args[1].toLowerCase(), Boolean.parseBoolean(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of boolean (true or false)."); } break; case DELAY: try { plugin.mainConfig.set(args[1].toLowerCase(), Integer.parseInt(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of Integer."); } break; default: break; } if (b) { sender.sendMessage(ChatColor.GOLD + args[1] + " has been set to " + args[2] + "."); } plugin.mainConfig.saveConfig(); plugin.ignoreConfig.saveConfig(); plugin.autoReload(); return true; } else if (args[1].equalsIgnoreCase("list")) { String s = ""; for (ConfigSection cs : ConfigSection.values()) { s = s + " " + cs.name().toLowerCase(); } s = s + "."; s = s.trim(); sender.sendMessage(ChatColor.GOLD + "Config Sections: " + s); } else { sender.sendMessage(ChatColor.RED + "That is an invalid configuration section"); return false; } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("raw")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } }else { sender.sendMessage(ChatColor.RED + "ZavAutoMessager did not recognize this command."); sender.sendMessage(ChatColor.RED + "Use /automessager help to get a list of commands!"); } } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String freeVariable; if (args.length == 0 || args[0].equalsIgnoreCase("help")) { if (sender.hasPermission("zavautomessager.view")) { if (args.length == 1 || args.length == 0) { MessagesHandler.listHelpPage(1, sender); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You need to enter a valid page number to do this."); } if (Integer.parseInt(args[1]) > 0 && Integer.parseInt(args[1]) < 4) { MessagesHandler.listHelpPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(ChatColor.RED + "That is not a valid page number"); } } } else { sender.sendMessage(noPerm); } } else if (args.length >= 1) { if (args[0].equalsIgnoreCase("reload")) { if (sender.hasPermission("zavautomessager.reload")) { plugin.messageIt = 0; plugin.mainConfig.saveConfig(); plugin.ignoreConfig.saveConfig(); plugin.autoReload(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager's config has been reloaded."); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("on")) { if (sender.hasPermission("zavautomessager.toggle")) { if ((Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already enabled"); } else { plugin.mainConfig.set("enabled", true); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now on"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("off")) { if (sender.hasPermission("zavautomessager.toggle")) { if (!(Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already disabled"); } else { plugin.mainConfig.set("enabled", false); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now off"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("add")) { if (sender.hasPermission("zavautomessager.add")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a chat message to add."); } else { freeVariable = ""; for (int i = 1; i < args.length; i++) { freeVariable = freeVariable + args[i] + " "; } freeVariable = freeVariable.trim(); plugin.messageIt = 0; plugin.MessagesHandler.addMessage(freeVariable); sender.sendMessage(ChatColor.GREEN + "Your message has been added to the message list."); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("ignore")) { if (sender instanceof Player) { if (sender.hasPermission("zavautomessager.ignore")) { List<String> ignorePlayers = new ArrayList<String>(); ignorePlayers = plugin.ignoreConfig.getConfig().getStringList("players"); if (ignorePlayers.contains(sender.getName())) { ignorePlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer ignoring automatic messages"); } else { ignorePlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now ignoring automatic messages"); } plugin.ignoreConfig.set("players", ignorePlayers); plugin.ignoreConfig.saveConfig(); } else { sender.sendMessage(noPerm); } } else { ZavAutoMessager.log.info("The console cannot use this command."); } } else if (args[0].equalsIgnoreCase("broadcast")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); cutBroadcastList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cutBroadcastList[0]); cutBroadcastList[0] = cutBroadcastList[0].replace("&", "\u00A7"); cutBroadcastList = ChatPaginator.paginate(cutBroadcastList[0], 1).getLines(); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("about")) { if (sender.hasPermission("zavautomessager.about")) { sender.sendMessage(ChatColor.GOLD + "You are currently running ZavAutoMessage Version " + plugin.getDescription().getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "The latest version is currently version " + plugin.VersionConfig.getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "This plugin was developed by the ZavCodingTeam."); sender.sendMessage(ChatColor.GOLD + "Please visit our Bukkit Dev Page for complete details on this plugin."); sender.sendMessage(ChatColor.GOLD + "http://dev.bukkit.org/server-mods/zavautomessager/"); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("remove")) { if (sender.hasPermission("zavautomessager.remove")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a message number to delete."); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You have to enter a round number to remove."); return false; } if (Integer.parseInt(args[1]) < 0 || Integer.parseInt(args[1]) > plugin.messages.size() || plugin.messages.size() == 1) { sender.sendMessage(ChatColor.RED + "This is not a valid message number"); sender.sendMessage(ChatColor.RED + "Use /automessager list for a list of messages"); } else { plugin.messages.remove(Integer.parseInt(args[1]) - 1); sender.sendMessage(ChatColor.GREEN + "Your message has been removed."); Map<String, List<String>> list = new HashMap<String, List<String>>(); for (ChatMessage cm : plugin.messages) { if (list.containsKey(cm.getPermission())) { list.get(cm.getPermission()).add(cm.getMessage()); } else { List<String> mList = new ArrayList<String>(); mList.add(cm.getMessage()); list.put(cm.getPermission(), mList); } } plugin.mainConfig.set("messages", list); plugin.mainConfig.saveConfig(); plugin.messageIt = 0; plugin.autoReload(); } } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("list")) { if (sender.hasPermission("zavautomessager.list")) { if (args.length < 2) { plugin.MessagesHandler.listPage(1, sender); return true; } try { plugin.messages.get((5 * Integer.parseInt(args[1])) - 5); } catch (IndexOutOfBoundsException e) { sender.sendMessage(ChatColor.RED + "You do not have that any messages on that page"); return false; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "You have to enter an invalid number to show help page."); return false; } plugin.MessagesHandler.listPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("set")) { if (sender.hasPermission("zavautomessager.set")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "A minimum of two parameters are required to set any configuration section."); return false; } if (ConfigSection.contains(args[1].toUpperCase())) { Boolean b = false; switch (ConfigSection.valueOf(args[1].toUpperCase())) { case DONTREPEATRANDOMMESSAGES:// Intentional fallthrough since all are pretty much the same case ENABLED: case MESSAGEINRANDOMORDER: case MESSAGESINCONSOLE: case PERMISSIONSENABLED: case REQUIREPLAYERSONLINE: case UPDATECHECKING: case WORDWRAP: try { plugin.mainConfig.set(args[1].toLowerCase(), Boolean.parseBoolean(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of boolean (true or false)."); } break; case DELAY: try { plugin.mainConfig.set(args[1].toLowerCase(), Integer.parseInt(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of Integer."); } break; default: break; } if (b) { sender.sendMessage(ChatColor.GOLD + args[1] + " has been set to " + args[2] + "."); } plugin.mainConfig.saveConfig(); plugin.ignoreConfig.saveConfig(); plugin.autoReload(); return true; } else if (args[1].equalsIgnoreCase("list")) { String s = ""; for (ConfigSection cs : ConfigSection.values()) { s = s + " " + cs.name().toLowerCase(); } s = s + "."; s = s.trim(); sender.sendMessage(ChatColor.GOLD + "Config Sections: " + s); } else { sender.sendMessage(ChatColor.RED + "That is an invalid configuration section"); return false; } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("raw")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } }else { sender.sendMessage(ChatColor.RED + "ZavAutoMessager did not recognize this command."); sender.sendMessage(ChatColor.RED + "Use /automessager help to get a list of commands!"); } } return false; }
diff --git a/core/java/src/net/i2p/client/SessionIdleTimer.java b/core/java/src/net/i2p/client/SessionIdleTimer.java index 354a2b633..f4661b73b 100644 --- a/core/java/src/net/i2p/client/SessionIdleTimer.java +++ b/core/java/src/net/i2p/client/SessionIdleTimer.java @@ -1,117 +1,117 @@ package net.i2p.client; /* * free (adj.): unencumbered; not under the control of others * */ import java.util.Properties; import net.i2p.I2PAppContext; import net.i2p.data.DataHelper; import net.i2p.util.Log; import net.i2p.util.SimpleScheduler; import net.i2p.util.SimpleTimer; /** * Reduce tunnels or shutdown the session on idle if so configured * * @author zzz */ public class SessionIdleTimer implements SimpleTimer.TimedEvent { public static final long MINIMUM_TIME = 5*60*1000; private static final long DEFAULT_REDUCE_TIME = 20*60*1000; private static final long DEFAULT_CLOSE_TIME = 30*60*1000; private final static Log _log = new Log(SessionIdleTimer.class); private I2PAppContext _context; private I2PSessionImpl _session; private boolean _reduceEnabled; private int _reduceQuantity; private long _reduceTime; private boolean _shutdownEnabled; private long _shutdownTime; private long _minimumTime; private long _lastActive; /** * reduce, shutdown, or both must be true */ public SessionIdleTimer(I2PAppContext context, I2PSessionImpl session, boolean reduce, boolean shutdown) { _context = context; _session = session; _reduceEnabled = reduce; _shutdownEnabled = shutdown; if (! (reduce || shutdown)) throw new IllegalArgumentException("At least one must be enabled"); Properties props = session.getOptions(); _minimumTime = Long.MAX_VALUE; _lastActive = 0; if (reduce) { _reduceQuantity = 1; String p = props.getProperty("i2cp.reduceQuantity"); if (p != null) { try { _reduceQuantity = Math.max(Integer.parseInt(p), 1); // also check vs. configured quantities? } catch (NumberFormatException nfe) {} } _reduceTime = DEFAULT_REDUCE_TIME; - p = props.getProperty("i2cp.reduceTime"); + p = props.getProperty("i2cp.reduceIdleTime"); if (p != null) { try { _reduceTime = Math.max(Long.parseLong(p), MINIMUM_TIME); } catch (NumberFormatException nfe) {} } _minimumTime = _reduceTime; } if (shutdown) { _shutdownTime = DEFAULT_CLOSE_TIME; - String p = props.getProperty("i2cp.closeTime"); + String p = props.getProperty("i2cp.closeIdleTime"); if (p != null) { try { _shutdownTime = Math.max(Long.parseLong(p), MINIMUM_TIME); } catch (NumberFormatException nfe) {} } _minimumTime = Math.min(_minimumTime, _shutdownTime); if (reduce && _shutdownTime <= _reduceTime) reduce = false; } } public void timeReached() { if (_session.isClosed()) return; long now = _context.clock().now(); long lastActivity = _session.lastActivity(); if (_log.shouldLog(Log.INFO)) _log.info("Fire idle timer, last activity: " + DataHelper.formatDuration(now - lastActivity) + " ago "); long nextDelay = 0; if (_shutdownEnabled && now - lastActivity >= _shutdownTime) { if (_log.shouldLog(Log.WARN)) _log.warn("Closing on idle " + _session); _session.destroySession(); return; } else if (lastActivity <= _lastActive && !_shutdownEnabled) { if (_log.shouldLog(Log.WARN)) _log.warn("Still idle, sleeping again " + _session); nextDelay = _reduceTime; } else if (_reduceEnabled && now - lastActivity >= _reduceTime) { if (_log.shouldLog(Log.WARN)) _log.warn("Reducing quantity on idle " + _session); try { _session.getProducer().updateTunnels(_session, _reduceQuantity); } catch (I2PSessionException ise) { _log.error("bork idle reduction " + ise); } _session.setReduced(); _lastActive = lastActivity; if (_shutdownEnabled) nextDelay = _shutdownTime - (now - lastActivity); else nextDelay = _reduceTime; } else { nextDelay = _minimumTime - (now - lastActivity); } SimpleScheduler.getInstance().addEvent(this, nextDelay); } }
false
true
public SessionIdleTimer(I2PAppContext context, I2PSessionImpl session, boolean reduce, boolean shutdown) { _context = context; _session = session; _reduceEnabled = reduce; _shutdownEnabled = shutdown; if (! (reduce || shutdown)) throw new IllegalArgumentException("At least one must be enabled"); Properties props = session.getOptions(); _minimumTime = Long.MAX_VALUE; _lastActive = 0; if (reduce) { _reduceQuantity = 1; String p = props.getProperty("i2cp.reduceQuantity"); if (p != null) { try { _reduceQuantity = Math.max(Integer.parseInt(p), 1); // also check vs. configured quantities? } catch (NumberFormatException nfe) {} } _reduceTime = DEFAULT_REDUCE_TIME; p = props.getProperty("i2cp.reduceTime"); if (p != null) { try { _reduceTime = Math.max(Long.parseLong(p), MINIMUM_TIME); } catch (NumberFormatException nfe) {} } _minimumTime = _reduceTime; } if (shutdown) { _shutdownTime = DEFAULT_CLOSE_TIME; String p = props.getProperty("i2cp.closeTime"); if (p != null) { try { _shutdownTime = Math.max(Long.parseLong(p), MINIMUM_TIME); } catch (NumberFormatException nfe) {} } _minimumTime = Math.min(_minimumTime, _shutdownTime); if (reduce && _shutdownTime <= _reduceTime) reduce = false; } }
public SessionIdleTimer(I2PAppContext context, I2PSessionImpl session, boolean reduce, boolean shutdown) { _context = context; _session = session; _reduceEnabled = reduce; _shutdownEnabled = shutdown; if (! (reduce || shutdown)) throw new IllegalArgumentException("At least one must be enabled"); Properties props = session.getOptions(); _minimumTime = Long.MAX_VALUE; _lastActive = 0; if (reduce) { _reduceQuantity = 1; String p = props.getProperty("i2cp.reduceQuantity"); if (p != null) { try { _reduceQuantity = Math.max(Integer.parseInt(p), 1); // also check vs. configured quantities? } catch (NumberFormatException nfe) {} } _reduceTime = DEFAULT_REDUCE_TIME; p = props.getProperty("i2cp.reduceIdleTime"); if (p != null) { try { _reduceTime = Math.max(Long.parseLong(p), MINIMUM_TIME); } catch (NumberFormatException nfe) {} } _minimumTime = _reduceTime; } if (shutdown) { _shutdownTime = DEFAULT_CLOSE_TIME; String p = props.getProperty("i2cp.closeIdleTime"); if (p != null) { try { _shutdownTime = Math.max(Long.parseLong(p), MINIMUM_TIME); } catch (NumberFormatException nfe) {} } _minimumTime = Math.min(_minimumTime, _shutdownTime); if (reduce && _shutdownTime <= _reduceTime) reduce = false; } }
diff --git a/src/edu/upenn/ircs/lignos/morsel/CorpusLoader.java b/src/edu/upenn/ircs/lignos/morsel/CorpusLoader.java index 3f1c08e..437d81d 100644 --- a/src/edu/upenn/ircs/lignos/morsel/CorpusLoader.java +++ b/src/edu/upenn/ircs/lignos/morsel/CorpusLoader.java @@ -1,120 +1,120 @@ /******************************************************************************* * Copyright (C) 2012 Constantine Lignos * * This file is a part of MORSEL. * * MORSEL 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. * * MORSEL 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 MORSEL. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package edu.upenn.ircs.lignos.morsel; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import edu.upenn.ircs.lignos.morsel.lexicon.Lexicon; import edu.upenn.ircs.lignos.morsel.lexicon.Word; /** * The CorpusLoader class provides static methods for creating a lexicon from * a corpus or wordlist. * */ public class CorpusLoader { /** * Loads a wordlist file into a lexicon, returning null if the file could * not be read. The wordlist should contain one word per line, with any * whitespace between the word and the count. For example, a line could be * as follows: * 500 dog * Warnings are printed to stderr if duplicate words are found in the * wordlist, and status is printed to stdout every 50,000 word types that * are loaded. * @param wordListPath The path to the wordlist file. * @param encoding Encoding of the wordlist file. * @param verbose Whether to print information about the lexicon. * @return A lexicon representing the wordlist. */ public static Lexicon loadWordlist(String wordListPath, String encoding, boolean verbose) { try { Lexicon lex = new Lexicon(); // Open the word list and get each word BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(wordListPath), encoding)); String line; - int typesLoaded = 0; - int tokensLoaded = 0; + long typesLoaded = 0; + long tokensLoaded = 0; while ((line = input.readLine()) != null) { Word word = parseWordlistEntry(line); if (word != null) { // Add the word, print a warning if it's a duplicate if(!lex.addWord(word)) { System.err.println("Warning: Duplicate word in wordlist: " + word.getText()); continue; } // Add the token count tokensLoaded += word.getCount(); // Update status every 50,000 words if (verbose && ++typesLoaded % 50000 == 0) { System.out.print("\r" + typesLoaded + " types loaded..."); } } } //Clean up input.close(); if (verbose) { System.out.println("\r" + typesLoaded + " types loaded."); System.out.println(tokensLoaded + " tokens loaded."); } // Set the word frequencies in the lexicon lex.updateFrequencies(); return lex; } catch (IOException e) { // If the file could not be loaded, just return null for the lexicon return null; } } /** * Parse a string into a word and its count and create a matching Word * instance. Returns null if the string could not be parsed. * @param line The line to be parsed, which should be in the format of * a word, any amount of whitespace, and the count of the word. * @return A Word parsed from the line. */ static Word parseWordlistEntry(String line) { // Parse the line, return null if parsing fails String[] parts = line.split("\\s"); if (parts.length != 2) { return null; } // Parse the second item as a count try { long count = Long.parseLong(parts[0]); return new Word(parts[1], count, true); } catch (NumberFormatException e) { // Return null if the string could not be parsed return null; } } }
true
true
public static Lexicon loadWordlist(String wordListPath, String encoding, boolean verbose) { try { Lexicon lex = new Lexicon(); // Open the word list and get each word BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(wordListPath), encoding)); String line; int typesLoaded = 0; int tokensLoaded = 0; while ((line = input.readLine()) != null) { Word word = parseWordlistEntry(line); if (word != null) { // Add the word, print a warning if it's a duplicate if(!lex.addWord(word)) { System.err.println("Warning: Duplicate word in wordlist: " + word.getText()); continue; } // Add the token count tokensLoaded += word.getCount(); // Update status every 50,000 words if (verbose && ++typesLoaded % 50000 == 0) { System.out.print("\r" + typesLoaded + " types loaded..."); } } } //Clean up input.close(); if (verbose) { System.out.println("\r" + typesLoaded + " types loaded."); System.out.println(tokensLoaded + " tokens loaded."); } // Set the word frequencies in the lexicon lex.updateFrequencies(); return lex; } catch (IOException e) { // If the file could not be loaded, just return null for the lexicon return null; } }
public static Lexicon loadWordlist(String wordListPath, String encoding, boolean verbose) { try { Lexicon lex = new Lexicon(); // Open the word list and get each word BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(wordListPath), encoding)); String line; long typesLoaded = 0; long tokensLoaded = 0; while ((line = input.readLine()) != null) { Word word = parseWordlistEntry(line); if (word != null) { // Add the word, print a warning if it's a duplicate if(!lex.addWord(word)) { System.err.println("Warning: Duplicate word in wordlist: " + word.getText()); continue; } // Add the token count tokensLoaded += word.getCount(); // Update status every 50,000 words if (verbose && ++typesLoaded % 50000 == 0) { System.out.print("\r" + typesLoaded + " types loaded..."); } } } //Clean up input.close(); if (verbose) { System.out.println("\r" + typesLoaded + " types loaded."); System.out.println(tokensLoaded + " tokens loaded."); } // Set the word frequencies in the lexicon lex.updateFrequencies(); return lex; } catch (IOException e) { // If the file could not be loaded, just return null for the lexicon return null; } }
diff --git a/grisu-client-lib-old/src/main/java/org/vpac/grisu/client/model/template/postprocessor/ConvertToBytes.java b/grisu-client-lib-old/src/main/java/org/vpac/grisu/client/model/template/postprocessor/ConvertToBytes.java index 4d4c322..162d15c 100644 --- a/grisu-client-lib-old/src/main/java/org/vpac/grisu/client/model/template/postprocessor/ConvertToBytes.java +++ b/grisu-client-lib-old/src/main/java/org/vpac/grisu/client/model/template/postprocessor/ConvertToBytes.java @@ -1,34 +1,34 @@ package org.vpac.grisu.client.model.template.postprocessor; import org.vpac.grisu.client.model.template.JsdlTemplate; import org.w3c.dom.Element; public class ConvertToBytes extends ElementPostprocessor { public ConvertToBytes(JsdlTemplate template, Element element) { super(template, element); } @Override public void process(String fqan) throws PostProcessException { Integer mb; try { mb = Integer.parseInt(element.getTextContent()); } catch (Exception e) { throw new PostProcessException( "Could not process specified memory.", e); } - Long bytes = new Long(mb * 1024); + Long bytes = new Long(mb * 1024 * 1024); element.setTextContent(bytes.toString()); } @Override public boolean processBeforeJobCreation() { return true; } }
true
true
public void process(String fqan) throws PostProcessException { Integer mb; try { mb = Integer.parseInt(element.getTextContent()); } catch (Exception e) { throw new PostProcessException( "Could not process specified memory.", e); } Long bytes = new Long(mb * 1024); element.setTextContent(bytes.toString()); }
public void process(String fqan) throws PostProcessException { Integer mb; try { mb = Integer.parseInt(element.getTextContent()); } catch (Exception e) { throw new PostProcessException( "Could not process specified memory.", e); } Long bytes = new Long(mb * 1024 * 1024); element.setTextContent(bytes.toString()); }
diff --git a/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/OgmTestCase.java b/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/OgmTestCase.java index 773a4b172..d8bb658b8 100644 --- a/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/OgmTestCase.java +++ b/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/OgmTestCase.java @@ -1,200 +1,200 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2010-2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ogm.test.simpleentity; import java.io.InputStream; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.ogm.cfg.impl.OgmNamingStrategy; import org.hibernate.ogm.datastore.infinispan.impl.CacheManagerServiceProvider; import org.hibernate.ogm.dialect.NoopDialect; import org.hibernate.ogm.jdbc.NoopConnectionProvider; import org.hibernate.ogm.jpa.impl.OgmPersisterClassProvider; import org.hibernate.ogm.metadata.GridMetadataManager; import org.hibernate.ogm.transaction.infinispan.impl.DummyTransactionManagerLookup; import org.hibernate.ogm.transaction.infinispan.impl.JTATransactionManagerTransactionFactory; import org.hibernate.testing.junit.functional.annotations.HibernateTestCase; import org.hibernate.transaction.JBossTSStandaloneTransactionManagerLookup; import static org.fest.assertions.Assertions.assertThat; import static org.hibernate.ogm.test.utils.TestHelper.getAssociationCache; import static org.hibernate.ogm.test.utils.TestHelper.getEntityCache; /** * A base class for all OGM tests. * * @author Emmnauel Bernand * @author Hardy Ferentschik */ public abstract class OgmTestCase extends HibernateTestCase { protected static SessionFactory sessions; private Session session; public OgmTestCase() { super(); } public OgmTestCase(String name) { super( name ); } public Session openSession() throws HibernateException { rebuildSessionFactory(); session = getSessions().openSession(); return session; } public Session openSession(Interceptor interceptor) throws HibernateException { rebuildSessionFactory(); session = getSessions().openSession( interceptor ); return session; } private void rebuildSessionFactory() { if ( sessions == null ) { try { buildConfiguration(); } catch ( Exception e ) { throw new HibernateException( e ); } } } protected void setSessions(SessionFactory sessions) { OgmTestCase.sessions = sessions; } protected SessionFactory getSessions() { return sessions; } protected SessionFactoryImplementor sfi() { return (SessionFactoryImplementor) getSessions(); } //FIXME clear cache when this happens protected void runSchemaGeneration() { } //FIXME clear cache when this happens protected void runSchemaDrop() { } @Override protected void buildConfiguration() throws Exception { if ( getSessions() != null ) { getSessions().close(); } try { setCfg( new Configuration() ); //Grid specific configuration cfg.setProperty( Environment.DIALECT, NoopDialect.class.getName() ); cfg.setProperty( CacheManagerServiceProvider.INFINISPAN_CONFIGURATION_RESOURCENAME, "infinispan-local.xml" ); cfg.setSessionFactoryObserver( new GridMetadataManager() ); cfg.setProperty( Environment.CONNECTION_PROVIDER, NoopConnectionProvider.class.getName() ); cfg.setProperty( "hibernate.transaction.default_factory_class", JTATransactionManagerTransactionFactory.class.getName() ); - cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, DummyTransactionManagerLookup.class.getName() ); + cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, JBossTSStandaloneTransactionManagerLookup.class.getName() ); cfg.setNamingStrategy( OgmNamingStrategy.INSTANCE ); cfg.setPersisterClassProvider( OgmPersisterClassProvider.INSTANCE ); //Other configurations // by default use the new id generator scheme... cfg.setProperty( Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); configure( cfg ); if ( recreateSchema() ) { cfg.setProperty( Environment.HBM2DDL_AUTO, "none" ); } for ( String aPackage : getAnnotatedPackages() ) { getCfg().addPackage( aPackage ); } for ( Class<?> aClass : getAnnotatedClasses() ) { getCfg().addAnnotatedClass( aClass ); } for ( String xmlFile : getXmlFiles() ) { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ); getCfg().addInputStream( is ); } setSessions( getCfg().buildSessionFactory( /* new TestInterceptor() */ ) ); } catch ( Exception e ) { e.printStackTrace(); throw e; } } @Override protected void handleUnclosedResources() { if ( session != null && session.isOpen() ) { if ( session.isConnected() ) { session.doWork( new RollbackWork() ); } session.close(); session = null; fail( "unclosed session" ); } else { session = null; } if ( sessions != null && !sessions.isClosed() ) { sessions.close(); sessions = null; } } @Override protected void closeResources() { try { if ( session != null && session.isOpen() ) { if ( session.isConnected() ) { session.doWork( new RollbackWork() ); } session.close(); } } catch ( Exception ignore ) { } try { if ( sessions != null ) { sessions.close(); sessions = null; } } catch ( Exception ignore ) { } } public void checkCleanCache() { assertThat(getEntityCache( sessions )).as("Entity cache should be empty").hasSize( 0 ); assertThat(getAssociationCache( sessions )).as("Association cache should be empty").hasSize( 0 ); } }
true
true
protected void buildConfiguration() throws Exception { if ( getSessions() != null ) { getSessions().close(); } try { setCfg( new Configuration() ); //Grid specific configuration cfg.setProperty( Environment.DIALECT, NoopDialect.class.getName() ); cfg.setProperty( CacheManagerServiceProvider.INFINISPAN_CONFIGURATION_RESOURCENAME, "infinispan-local.xml" ); cfg.setSessionFactoryObserver( new GridMetadataManager() ); cfg.setProperty( Environment.CONNECTION_PROVIDER, NoopConnectionProvider.class.getName() ); cfg.setProperty( "hibernate.transaction.default_factory_class", JTATransactionManagerTransactionFactory.class.getName() ); cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, DummyTransactionManagerLookup.class.getName() ); cfg.setNamingStrategy( OgmNamingStrategy.INSTANCE ); cfg.setPersisterClassProvider( OgmPersisterClassProvider.INSTANCE ); //Other configurations // by default use the new id generator scheme... cfg.setProperty( Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); configure( cfg ); if ( recreateSchema() ) { cfg.setProperty( Environment.HBM2DDL_AUTO, "none" ); } for ( String aPackage : getAnnotatedPackages() ) { getCfg().addPackage( aPackage ); } for ( Class<?> aClass : getAnnotatedClasses() ) { getCfg().addAnnotatedClass( aClass ); } for ( String xmlFile : getXmlFiles() ) { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ); getCfg().addInputStream( is ); } setSessions( getCfg().buildSessionFactory( /* new TestInterceptor() */ ) ); } catch ( Exception e ) { e.printStackTrace(); throw e; } }
protected void buildConfiguration() throws Exception { if ( getSessions() != null ) { getSessions().close(); } try { setCfg( new Configuration() ); //Grid specific configuration cfg.setProperty( Environment.DIALECT, NoopDialect.class.getName() ); cfg.setProperty( CacheManagerServiceProvider.INFINISPAN_CONFIGURATION_RESOURCENAME, "infinispan-local.xml" ); cfg.setSessionFactoryObserver( new GridMetadataManager() ); cfg.setProperty( Environment.CONNECTION_PROVIDER, NoopConnectionProvider.class.getName() ); cfg.setProperty( "hibernate.transaction.default_factory_class", JTATransactionManagerTransactionFactory.class.getName() ); cfg.setProperty( Environment.TRANSACTION_MANAGER_STRATEGY, JBossTSStandaloneTransactionManagerLookup.class.getName() ); cfg.setNamingStrategy( OgmNamingStrategy.INSTANCE ); cfg.setPersisterClassProvider( OgmPersisterClassProvider.INSTANCE ); //Other configurations // by default use the new id generator scheme... cfg.setProperty( Configuration.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); configure( cfg ); if ( recreateSchema() ) { cfg.setProperty( Environment.HBM2DDL_AUTO, "none" ); } for ( String aPackage : getAnnotatedPackages() ) { getCfg().addPackage( aPackage ); } for ( Class<?> aClass : getAnnotatedClasses() ) { getCfg().addAnnotatedClass( aClass ); } for ( String xmlFile : getXmlFiles() ) { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ); getCfg().addInputStream( is ); } setSessions( getCfg().buildSessionFactory( /* new TestInterceptor() */ ) ); } catch ( Exception e ) { e.printStackTrace(); throw e; } }
diff --git a/v7/appcompat/src/android/support/v7/internal/view/menu/MenuDialogHelper.java b/v7/appcompat/src/android/support/v7/internal/view/menu/MenuDialogHelper.java index 7f433eca4..a6e29a3b0 100644 --- a/v7/appcompat/src/android/support/v7/internal/view/menu/MenuDialogHelper.java +++ b/v7/appcompat/src/android/support/v7/internal/view/menu/MenuDialogHelper.java @@ -1,172 +1,172 @@ /* * Copyright (C) 2013 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 android.support.v7.internal.view.menu; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.IBinder; import android.support.v7.appcompat.R; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; /** * Helper for menus that appear as Dialogs (context and submenus). * * @hide */ public class MenuDialogHelper implements DialogInterface.OnKeyListener, DialogInterface.OnClickListener, DialogInterface.OnDismissListener, MenuPresenter.Callback { private MenuBuilder mMenu; private AlertDialog mDialog; ListMenuPresenter mPresenter; private MenuPresenter.Callback mPresenterCallback; public MenuDialogHelper(MenuBuilder menu) { mMenu = menu; } /** * Shows menu as a dialog. * * @param windowToken Optional token to assign to the window. */ public void show(IBinder windowToken) { // Many references to mMenu, create local reference final MenuBuilder menu = mMenu; // Get the builder for the dialog final AlertDialog.Builder builder = new AlertDialog.Builder(menu.getContext()); // Need to force Light Menu theme as list_menu_item_layout is usually against a dark bg and // AlertDialog's bg is white mPresenter = new ListMenuPresenter(R.layout.list_menu_item_layout, - R.style.Theme_AppCompat_Light_CompactMenu); + R.style.Theme_AppCompat_CompactMenu_Dialog); mPresenter.setCallback(this); mMenu.addMenuPresenter(mPresenter); builder.setAdapter(mPresenter.getAdapter(), this); // Set the title final View headerView = menu.getHeaderView(); if (headerView != null) { // Menu's client has given a custom header view, use it builder.setCustomTitle(headerView); } else { // Otherwise use the (text) title and icon builder.setIcon(menu.getHeaderIcon()).setTitle(menu.getHeaderTitle()); } // Set the key listener builder.setOnKeyListener(this); // Show the menu mDialog = builder.create(); mDialog.setOnDismissListener(this); WindowManager.LayoutParams lp = mDialog.getWindow().getAttributes(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; if (windowToken != null) { lp.token = windowToken; } lp.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; mDialog.show(); } public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_BACK) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { Window win = mDialog.getWindow(); if (win != null) { View decor = win.getDecorView(); if (decor != null) { KeyEvent.DispatcherState ds = decor.getKeyDispatcherState(); if (ds != null) { ds.startTracking(event, this); return true; } } } } else if (event.getAction() == KeyEvent.ACTION_UP && !event.isCanceled()) { Window win = mDialog.getWindow(); if (win != null) { View decor = win.getDecorView(); if (decor != null) { KeyEvent.DispatcherState ds = decor.getKeyDispatcherState(); if (ds != null && ds.isTracking(event)) { mMenu.close(true); dialog.dismiss(); return true; } } } } } // Menu shortcut matching return mMenu.performShortcut(keyCode, event, 0); } public void setPresenterCallback(MenuPresenter.Callback cb) { mPresenterCallback = cb; } /** * Dismisses the menu's dialog. * * @see Dialog#dismiss() */ public void dismiss() { if (mDialog != null) { mDialog.dismiss(); } } @Override public void onDismiss(DialogInterface dialog) { mPresenter.onCloseMenu(mMenu, true); } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { if (allMenusAreClosing || menu == mMenu) { dismiss(); } if (mPresenterCallback != null) { mPresenterCallback.onCloseMenu(menu, allMenusAreClosing); } } @Override public boolean onOpenSubMenu(MenuBuilder subMenu) { if (mPresenterCallback != null) { return mPresenterCallback.onOpenSubMenu(subMenu); } return false; } public void onClick(DialogInterface dialog, int which) { mMenu.performItemAction((MenuItemImpl) mPresenter.getAdapter().getItem(which), 0); } }
true
true
public void show(IBinder windowToken) { // Many references to mMenu, create local reference final MenuBuilder menu = mMenu; // Get the builder for the dialog final AlertDialog.Builder builder = new AlertDialog.Builder(menu.getContext()); // Need to force Light Menu theme as list_menu_item_layout is usually against a dark bg and // AlertDialog's bg is white mPresenter = new ListMenuPresenter(R.layout.list_menu_item_layout, R.style.Theme_AppCompat_Light_CompactMenu); mPresenter.setCallback(this); mMenu.addMenuPresenter(mPresenter); builder.setAdapter(mPresenter.getAdapter(), this); // Set the title final View headerView = menu.getHeaderView(); if (headerView != null) { // Menu's client has given a custom header view, use it builder.setCustomTitle(headerView); } else { // Otherwise use the (text) title and icon builder.setIcon(menu.getHeaderIcon()).setTitle(menu.getHeaderTitle()); } // Set the key listener builder.setOnKeyListener(this); // Show the menu mDialog = builder.create(); mDialog.setOnDismissListener(this); WindowManager.LayoutParams lp = mDialog.getWindow().getAttributes(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; if (windowToken != null) { lp.token = windowToken; } lp.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; mDialog.show(); }
public void show(IBinder windowToken) { // Many references to mMenu, create local reference final MenuBuilder menu = mMenu; // Get the builder for the dialog final AlertDialog.Builder builder = new AlertDialog.Builder(menu.getContext()); // Need to force Light Menu theme as list_menu_item_layout is usually against a dark bg and // AlertDialog's bg is white mPresenter = new ListMenuPresenter(R.layout.list_menu_item_layout, R.style.Theme_AppCompat_CompactMenu_Dialog); mPresenter.setCallback(this); mMenu.addMenuPresenter(mPresenter); builder.setAdapter(mPresenter.getAdapter(), this); // Set the title final View headerView = menu.getHeaderView(); if (headerView != null) { // Menu's client has given a custom header view, use it builder.setCustomTitle(headerView); } else { // Otherwise use the (text) title and icon builder.setIcon(menu.getHeaderIcon()).setTitle(menu.getHeaderTitle()); } // Set the key listener builder.setOnKeyListener(this); // Show the menu mDialog = builder.create(); mDialog.setOnDismissListener(this); WindowManager.LayoutParams lp = mDialog.getWindow().getAttributes(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; if (windowToken != null) { lp.token = windowToken; } lp.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; mDialog.show(); }
diff --git a/source/de/tuclausthal/submissioninterface/persistence/dao/impl/SubmissionDAO.java b/source/de/tuclausthal/submissioninterface/persistence/dao/impl/SubmissionDAO.java index 8075af5..61bd081 100644 --- a/source/de/tuclausthal/submissioninterface/persistence/dao/impl/SubmissionDAO.java +++ b/source/de/tuclausthal/submissioninterface/persistence/dao/impl/SubmissionDAO.java @@ -1,91 +1,91 @@ /* * Copyright 2009 Sven Strickroth <[email protected]> * * This file is part of the SubmissionInterface. * * SubmissionInterface is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * SubmissionInterface 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 SubmissionInterface. If not, see <http://www.gnu.org/licenses/>. */ package de.tuclausthal.submissioninterface.persistence.dao.impl; import java.io.File; import java.util.List; import org.hibernate.LockMode; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import de.tuclausthal.submissioninterface.persistence.dao.SubmissionDAOIf; import de.tuclausthal.submissioninterface.persistence.datamodel.Participation; import de.tuclausthal.submissioninterface.persistence.datamodel.Submission; import de.tuclausthal.submissioninterface.persistence.datamodel.Task; import de.tuclausthal.submissioninterface.persistence.datamodel.User; import de.tuclausthal.submissioninterface.util.HibernateSessionHelper; /** * Data Access Object implementation for the SubmissionDAOIf * @author Sven Strickroth */ public class SubmissionDAO implements SubmissionDAOIf { @Override public Submission getSubmission(int submissionid) { return (Submission) HibernateSessionHelper.getSession().get(Submission.class, submissionid); } @Override public Submission getSubmission(Task task, User user) { return (Submission) HibernateSessionHelper.getSession().createCriteria(Submission.class).add(Restrictions.eq("task", task)).createCriteria("submitter").add(Restrictions.eq("user", user)).uniqueResult(); } @Override public Submission createSubmission(Task task, Participation submitter) { Session session = HibernateSessionHelper.getSession(); Transaction tx = session.beginTransaction(); Submission submission = getSubmission(task, submitter.getUser()); if (submission == null) { submission = new Submission(task, submitter); session.save(submission); } tx.commit(); return submission; } @Override public void saveSubmission(Submission submission) { Session session = HibernateSessionHelper.getSession(); Transaction tx = session.beginTransaction(); session.saveOrUpdate(submission); tx.commit(); } @Override public List<Submission> getSubmissionsForTaskOrdered(Task task) { return (List<Submission>) HibernateSessionHelper.getSession().createCriteria(Submission.class).add(Restrictions.eq("task", task)).createCriteria("submitter").addOrder(Order.asc("group")).createCriteria("user").addOrder(Order.asc("lastName")).addOrder(Order.asc("firstName")).list(); } @Override public boolean deleteIfNoFiles(Submission submission, File submissionPath) { Session session = HibernateSessionHelper.getSession(); Transaction tx = session.beginTransaction(); session.lock(submission, LockMode.UPGRADE); boolean result = false; - if (submissionPath.listFiles().length == 0) { + if (submissionPath.listFiles().length == 0 && submissionPath.delete()) { session.delete(submission); result = true; } tx.commit(); return result; } }
true
true
public boolean deleteIfNoFiles(Submission submission, File submissionPath) { Session session = HibernateSessionHelper.getSession(); Transaction tx = session.beginTransaction(); session.lock(submission, LockMode.UPGRADE); boolean result = false; if (submissionPath.listFiles().length == 0) { session.delete(submission); result = true; } tx.commit(); return result; }
public boolean deleteIfNoFiles(Submission submission, File submissionPath) { Session session = HibernateSessionHelper.getSession(); Transaction tx = session.beginTransaction(); session.lock(submission, LockMode.UPGRADE); boolean result = false; if (submissionPath.listFiles().length == 0 && submissionPath.delete()) { session.delete(submission); result = true; } tx.commit(); return result; }
diff --git a/ui/api/src/main/java/org/jboss/forge/ui/util/Callables.java b/ui/api/src/main/java/org/jboss/forge/ui/util/Callables.java index 2db6827f4..3ada8151a 100644 --- a/ui/api/src/main/java/org/jboss/forge/ui/util/Callables.java +++ b/ui/api/src/main/java/org/jboss/forge/ui/util/Callables.java @@ -1,74 +1,74 @@ /* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.ui.util; import java.util.concurrent.Callable; /** * Utility to create and handle {@link Callable} objects * * @author <a href="mailto:[email protected]">George Gastaldi</a> */ public final class Callables { private Callables() { } /** * Wrap a constant value into a Callable Object */ public static <T> Callable<T> returning(T value) { return new ConstantCallable<T>(value); } /** * Calls the {@link Callable} avoiding the checked exception */ public static <T> T call(Callable<T> c) { if (c == null) { return null; } try { return c.call(); } - catch (RuntimeException re) + catch (RuntimeException e) { - throw re; + throw e; } catch (Exception e) { - throw new RuntimeException(e); + throw new RuntimeException("Error invoking Callable [c]", e); } } /** * Simple callable class that returns the same value */ static class ConstantCallable<V> implements Callable<V> { private final V value; public ConstantCallable(V value) { this.value = value; } @Override public V call() { return value; } } }
false
true
public static <T> T call(Callable<T> c) { if (c == null) { return null; } try { return c.call(); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new RuntimeException(e); } }
public static <T> T call(Callable<T> c) { if (c == null) { return null; } try { return c.call(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Error invoking Callable [c]", e); } }
diff --git a/iwsn/runtime.wsn-app/src/main/java/de/uniluebeck/itm/tr/runtime/wsnapp/WSNDeviceAppImpl.java b/iwsn/runtime.wsn-app/src/main/java/de/uniluebeck/itm/tr/runtime/wsnapp/WSNDeviceAppImpl.java index 99fed1c8..a14ca178 100644 --- a/iwsn/runtime.wsn-app/src/main/java/de/uniluebeck/itm/tr/runtime/wsnapp/WSNDeviceAppImpl.java +++ b/iwsn/runtime.wsn-app/src/main/java/de/uniluebeck/itm/tr/runtime/wsnapp/WSNDeviceAppImpl.java @@ -1,1068 +1,1068 @@ /********************************************************************************************************************** * Copyright (c) 2010, Institute of Telematics, University of Luebeck * * 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 the University of Luebeck 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 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 de.uniluebeck.itm.tr.runtime.wsnapp; import com.google.common.base.Preconditions; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.internal.Nullable; import com.google.inject.name.Named; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import de.uniluebeck.itm.gtr.TestbedRuntime; import de.uniluebeck.itm.gtr.messaging.MessageTools; import de.uniluebeck.itm.gtr.messaging.Messages; import de.uniluebeck.itm.gtr.messaging.event.MessageEventAdapter; import de.uniluebeck.itm.gtr.messaging.event.MessageEventListener; import de.uniluebeck.itm.gtr.messaging.srmr.SingleRequestMultiResponseListener; import de.uniluebeck.itm.motelist.MoteList; import de.uniluebeck.itm.motelist.MoteListFactory; import de.uniluebeck.itm.motelist.MoteType; import de.uniluebeck.itm.tr.nodeapi.NodeApi; import de.uniluebeck.itm.tr.nodeapi.NodeApiCallback; import de.uniluebeck.itm.tr.nodeapi.NodeApiDeviceAdapter; import de.uniluebeck.itm.tr.util.StringUtils; import de.uniluebeck.itm.tr.util.TimeDiff; import de.uniluebeck.itm.wsn.devicedrivers.DeviceFactory; import de.uniluebeck.itm.wsn.devicedrivers.generic.*; import de.uniluebeck.itm.wsn.devicedrivers.jennic.JennicBinFile; import de.uniluebeck.itm.wsn.devicedrivers.jennic.JennicDevice; import de.uniluebeck.itm.wsn.devicedrivers.pacemate.PacemateBinFile; import de.uniluebeck.itm.wsn.devicedrivers.pacemate.PacemateDevice; import de.uniluebeck.itm.wsn.devicedrivers.telosb.TelosbBinFile; import de.uniluebeck.itm.wsn.devicedrivers.telosb.TelosbDevice; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.TimeUnit; @Singleton class WSNDeviceAppImpl implements WSNDeviceApp { private static final Logger log = LoggerFactory.getLogger(WSNDeviceApp.class); private String nodeUrn; private String nodeType; private String nodeSerialInterface; private TestbedRuntime testbedRuntime; private MessageEventListener messageEventListener = new MessageEventAdapter() { @Override public void messageReceived(Messages.Msg msg) { Preconditions.checkNotNull(device, "We should only receive message if we're connected to a device"); boolean isRecipient = nodeUrn.equals(msg.getTo()); boolean isOperationInvocation = WSNApp.MSG_TYPE_OPERATION_INVOCATION_REQUEST.equals(msg.getMsgType()); boolean isListenerManagement = WSNApp.MSG_TYPE_LISTENER_MANAGEMENT.equals(msg.getMsgType()); if (isRecipient && isOperationInvocation) { log.trace("{} => Received message of type {}...", nodeUrn, msg.getMsgType()); WSNAppMessages.OperationInvocation invocation = parseOperation(msg); if (invocation != null && !isExclusiveOperationRunning()) { log.trace("{} => Operation parsed: {}", nodeUrn, invocation.getOperation()); executeOperation(invocation, msg); } } else if (isRecipient && isListenerManagement) { log.trace("{} => Received message of type {}...", nodeUrn, msg.getMsgType()); try { WSNAppMessages.ListenerManagement management = WSNAppMessages.ListenerManagement.newBuilder() .mergeFrom(msg.getPayload()).build(); executeManagement(management); } catch (InvalidProtocolBufferException e) { log.warn("InvalidProtocolBufferException while unmarshalling listener management message: " + e, e); } } } }; private final Set<String> nodeMessageListeners = new HashSet<String>(); private NodeApiDeviceAdapter nodeApiDeviceAdapter = new NodeApiDeviceAdapter() { @Override public void sendToNode(final ByteBuffer packet) { try { if (log.isDebugEnabled()) { log.debug( "{} => Sending a WISELIB_DOWNSTREAM packet: {}", nodeUrn, StringUtils.toHexString(packet.array()) ); } device.send(new MessagePacket(MESSAGE_TYPE_WISELIB_DOWNSTREAM, packet.array())); } catch (Exception e) { log.error("" + e, e); } } }; private NodeApi nodeApi; private static final int DEFAULT_NODE_API_TIMEOUT = 5000; private String nodeUSBChipID; private void executeManagement(WSNAppMessages.ListenerManagement management) { if (WSNAppMessages.ListenerManagement.Operation.REGISTER == management.getOperation()) { log.debug("{} => Node {} registered for node outputs", nodeUrn, management.getNodeName()); nodeMessageListeners.add(management.getNodeName()); } else { log.debug("{} => Node {} unregistered from node outputs", nodeUrn, management.getNodeName()); nodeMessageListeners.remove(management.getNodeName()); } } private Messages.Msg currentOperationInvocationMsg; private WSNAppMessages.OperationInvocation currentOperationInvocation; private TimeDiff currentOperationLastProgress; private iSenseDevice device; private SingleRequestMultiResponseListener.Responder currentOperationResponder; @Inject public WSNDeviceAppImpl(@Named(WSNDeviceAppModule.NAME_NODE_URN) String nodeUrn, @Named(WSNDeviceAppModule.NAME_NODE_TYPE) String nodeType, @Named(WSNDeviceAppModule.NAME_SERIAL_INTERFACE) @Nullable String nodeSerialInterface, @Named(WSNDeviceAppModule.NAME_NODE_API_TIMEOUT) @Nullable Integer nodeAPITimeout, @Named(WSNDeviceAppModule.NAME_USB_CHIP_ID) @Nullable String nodeUSBChipID, TestbedRuntime testbedRuntime) { Preconditions.checkNotNull(nodeUrn); Preconditions.checkNotNull(nodeType); this.nodeUrn = nodeUrn; this.nodeType = nodeType; this.nodeUSBChipID = nodeUSBChipID; this.nodeSerialInterface = nodeSerialInterface; this.testbedRuntime = testbedRuntime; this.nodeApi = new NodeApi(nodeApiDeviceAdapter, nodeAPITimeout == null ? DEFAULT_NODE_API_TIMEOUT : nodeAPITimeout, TimeUnit.MILLISECONDS ); try { this.datatypeFactory = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException e) { log.error(nodeUrn + " => " + e, e); } } private void executeOperation(WSNAppMessages.OperationInvocation invocation, Messages.Msg msg) { switch (invocation.getOperation()) { case ARE_NODES_ALIVE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> checkAreNodesAlive()", nodeUrn); executeAreNodesAlive(msg); break; case DISABLE_NODE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> disableNode()", nodeUrn); executeDisableNode(msg); break; case ENABLE_NODE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> enableNode()", nodeUrn); executeEnableNode(msg); break; case DISABLE_PHYSICAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> disablePhysicalLink()", nodeUrn); try { WSNAppMessages.DisablePhysicalLink disablePhysicalLink = WSNAppMessages.DisablePhysicalLink.parseFrom(invocation.getArguments()); - long nodeB = Long.parseLong(disablePhysicalLink.getNodeB()); + long nodeB = StringUtils.parseHexOrDecLongFromUrn(disablePhysicalLink.getNodeB()); executeDisablePhysicalLink(msg, nodeB); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for disablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); return; } catch (NumberFormatException e) { log.warn("{} => Couldn't parse long value for disablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(-1, "Destination node is not a valid long value!") ) ); } break; case ENABLE_PHYSICAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> enablePhysicalLink()", nodeUrn); try { WSNAppMessages.EnablePhysicalLink enablePhysicalLink = WSNAppMessages.EnablePhysicalLink.parseFrom(invocation.getArguments()); - long nodeB = Long.parseLong(enablePhysicalLink.getNodeB()); + long nodeB = StringUtils.parseHexOrDecLongFromUrn(enablePhysicalLink.getNodeB()); executeEnablePhysicalLink(msg, nodeB); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for enablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); return; } catch (NumberFormatException e) { log.warn("{} => Couldn't parse long value for enablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(-1, "Destination node is not a valid long value!") ) ); } break; case RESET_NODES: log.trace("{} => WSNDeviceAppImpl.executeOperation --> resetNodes()", nodeUrn); executeResetNodes(msg, invocation); break; case SEND: log.trace("{} => WSNDeviceAppImpl.executeOperation --> send()", nodeUrn); try { WSNAppMessages.Message message = WSNAppMessages.Message.parseFrom(invocation.getArguments()); executeSendMessage(message); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for send operation: {}. Ignoring...", nodeUrn, e); return; } break; case SET_VIRTUAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> setVirtualLink()", nodeUrn); try { WSNAppMessages.SetVirtualLinkRequest setVirtualLinkRequest = WSNAppMessages.SetVirtualLinkRequest.parseFrom(invocation.getArguments()); executeSetVirtualLink(setVirtualLinkRequest, msg); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for setVirtualLink operation: {}. Ignoring...", nodeUrn, e); return; } break; case DESTROY_VIRTUAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> destroyVirtualLink()", nodeUrn); try { WSNAppMessages.DestroyVirtualLinkRequest destroyVirtualLinkRequest = WSNAppMessages.DestroyVirtualLinkRequest.parseFrom(invocation.getArguments()); executeDestroyVirtualLink(destroyVirtualLinkRequest, msg); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for setVirtualLink operation: {}. Ignoring...", nodeUrn, e); return; } break; } } private void executeEnablePhysicalLink(final Messages.Msg msg, final long nodeB) { nodeApi.getLinkControl().disablePhysicalLink(nodeB, new ReplyingNodeApiCallback(msg)); } private void executeDisablePhysicalLink(final Messages.Msg msg, final long nodeB) { nodeApi.getLinkControl().enablePhysicalLink(nodeB, new ReplyingNodeApiCallback(msg)); } private void executeEnableNode(final Messages.Msg msg) { nodeApi.getNodeControl().enableNode(new ReplyingNodeApiCallback(msg)); } private void executeDisableNode(final Messages.Msg msg) { nodeApi.getNodeControl().disableNode(new ReplyingNodeApiCallback(msg)); } private class ReplyingNodeApiCallback implements NodeApiCallback { private Messages.Msg invocationMsg; private ReplyingNodeApiCallback(final Messages.Msg invocationMsg) { this.invocationMsg = invocationMsg; } @Override public void success(@Nullable byte[] replyPayload) { String message = replyPayload == null ? null : new String(replyPayload); sendExecutionReply(invocationMsg, 1, message); } @Override public void failure(byte responseType, @Nullable byte[] replyPayload) { sendExecutionReply(invocationMsg, responseType, new String(replyPayload)); } @Override public void timeout() { sendExecutionReply(invocationMsg, 0, "Communication to node timed out!"); } private void sendExecutionReply(final Messages.Msg invocationMsg, final int code, final String message) { testbedRuntime.getUnreliableMessagingService().sendAsync( MessageTools.buildReply(invocationMsg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(code, message) ) ); } } private byte[] buildRequestStatus(int value, String message) { WSNAppMessages.RequestStatus.Status.Builder statusBuilder = WSNAppMessages.RequestStatus.Status.newBuilder() .setNodeId(nodeUrn) .setValue(value); if (message != null) { statusBuilder.setMsg(message); } WSNAppMessages.RequestStatus requestStatus = WSNAppMessages.RequestStatus.newBuilder() .setStatus(statusBuilder) .build(); return requestStatus.toByteArray(); } private void executeDestroyVirtualLink(final WSNAppMessages.DestroyVirtualLinkRequest destroyVirtualLinkRequest, final Messages.Msg msg) { Long destinationNode = null; try { String[] strings = destroyVirtualLinkRequest.getTargetNode().split(":"); destinationNode = StringUtils.parseHexOrDecLong(strings[strings.length - 1]); } catch (Exception e) { log.warn( "{} => Received destinationNode URN whose suffix could not be parsed to long: {}", nodeUrn, destroyVirtualLinkRequest.getTargetNode() ); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(-1, "Destination node URN suffix is not a valid long value!") ) ); } if (destinationNode != null) { nodeApi.getLinkControl().destroyVirtualLink(destinationNode, new ReplyingNodeApiCallback(msg)); } } private void executeSetVirtualLink(final WSNAppMessages.SetVirtualLinkRequest setVirtualLinkRequest, final Messages.Msg msg) { Long destinationNode = null; try { String[] strings = setVirtualLinkRequest.getTargetNode().split(":"); destinationNode = StringUtils.parseHexOrDecLong(strings[strings.length - 1]); } catch (Exception e) { log.warn("{} => Received destinationNode URN whose suffix could not be parsed to long: {}", nodeUrn, setVirtualLinkRequest.getTargetNode() ); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(-1, "Destination node URN suffix is not a valid long value!") ) ); } if (destinationNode != null) { nodeApi.getLinkControl().setVirtualLink(destinationNode, new NodeApiCallback() { @Override public void success(@Nullable byte[] replyPayload) { String message = replyPayload == null ? null : new String(replyPayload); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(1, message) ) ); } @Override public void failure(byte responseType, @Nullable byte[] replyPayload) { testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(responseType, new String(replyPayload)) ) ); } @Override public void timeout() { testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(0, "Communication to node timed out!") ) ); } } ); } } private void executeSendMessage(WSNAppMessages.Message message) { log.debug("{} => WSNDeviceAppImpl.executeSendMessage()", nodeUrn); byte[] messageBytes = null; byte messageType = -1; if (message.hasBinaryMessage()) { WSNAppMessages.Message.BinaryMessage binaryMessage = message.getBinaryMessage(); if (!binaryMessage.hasBinaryType()) { log.warn("{} => Message type missing in message {}", nodeUrn, message); return; } else { messageType = (byte) binaryMessage.getBinaryType(); messageBytes = binaryMessage.getBinaryData().toByteArray(); if (log.isDebugEnabled()) { log.debug("{} => Delivering binary message of type {} and payload {}", new Object[]{ nodeUrn, StringUtils.toHexString(messageType), StringUtils.toHexString(messageBytes) } ); } } } else if (message.hasTextMessage()) { log.debug("{} => Delivering text message \"{}\"", message.getTextMessage()); WSNAppMessages.Message.TextMessage textMessage = message.getTextMessage(); messageType = (byte) textMessage.getMessageLevel().getNumber(); messageBytes = textMessage.getMsg().getBytes(); } else { log.error("{} => This case MUST NOT OCCUR or something is wrong!!!!!!!!!!!!!!!", nodeUrn); } try { if (messageType == MESSAGE_TYPE_WISELIB_DOWNSTREAM && messageBytes[0] == VIRTUAL_LINK_MESSAGE) { log.debug("{} => Delivering virtual link message over node API", nodeUrn); ByteBuffer messageBuffer = ByteBuffer.wrap(messageBytes); final byte RSSI = messageBuffer.get(2); final byte LQI = messageBuffer.get(3); final byte payloadLength = messageBuffer.get(4); final long destination = messageBuffer.getLong(5); final long source = messageBuffer.getLong(13); final byte[] payload = new byte[payloadLength]; System.arraycopy(messageBytes, 21, payload, 0, payloadLength); final byte[] finalMessageBytes = messageBytes; System.out.println("payloadLength = " + payloadLength); nodeApi.getInteraction() .sendVirtualLinkMessage(RSSI, LQI, destination, source, payload, new NodeApiCallback() { @Override public void success(@Nullable final byte[] replyPayload) { log.debug( "{} => Successfully delivered virtual link message to node. MessageBytes: {}. Reply: {}", new Object[]{ nodeUrn, StringUtils.toHexString(finalMessageBytes), StringUtils.toHexString(replyPayload) } ); } @Override public void failure(final byte responseType, @Nullable final byte[] replyPayload) { log.warn( "{} => Failed to deliver virtual link message to node. ResponseType: {}. ReplyPayload: {}", new Object[]{ nodeUrn, StringUtils.toHexString(responseType), StringUtils.toHexString(replyPayload) } ); } @Override public void timeout() { log.warn("{} => Timed out when trying to deliver virtual link message to node.", nodeUrn ); } } ); } else { log.debug( "{} => Delivering message directly over iSenseDevice.send(), i.e. not as a virtual link message.", nodeUrn ); device.send(new MessagePacket(messageType, messageBytes)); } } catch (Exception e) { log.error("" + e, e); } } private void executeResetNodes(Messages.Msg msg, WSNAppMessages.OperationInvocation invocation) { log.debug("{} => WSNDeviceAppImpl.executeResetNodes()", nodeUrn); try { currentOperationInvocation = invocation; currentOperationInvocationMsg = msg; if (!device.isConnected()) { failedReset("Failed resetting node. Reason: Device is not connected."); } boolean triggered = device.triggerReboot(); if (!triggered) { failedReset("Failed resetting node. Reason: Could not trigger reboot."); } } catch (Exception e) { log.error("Error while resetting device: " + e, e); failedReset("Failed resetting node. Reason: " + e.getMessage()); } } private void executeFlashPrograms(WSNAppMessages.OperationInvocation invocation, SingleRequestMultiResponseListener.Responder responder) { log.debug("{} => WSNDeviceAppImpl.executeFlashPrograms()", nodeUrn); try { WSNAppMessages.Program program = WSNAppMessages.Program.parseFrom(invocation.getArguments()); IDeviceBinFile iSenseBinFile = null; if (device instanceof JennicDevice) { iSenseBinFile = new JennicBinFile(program.getProgram().toByteArray(), program.getMetaData().toString()); } else if (device instanceof TelosbDevice) { iSenseBinFile = new TelosbBinFile(program.getProgram().toByteArray(), program.getMetaData().toString()); } else if (device instanceof PacemateDevice) { iSenseBinFile = new PacemateBinFile(program.getProgram().toByteArray(), program.getMetaData().toString()); } try { // remember invocation message to be able to send asynchronous replies currentOperationInvocation = invocation; currentOperationResponder = responder; currentOperationLastProgress = new TimeDiff(1000); if (!device.isConnected()) { failedFlashPrograms("Failed flashing node. Reason: Node is not connected."); return; } if (!device.triggerProgram(iSenseBinFile, true)) { failedFlashPrograms("Failed to trigger programming."); return; } } catch (Exception e) { log.error("{} => Error while flashing device. Reason: {}", nodeUrn, e.getMessage()); failedFlashPrograms("Error while flashing device. Reason: " + e.getMessage()); return; } } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse program for flash operation: {}. Ignoring...", nodeUrn, e); } catch (Exception e) { log.error("Error reading bin file " + e); } } private void failedFlashPrograms(String reason) { log.debug("{} => WSNDeviceAppImpl.failedFlashPrograms()", nodeUrn); // send reply to indicate failure currentOperationResponder.sendResponse(buildRequestStatus(-1, "Failed flashing node. Reason: " + reason)); resetCurrentOperation(); } private void resetCurrentOperation() { currentOperationInvocation = null; currentOperationInvocationMsg = null; currentOperationResponder = null; currentOperationLastProgress = null; } private void progressFlashPrograms(float value) { log.debug("{} => WSNDeviceAppImpl.progressFlashPrograms({})", nodeUrn, value); if (currentOperationLastProgress.isTimeout()) { log.debug("{} => Sending asynchronous receivedRequestStatus message.", nodeUrn); // send reply to indicate failure currentOperationResponder.sendResponse(buildRequestStatus((int) (value * 100), null)); currentOperationLastProgress.touch(); } } private void doneFlashPrograms() { log.debug("{} => WSNDeviceAppImpl.doneFlashPrograms()", nodeUrn); // send reply to indicate failure currentOperationResponder.sendResponse(buildRequestStatus(100, null)); resetCurrentOperation(); } private void executeAreNodesAlive(Messages.Msg msg) { log.debug("{} => WSNDeviceAppImpl.executeAreNodesAlive()", nodeUrn); // to the best of our knowledge, a node is alive if we're connected to it boolean connected = device != null && device.isConnected(); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(connected ? 1 : 0, null) ) ); } private WSNAppMessages.OperationInvocation parseOperation(Messages.Msg msg) { try { if (log.isDebugEnabled()) { log.debug("{} => Received operation invocation, bytes: {}", nodeUrn, StringUtils.toHexString(msg.getPayload().toByteArray()) ); } return WSNAppMessages.OperationInvocation.parseFrom(msg.getPayload()); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse operation invocation message: {}. Ignoring...", nodeUrn, e); return null; } } private boolean isFlashOperation(WSNAppMessages.OperationInvocation operationInvocation) { return operationInvocation != null && operationInvocation .getOperation() == WSNAppMessages.OperationInvocation.Operation.FLASH_PROGRAMS; } private static final int MESSAGE_TYPE_WISELIB_DOWNSTREAM = 10; private static final int MESSAGE_TYPE_WISELIB_UPSTREAM = 105; private static final byte NODE_OUTPUT_TEXT = 50; private static final byte NODE_OUTPUT_BYTE = 51; private static final byte NODE_OUTPUT_VIRTUAL_LINK = 52; private static final byte VIRTUAL_LINK_MESSAGE = 11; private iSenseDeviceListener deviceListener = new iSenseDeviceListenerAdapter() { @Override public void receivePacket(MessagePacket p) { log.trace("{} => WSNDeviceAppImpl.receivePacket: {}", nodeUrn, p); boolean isWiselibUpstream = p.getType() == MESSAGE_TYPE_WISELIB_UPSTREAM; boolean isByteTextOrVLink = (p.getContent()[0] & 0xFF) == NODE_OUTPUT_BYTE || (p.getContent()[0] & 0xFF) == NODE_OUTPUT_TEXT || (p.getContent()[0] & 0xFF) == NODE_OUTPUT_VIRTUAL_LINK; boolean isWiselibReply = isWiselibUpstream && !isByteTextOrVLink; if (isWiselibReply) { if (log.isDebugEnabled()) { log.debug("{} => Received WISELIB_UPSTREAM packet with content: {}", nodeUrn, p); } nodeApiDeviceAdapter.receiveFromNode(ByteBuffer.wrap(p.getContent())); } else { deliverToNodeMessageReceivers(p); } } @Override public void operationCanceled(Operation operation) { log.debug("{} => Operation {} canceled.", nodeUrn, operation); if (isFlashOperation(currentOperationInvocation) && operation == Operation.PROGRAM) { failedFlashPrograms("operation canceled"); } else if (isResetOperation(currentOperationInvocation) && operation == Operation.RESET) { failedReset("Failed resetting node. Reason: Operation canceled."); } } @Override public void operationDone(Operation operation, Object o) { log.debug("{} => Operation {} done. Object: {}", new Object[]{nodeUrn, operation, o}); if (isFlashOperation(currentOperationInvocation) && operation == Operation.PROGRAM) { if (o instanceof Exception) { failedFlashPrograms(((Exception) o).getMessage()); } else { doneFlashPrograms(); } } else if (isResetOperation(currentOperationInvocation) && operation == Operation.RESET) { if (o == null) { failedFlashPrograms("Could not reset node"); } else if (o instanceof Boolean && ((Boolean) o).booleanValue()) { doneReset(); } else { failedFlashPrograms("Could not reset node" );//urn:wisebed:uzl-staging:0xe301,urn:wisebed:uzl-staging:0x2504,urn:wisebed:uzl-staging:0x0d99,urn:wisebed:uzl-staging:0x2bbb } } } @Override public void operationProgress(Operation operation, float v) { log.debug("{} => Operation {} receivedRequestStatus: {}", new Object[]{nodeUrn, operation, v}); if (isFlashOperation(currentOperationInvocation)) { progressFlashPrograms(v); } } }; private DatatypeFactory datatypeFactory = null; private void deliverToNodeMessageReceivers(MessagePacket p) { if (nodeMessageListeners.size() == 0) { log.debug("{} => No message listeners registered!", nodeUrn); return; } XMLGregorianCalendar now = datatypeFactory.newXMLGregorianCalendar((GregorianCalendar) GregorianCalendar.getInstance()); WSNAppMessages.Message.Builder messageBuilder = WSNAppMessages.Message.newBuilder() .setSourceNodeId(nodeUrn) .setTimestamp(now.toXMLFormat()); boolean isTextMessage = PacketTypes.LOG == p.getType(); if (isTextMessage) { byte[] content = p.getContent(); if (content != null && content.length > 1) { WSNAppMessages.Message.MessageLevel messageLevel; switch (content[0]) { case PacketTypes.LogType.FATAL: messageLevel = WSNAppMessages.Message.MessageLevel.FATAL; break; default: messageLevel = WSNAppMessages.Message.MessageLevel.DEBUG; break; } String textMessage = new String(content, 1, content.length - 1); WSNAppMessages.Message.TextMessage.Builder textMessageBuilder = WSNAppMessages.Message.TextMessage.newBuilder() .setMessageLevel(messageLevel) .setMsg(textMessage); messageBuilder.setTextMessage(textMessageBuilder); } else { log.debug("{} => Received text message without content. Ignoring packet: {}", nodeUrn, p); return; } } else { WSNAppMessages.Message.BinaryMessage.Builder binaryMessageBuilder = WSNAppMessages.Message.BinaryMessage.newBuilder() .setBinaryType(p.getType()) .setBinaryData(ByteString.copyFrom(p.getContent())); messageBuilder.setBinaryMessage(binaryMessageBuilder); } WSNAppMessages.Message message = messageBuilder.build(); for (String nodeMessageListener : nodeMessageListeners) { if (log.isDebugEnabled()) { log.debug("{} => Delivering node output to {}: {}", new String[]{ nodeUrn, nodeMessageListener, WSNAppMessageTools.toString(message, false) } ); } testbedRuntime.getUnreliableMessagingService().sendAsync( nodeUrn, nodeMessageListener, WSNApp.MSG_TYPE_LISTENER_MESSAGE, message.toByteArray(), 1, System.currentTimeMillis() + 5000 ); } } private void doneReset() { log.debug("{} => WSNDeviceAppImpl.doneReset()", nodeUrn); // send reply to indicate failure testbedRuntime.getUnreliableMessagingService().sendAsync( MessageTools.buildReply(currentOperationInvocationMsg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(1, null) ) ); resetCurrentOperation(); } private void failedReset(String reason) { log.debug("{} => WSNDeviceAppImpl.failedReset()", nodeUrn); // send reply to indicate failure testbedRuntime.getUnreliableMessagingService().sendAsync( MessageTools.buildReply(currentOperationInvocationMsg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(0, reason) ) ); resetCurrentOperation(); } private boolean isResetOperation(WSNAppMessages.OperationInvocation operationInvocation) { return operationInvocation != null && operationInvocation .getOperation() == WSNAppMessages.OperationInvocation.Operation.RESET_NODES; } @Override public String getName() { return WSNDeviceApp.class.getSimpleName(); } private SingleRequestMultiResponseListener srmrsListener = new SingleRequestMultiResponseListener() { @Override public void receiveRequest(Messages.Msg msg, Responder responder) { try { WSNAppMessages.OperationInvocation invocation = WSNAppMessages.OperationInvocation.newBuilder().mergeFrom(msg.getPayload()).build(); if (WSNAppMessages.OperationInvocation.Operation.FLASH_PROGRAMS == invocation.getOperation()) { executeFlashPrograms(invocation, responder); } } catch (InvalidProtocolBufferException e) { log.warn("{} => Error while parsing operation invocation. Ignoring...: {}", nodeUrn, e); } } }; private Runnable connectRunnable = new Runnable() { @Override public void run() { if (nodeSerialInterface == null || "".equals(nodeSerialInterface)) { Long macAddress = StringUtils.parseHexOrDecLongFromUrn(nodeUrn); MoteList moteList; log.debug("{} => Using motelist module to detect serial port for {} device.", nodeUrn, nodeType); try { Map<String, String> telosBReferenceToMACMap = null; if ("telosb".equals(nodeType) && nodeUSBChipID != null && !"".equals(nodeUSBChipID)) { telosBReferenceToMACMap = new HashMap<String, String>() {{ put(nodeUSBChipID, StringUtils.getUrnSuffix(nodeUrn)); }}; } moteList = MoteListFactory.create(telosBReferenceToMACMap); } catch (Exception e) { log.error( "{} => Failed to load the motelist module to detect the serial port. Reason: {}. Not trying to reconnect to device.", nodeUrn, e.getMessage() ); return; } try { nodeSerialInterface = moteList.getMotePort(MoteType.fromString(nodeType.toLowerCase()), macAddress); } catch (Exception e) { log.warn("{} => Exception while detecting serial interface: {}", nodeUrn, e); } if (nodeSerialInterface == null) { log.warn("{} => No serial interface could be detected for {} node. Retrying in 30 seconds.", nodeUrn, nodeType ); testbedRuntime.getSchedulerService().schedule(this, 30, TimeUnit.SECONDS); return; } else { log.debug("{} => Found {} node on serial port {}.", new Object[]{nodeUrn, nodeType, nodeSerialInterface} ); } } try { device = DeviceFactory.create(nodeType, nodeSerialInterface); } catch (Exception e) { log.warn("{} => Connection to {} device on serial port {} failed. Reason: {}. Retrying in 30 seconds.", new Object[]{ nodeUrn, nodeType, nodeSerialInterface, e.getMessage() } ); testbedRuntime.getSchedulerService().schedule(this, 30, TimeUnit.SECONDS); return; } log.debug("{} => Successfully connected to {} node on serial port {}", new Object[]{nodeUrn, nodeType, nodeSerialInterface} ); // attach as listener to device output device.registerListener(deviceListener); // now start listening to messages testbedRuntime.getSingleRequestMultiResponseService() .addListener(nodeUrn, WSNApp.MSG_TYPE_OPERATION_INVOCATION_REQUEST, srmrsListener); testbedRuntime.getMessageEventService().addListener(messageEventListener); } }; @Override public void start() throws Exception { log.debug("{} => WSNDeviceAppImpl.start()", nodeUrn); testbedRuntime.getSchedulerService().execute(connectRunnable); } @Override public void stop() { log.debug("{} => WSNDeviceAppImpl.stop()", nodeUrn); // first stop listening to messages testbedRuntime.getMessageEventService().removeListener(messageEventListener); testbedRuntime.getSingleRequestMultiResponseService().removeListener(srmrsListener); // then disconnect from device if (device != null) { device.deregisterListener(deviceListener); log.debug("{} => Shutting down {} device", nodeUrn, nodeType); device.shutdown(); } } public boolean isExclusiveOperationRunning() { return currentOperationInvocation != null; } }
false
true
private void executeOperation(WSNAppMessages.OperationInvocation invocation, Messages.Msg msg) { switch (invocation.getOperation()) { case ARE_NODES_ALIVE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> checkAreNodesAlive()", nodeUrn); executeAreNodesAlive(msg); break; case DISABLE_NODE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> disableNode()", nodeUrn); executeDisableNode(msg); break; case ENABLE_NODE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> enableNode()", nodeUrn); executeEnableNode(msg); break; case DISABLE_PHYSICAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> disablePhysicalLink()", nodeUrn); try { WSNAppMessages.DisablePhysicalLink disablePhysicalLink = WSNAppMessages.DisablePhysicalLink.parseFrom(invocation.getArguments()); long nodeB = Long.parseLong(disablePhysicalLink.getNodeB()); executeDisablePhysicalLink(msg, nodeB); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for disablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); return; } catch (NumberFormatException e) { log.warn("{} => Couldn't parse long value for disablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(-1, "Destination node is not a valid long value!") ) ); } break; case ENABLE_PHYSICAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> enablePhysicalLink()", nodeUrn); try { WSNAppMessages.EnablePhysicalLink enablePhysicalLink = WSNAppMessages.EnablePhysicalLink.parseFrom(invocation.getArguments()); long nodeB = Long.parseLong(enablePhysicalLink.getNodeB()); executeEnablePhysicalLink(msg, nodeB); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for enablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); return; } catch (NumberFormatException e) { log.warn("{} => Couldn't parse long value for enablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(-1, "Destination node is not a valid long value!") ) ); } break; case RESET_NODES: log.trace("{} => WSNDeviceAppImpl.executeOperation --> resetNodes()", nodeUrn); executeResetNodes(msg, invocation); break; case SEND: log.trace("{} => WSNDeviceAppImpl.executeOperation --> send()", nodeUrn); try { WSNAppMessages.Message message = WSNAppMessages.Message.parseFrom(invocation.getArguments()); executeSendMessage(message); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for send operation: {}. Ignoring...", nodeUrn, e); return; } break; case SET_VIRTUAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> setVirtualLink()", nodeUrn); try { WSNAppMessages.SetVirtualLinkRequest setVirtualLinkRequest = WSNAppMessages.SetVirtualLinkRequest.parseFrom(invocation.getArguments()); executeSetVirtualLink(setVirtualLinkRequest, msg); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for setVirtualLink operation: {}. Ignoring...", nodeUrn, e); return; } break; case DESTROY_VIRTUAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> destroyVirtualLink()", nodeUrn); try { WSNAppMessages.DestroyVirtualLinkRequest destroyVirtualLinkRequest = WSNAppMessages.DestroyVirtualLinkRequest.parseFrom(invocation.getArguments()); executeDestroyVirtualLink(destroyVirtualLinkRequest, msg); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for setVirtualLink operation: {}. Ignoring...", nodeUrn, e); return; } break; } }
private void executeOperation(WSNAppMessages.OperationInvocation invocation, Messages.Msg msg) { switch (invocation.getOperation()) { case ARE_NODES_ALIVE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> checkAreNodesAlive()", nodeUrn); executeAreNodesAlive(msg); break; case DISABLE_NODE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> disableNode()", nodeUrn); executeDisableNode(msg); break; case ENABLE_NODE: log.trace("{} => WSNDeviceAppImpl.executeOperation --> enableNode()", nodeUrn); executeEnableNode(msg); break; case DISABLE_PHYSICAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> disablePhysicalLink()", nodeUrn); try { WSNAppMessages.DisablePhysicalLink disablePhysicalLink = WSNAppMessages.DisablePhysicalLink.parseFrom(invocation.getArguments()); long nodeB = StringUtils.parseHexOrDecLongFromUrn(disablePhysicalLink.getNodeB()); executeDisablePhysicalLink(msg, nodeB); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for disablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); return; } catch (NumberFormatException e) { log.warn("{} => Couldn't parse long value for disablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(-1, "Destination node is not a valid long value!") ) ); } break; case ENABLE_PHYSICAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> enablePhysicalLink()", nodeUrn); try { WSNAppMessages.EnablePhysicalLink enablePhysicalLink = WSNAppMessages.EnablePhysicalLink.parseFrom(invocation.getArguments()); long nodeB = StringUtils.parseHexOrDecLongFromUrn(enablePhysicalLink.getNodeB()); executeEnablePhysicalLink(msg, nodeB); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for enablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); return; } catch (NumberFormatException e) { log.warn("{} => Couldn't parse long value for enablePhysicalLink operation: {}. Ignoring...", nodeUrn, e ); testbedRuntime.getUnreliableMessagingService() .sendAsync(MessageTools.buildReply(msg, WSNApp.MSG_TYPE_OPERATION_INVOCATION_RESPONSE, buildRequestStatus(-1, "Destination node is not a valid long value!") ) ); } break; case RESET_NODES: log.trace("{} => WSNDeviceAppImpl.executeOperation --> resetNodes()", nodeUrn); executeResetNodes(msg, invocation); break; case SEND: log.trace("{} => WSNDeviceAppImpl.executeOperation --> send()", nodeUrn); try { WSNAppMessages.Message message = WSNAppMessages.Message.parseFrom(invocation.getArguments()); executeSendMessage(message); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for send operation: {}. Ignoring...", nodeUrn, e); return; } break; case SET_VIRTUAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> setVirtualLink()", nodeUrn); try { WSNAppMessages.SetVirtualLinkRequest setVirtualLinkRequest = WSNAppMessages.SetVirtualLinkRequest.parseFrom(invocation.getArguments()); executeSetVirtualLink(setVirtualLinkRequest, msg); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for setVirtualLink operation: {}. Ignoring...", nodeUrn, e); return; } break; case DESTROY_VIRTUAL_LINK: log.trace("{} => WSNDeviceAppImpl.executeOperation --> destroyVirtualLink()", nodeUrn); try { WSNAppMessages.DestroyVirtualLinkRequest destroyVirtualLinkRequest = WSNAppMessages.DestroyVirtualLinkRequest.parseFrom(invocation.getArguments()); executeDestroyVirtualLink(destroyVirtualLinkRequest, msg); } catch (InvalidProtocolBufferException e) { log.warn("{} => Couldn't parse message for setVirtualLink operation: {}. Ignoring...", nodeUrn, e); return; } break; } }
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNWCAccess.java b/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNWCAccess.java index c5df488ce..27521674f 100644 --- a/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNWCAccess.java +++ b/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNWCAccess.java @@ -1,633 +1,633 @@ /* * ==================================================================== * Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.wc.admin; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNExternalInfo; import org.tmatesoft.svn.core.internal.wc.SVNFileType; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.ISVNOptions; import org.tmatesoft.svn.core.wc.SVNEvent; /** * @version 1.1.1 * @author TMate Software Ltd. */ public class SVNWCAccess implements ISVNEventHandler { public static final int INFINITE_DEPTH = -1; private ISVNEventHandler myEventHandler; private ISVNOptions myOptions; private Map myAdminAreas; private File myAnchor; public static SVNWCAccess newInstance(ISVNEventHandler eventHandler) { return new SVNWCAccess(eventHandler); } private SVNWCAccess(ISVNEventHandler handler) { myEventHandler = handler; } public void setEventHandler(ISVNEventHandler handler) { myEventHandler = handler; } public ISVNEventHandler getEventHandler() { return myEventHandler; } public void checkCancelled() throws SVNCancelException { if (myEventHandler != null) { myEventHandler.checkCancelled(); } } public void handleEvent(SVNEvent event) throws SVNException { handleEvent(event, ISVNEventHandler.UNKNOWN); } public void handleEvent(SVNEvent event, double progress) throws SVNException { if (myEventHandler != null) { try { myEventHandler.handleEvent(event, progress); } catch (SVNException e) { throw e; } catch (Throwable th) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNKNOWN, "Error while dispatching event: {0}", th.getMessage()); SVNErrorManager.error(err, th); } } } public void setOptions(ISVNOptions options) { myOptions = options; } public ISVNOptions getOptions() { if (myOptions == null) { myOptions = new DefaultSVNOptions(); } return myOptions; } public void setAnchor(File anchor) { myAnchor = anchor; } public File getAnchor() { return myAnchor; } public SVNAdminAreaInfo openAnchor(File path, boolean writeLock, int depth) throws SVNException { File parent = path.getParentFile(); if (parent == null) { SVNAdminArea anchor = open(path, writeLock, depth); return new SVNAdminAreaInfo(this, anchor, anchor, ""); } String name = path.getName(); SVNAdminArea parentArea = null; SVNAdminArea targetArea = null; SVNException parentError = null; try { parentArea = open(parent, writeLock, false, 0); } catch (SVNException svne) { if (writeLock && svne.getErrorMessage().getErrorCode() == SVNErrorCode.WC_LOCKED) { try { parentArea = open(parent, false, false, 0); } catch (SVNException svne2) { throw svne; } parentError = svne; } else if (svne.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_DIRECTORY) { throw svne; } } try { targetArea = open(path, writeLock, false, depth); } catch (SVNException svne) { if (parentArea == null || svne.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_DIRECTORY) { try { close(); } catch (SVNException svne2) { // } throw svne; } } if (parentArea != null && targetArea != null) { SVNEntry parentEntry = null; SVNEntry targetEntry = null; SVNEntry targetInParent = null; try { targetInParent = parentArea.getEntry(name, false); targetEntry = targetArea.getEntry(targetArea.getThisDirName(), false); parentEntry = parentArea.getEntry(parentArea.getThisDirName(), false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } - SVNURL parentURL = parentEntry.getSVNURL(); - SVNURL targetURL = targetEntry.getSVNURL(); + SVNURL parentURL = parentEntry != null ? parentEntry.getSVNURL() : null; + SVNURL targetURL = targetEntry != null ? targetEntry.getSVNURL() : null; String encodedName = SVNEncodingUtil.uriEncode(name); if (targetInParent == null || (parentURL != null && targetURL != null && (!parentURL.equals(targetURL.removePathTail()) || !encodedName.equals(SVNPathUtil.tail(targetURL.getPath()))))) { if (myAdminAreas != null) { myAdminAreas.remove(parent); } try { doClose(parentArea, false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } parentArea = null; } } if (parentArea != null) { if (parentError != null && targetArea != null) { try { close(); } catch (SVNException svne) { // } throw parentError; } } if (targetArea == null) { SVNEntry targetEntry = null; try { targetEntry = parentArea.getEntry(name, false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } if (targetEntry != null && targetEntry.isDirectory()) { if (myAdminAreas != null) { myAdminAreas.put(path, null); } } } SVNAdminArea anchor = parentArea != null ? parentArea : targetArea; SVNAdminArea target = targetArea != null ? targetArea : parentArea; return new SVNAdminAreaInfo(this, anchor, target, parentArea == null ? "" : name); } public SVNAdminArea open(File path, boolean writeLock, int depth) throws SVNException { return open(path, writeLock, false, depth); } public SVNAdminArea open(File path, boolean writeLock, boolean stealLock, int depth) throws SVNException { Map tmp = new HashMap(); SVNAdminArea area; try { area = doOpen(path, writeLock, stealLock, depth, tmp); } finally { for(Iterator paths = tmp.keySet().iterator(); paths.hasNext();) { Object childPath = paths.next(); SVNAdminArea childArea = (SVNAdminArea) tmp.get(childPath); myAdminAreas.put(childPath, childArea); } } return area; } public SVNAdminArea probeOpen(File path, boolean writeLock, int depth) throws SVNException { File dir = probe(path); if (!path.equals(dir)) { depth = 0; } SVNAdminArea adminArea = null; try { adminArea = open(dir, writeLock, false, depth); } catch (SVNException svne) { SVNFileType childKind = SVNFileType.getType(path); SVNErrorCode errCode = svne.getErrorMessage().getErrorCode(); if (!path.equals(dir) && childKind == SVNFileType.DIRECTORY && errCode == SVNErrorCode.WC_NOT_DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "''{0}'' is not a working copy", path); SVNErrorManager.error(err); } else { throw svne; } } return adminArea; } public SVNAdminArea probeTry(File path, boolean writeLock, int depth) throws SVNException { SVNAdminArea adminArea = null; try { adminArea = probeRetrieve(path); } catch (SVNException svne) { if (svne.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) { try { adminArea = probeOpen(path, writeLock, depth); } catch (SVNException svne2) { if (svne2.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_DIRECTORY) { throw svne2; } } } else { throw svne; } } return adminArea; } public void close() throws SVNException { if (myAdminAreas != null) { doClose(myAdminAreas, false); myAdminAreas.clear(); } } public void closeAdminArea(File path) throws SVNException { if (myAdminAreas != null) { SVNAdminArea area = (SVNAdminArea) myAdminAreas.get(path); if (area != null) { doClose(area, false); myAdminAreas.remove(path); } } } private SVNAdminArea doOpen(File path, boolean writeLock, boolean stealLock, int depth, Map tmp) throws SVNException { // no support for 'under consturction here' - it will go to adminAreaFactory. tmp = tmp == null ? new HashMap() : tmp; if (myAdminAreas != null) { SVNAdminArea existing = (SVNAdminArea) myAdminAreas.get(path); if (myAdminAreas.containsKey(path) && existing != null) { SVNErrorMessage error = SVNErrorMessage.create(SVNErrorCode.WC_LOCKED, "Working copy ''{0}'' locked", path); SVNErrorManager.error(error); } } else { myAdminAreas = new HashMap(); } SVNAdminArea area = SVNAdminAreaFactory.open(path); area.setWCAccess(this); if (writeLock) { area.lock(stealLock); area = SVNAdminAreaFactory.upgrade(area); } tmp.put(path, area); if (depth != 0) { if (depth > 0) { depth--; } for(Iterator entries = area.entries(false); entries.hasNext();) { try { checkCancelled(); } catch (SVNCancelException e) { doClose(tmp, false); throw e; } SVNEntry entry = (SVNEntry) entries.next(); if (entry.getKind() != SVNNodeKind.DIR || area.getThisDirName().equals(entry.getName())) { continue; } File childPath = new File(path, entry.getName()); try { // this method will put created area into our map. doOpen(childPath, writeLock, stealLock, depth, tmp); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_DIRECTORY) { doClose(tmp, false); throw e; } // only for missing! tmp.put(childPath, null); continue; } } } return area; } private void doClose(Map adminAreas, boolean preserveLocks) throws SVNException { for (Iterator paths = adminAreas.keySet().iterator(); paths.hasNext();) { File path = (File) paths.next(); SVNAdminArea adminArea = (SVNAdminArea) adminAreas.get(path); if (adminArea == null) { paths.remove(); continue; } doClose(adminArea, preserveLocks); paths.remove(); } } private void doClose(SVNAdminArea adminArea, boolean preserveLocks) throws SVNException { if (adminArea == null) { return; } if (!preserveLocks && adminArea.isLocked()) { adminArea.unlock(); } } public SVNAdminArea probeRetrieve(File path) throws SVNException { File dir = probe(path); return retrieve(dir); } public boolean isMissing(File path) { if (myAdminAreas != null) { return myAdminAreas.containsKey(path) && myAdminAreas.get(path) == null; } return false; } public boolean isLocked(File path) throws SVNException { File lockFile = new File(path, SVNFileUtil.getAdminDirectoryName()); lockFile = new File(lockFile, "lock"); if (SVNFileType.getType(lockFile) == SVNFileType.FILE) { return true; } else if (SVNFileType.getType(lockFile) == SVNFileType.NONE) { return false; } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_LOCKED, "Lock file ''{0}'' is not a regular file", lockFile); SVNErrorManager.error(err); return false; } public boolean isWCRoot(File path) throws SVNException { SVNEntry entry = getEntry(path, false); if (path.getParentFile() == null && entry != null) { return true; } SVNAdminArea parentArea = getAdminArea(path.getParentFile()); if (parentArea == null) { try { parentArea = probeOpen(path.getParentFile(), false, 0); } catch (SVNException svne) { return true; } } SVNEntry parentEntry = getEntry(path.getParentFile(), false); if (parentEntry == null) { return true; } if (parentEntry.getURL() == null) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ENTRY_MISSING_URL, "''{0}'' has no ancestry information", path.getParentFile()); SVNErrorManager.error(err); } // what about switched paths? /* if (entry != null && entry.getURL() != null) { if (!entry.getURL().equals(SVNPathUtil.append(parentEntry.getURL(), SVNEncodingUtil.uriEncode(path.getName())))) { return true; } }*/ entry = parentArea.getEntry(path.getName(), false); if (entry == null) { return true; } return false; } public SVNEntry getEntry(File path, boolean showHidden) throws SVNException { SVNAdminArea adminArea = getAdminArea(path); String entryName = null; if (adminArea == null) { adminArea = getAdminArea(path.getParentFile()); entryName = path.getName(); } else { entryName = adminArea.getThisDirName(); } if (adminArea != null) { return adminArea.getEntry(entryName, showHidden); } return null; } public void setRepositoryRoot(File path, SVNURL reposRoot) throws SVNException { SVNEntry entry = getEntry(path, false); if (entry == null) { return; } SVNAdminArea adminArea = null; String name = null; if (entry.isFile()) { adminArea = getAdminArea(path.getParentFile()); name = path.getName(); } else { adminArea = getAdminArea(path); name = adminArea != null ? adminArea.getThisDirName() : null; } if (adminArea == null) { return; } if (adminArea.tweakEntry(name, null, reposRoot.toString(), -1, false)) { adminArea.saveEntries(false); } } public SVNAdminArea[] getAdminAreas() { if (myAdminAreas != null) { return (SVNAdminArea[]) myAdminAreas.values().toArray(new SVNAdminArea[myAdminAreas.size()]); } return new SVNAdminArea[0]; } public SVNAdminArea retrieve(File path) throws SVNException { SVNAdminArea adminArea = getAdminArea(path); if (adminArea == null) { SVNEntry subEntry = null; try { SVNAdminArea dirAdminArea = getAdminArea(path.getParentFile()); if (dirAdminArea != null) { subEntry = dirAdminArea.getEntry(path.getName(), true); } } catch (SVNException svne) { subEntry = null; } SVNFileType type = SVNFileType.getType(path); if (subEntry != null) { if (subEntry.getKind() == SVNNodeKind.DIR && type == SVNFileType.FILE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Expected ''{0}'' to be a directory but found a file", path); SVNErrorManager.error(err); } else if (subEntry.getKind() == SVNNodeKind.FILE && type == SVNFileType.DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Expected ''{0}'' to be a file but found a directory", path); SVNErrorManager.error(err); } } File adminDir = new File(path, SVNFileUtil.getAdminDirectoryName()); SVNFileType wcType = SVNFileType.getType(adminDir); if (type == SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Directory ''{0}'' is missing", path); SVNErrorManager.error(err); } else if (type == SVNFileType.DIRECTORY && wcType == SVNFileType.NONE) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Directory ''{0}'' containing working copy admin area is missing", adminDir); SVNErrorManager.error(err); } else if (type == SVNFileType.DIRECTORY && wcType == SVNFileType.DIRECTORY) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Unable to lock ''{0}''", path); SVNErrorManager.error(err); } SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is not locked", path); SVNErrorManager.error(err); } return adminArea; } public static SVNExternalInfo[] parseExternals(String rootPath, String externals) { Collection result = new ArrayList(); if (externals == null) { return (SVNExternalInfo[]) result.toArray(new SVNExternalInfo[result.size()]); } for (StringTokenizer lines = new StringTokenizer(externals, "\n\r"); lines.hasMoreTokens();) { String line = lines.nextToken().trim(); if (line.length() == 0 || line.startsWith("#")) { continue; } String url = null; String path; long rev = -1; List parts = new ArrayList(4); for (StringTokenizer tokens = new StringTokenizer(line, " \t"); tokens .hasMoreTokens();) { String token = tokens.nextToken().trim(); parts.add(token); } if (parts.size() < 2) { continue; } path = SVNPathUtil.append(rootPath, (String) parts.get(0)); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } if (parts.size() == 2) { url = (String) parts.get(1); } else if (parts.size() == 3 && parts.get(1).toString().startsWith("-r")) { String revStr = parts.get(1).toString(); revStr = revStr.substring("-r".length()); if (!"HEAD".equals(revStr)) { try { rev = Long.parseLong(revStr); } catch (NumberFormatException nfe) { continue; } } url = (String) parts.get(2); } else if (parts.size() == 4 && "-r".equals(parts.get(1))) { String revStr = parts.get(2).toString(); if (!"HEAD".equals(revStr)) { try { rev = Long.parseLong(revStr); } catch (NumberFormatException nfe) { continue; } } url = (String) parts.get(3); } if (path != null && url != null) { if ("".equals(rootPath) && ((String) parts.get(0)).startsWith("/")) { path = "/" + path; } try { url = SVNURL.parseURIEncoded(url).toString(); } catch (SVNException e) { continue; } try { SVNExternalInfo info = new SVNExternalInfo("", null, path, SVNURL.parseURIEncoded(url), rev); result.add(info); } catch (SVNException e) { } } } return (SVNExternalInfo[]) result.toArray(new SVNExternalInfo[result.size()]); } //analogous to retrieve_internal public SVNAdminArea getAdminArea(File path) { //internal retrieve SVNAdminArea adminArea = null; if (myAdminAreas != null) { adminArea = (SVNAdminArea) myAdminAreas.get(path); } return adminArea; } private File probe(File path) throws SVNException { int wcFormat = -1; SVNFileType type = SVNFileType.getType(path); if (type == SVNFileType.DIRECTORY) { wcFormat = SVNAdminAreaFactory.checkWC(path, true); } else { wcFormat = 0; } //non wc if (type != SVNFileType.DIRECTORY || wcFormat == 0) { if ("..".equals(path.getName()) || ".".equals(path.getName())) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_BAD_PATH, "Path ''{0}'' ends in ''{1}'', which is unsupported for this operation", new Object[]{path, path.getName()}); SVNErrorManager.error(err); } path = path.getParentFile(); } return path; } }
true
true
public SVNAdminAreaInfo openAnchor(File path, boolean writeLock, int depth) throws SVNException { File parent = path.getParentFile(); if (parent == null) { SVNAdminArea anchor = open(path, writeLock, depth); return new SVNAdminAreaInfo(this, anchor, anchor, ""); } String name = path.getName(); SVNAdminArea parentArea = null; SVNAdminArea targetArea = null; SVNException parentError = null; try { parentArea = open(parent, writeLock, false, 0); } catch (SVNException svne) { if (writeLock && svne.getErrorMessage().getErrorCode() == SVNErrorCode.WC_LOCKED) { try { parentArea = open(parent, false, false, 0); } catch (SVNException svne2) { throw svne; } parentError = svne; } else if (svne.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_DIRECTORY) { throw svne; } } try { targetArea = open(path, writeLock, false, depth); } catch (SVNException svne) { if (parentArea == null || svne.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_DIRECTORY) { try { close(); } catch (SVNException svne2) { // } throw svne; } } if (parentArea != null && targetArea != null) { SVNEntry parentEntry = null; SVNEntry targetEntry = null; SVNEntry targetInParent = null; try { targetInParent = parentArea.getEntry(name, false); targetEntry = targetArea.getEntry(targetArea.getThisDirName(), false); parentEntry = parentArea.getEntry(parentArea.getThisDirName(), false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } SVNURL parentURL = parentEntry.getSVNURL(); SVNURL targetURL = targetEntry.getSVNURL(); String encodedName = SVNEncodingUtil.uriEncode(name); if (targetInParent == null || (parentURL != null && targetURL != null && (!parentURL.equals(targetURL.removePathTail()) || !encodedName.equals(SVNPathUtil.tail(targetURL.getPath()))))) { if (myAdminAreas != null) { myAdminAreas.remove(parent); } try { doClose(parentArea, false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } parentArea = null; } } if (parentArea != null) { if (parentError != null && targetArea != null) { try { close(); } catch (SVNException svne) { // } throw parentError; } } if (targetArea == null) { SVNEntry targetEntry = null; try { targetEntry = parentArea.getEntry(name, false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } if (targetEntry != null && targetEntry.isDirectory()) { if (myAdminAreas != null) { myAdminAreas.put(path, null); } } } SVNAdminArea anchor = parentArea != null ? parentArea : targetArea; SVNAdminArea target = targetArea != null ? targetArea : parentArea; return new SVNAdminAreaInfo(this, anchor, target, parentArea == null ? "" : name); }
public SVNAdminAreaInfo openAnchor(File path, boolean writeLock, int depth) throws SVNException { File parent = path.getParentFile(); if (parent == null) { SVNAdminArea anchor = open(path, writeLock, depth); return new SVNAdminAreaInfo(this, anchor, anchor, ""); } String name = path.getName(); SVNAdminArea parentArea = null; SVNAdminArea targetArea = null; SVNException parentError = null; try { parentArea = open(parent, writeLock, false, 0); } catch (SVNException svne) { if (writeLock && svne.getErrorMessage().getErrorCode() == SVNErrorCode.WC_LOCKED) { try { parentArea = open(parent, false, false, 0); } catch (SVNException svne2) { throw svne; } parentError = svne; } else if (svne.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_DIRECTORY) { throw svne; } } try { targetArea = open(path, writeLock, false, depth); } catch (SVNException svne) { if (parentArea == null || svne.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_DIRECTORY) { try { close(); } catch (SVNException svne2) { // } throw svne; } } if (parentArea != null && targetArea != null) { SVNEntry parentEntry = null; SVNEntry targetEntry = null; SVNEntry targetInParent = null; try { targetInParent = parentArea.getEntry(name, false); targetEntry = targetArea.getEntry(targetArea.getThisDirName(), false); parentEntry = parentArea.getEntry(parentArea.getThisDirName(), false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } SVNURL parentURL = parentEntry != null ? parentEntry.getSVNURL() : null; SVNURL targetURL = targetEntry != null ? targetEntry.getSVNURL() : null; String encodedName = SVNEncodingUtil.uriEncode(name); if (targetInParent == null || (parentURL != null && targetURL != null && (!parentURL.equals(targetURL.removePathTail()) || !encodedName.equals(SVNPathUtil.tail(targetURL.getPath()))))) { if (myAdminAreas != null) { myAdminAreas.remove(parent); } try { doClose(parentArea, false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } parentArea = null; } } if (parentArea != null) { if (parentError != null && targetArea != null) { try { close(); } catch (SVNException svne) { // } throw parentError; } } if (targetArea == null) { SVNEntry targetEntry = null; try { targetEntry = parentArea.getEntry(name, false); } catch (SVNException svne) { try { close(); } catch (SVNException svne2) { // } throw svne; } if (targetEntry != null && targetEntry.isDirectory()) { if (myAdminAreas != null) { myAdminAreas.put(path, null); } } } SVNAdminArea anchor = parentArea != null ? parentArea : targetArea; SVNAdminArea target = targetArea != null ? targetArea : parentArea; return new SVNAdminAreaInfo(this, anchor, target, parentArea == null ? "" : name); }
diff --git a/eXoApplication/wiki/service/src/main/java/org/exoplatform/wiki/rendering/render/confluence/ConfluenceResourceReferenceSerializer.java b/eXoApplication/wiki/service/src/main/java/org/exoplatform/wiki/rendering/render/confluence/ConfluenceResourceReferenceSerializer.java index 34cb7d73f..668df2cba 100644 --- a/eXoApplication/wiki/service/src/main/java/org/exoplatform/wiki/rendering/render/confluence/ConfluenceResourceReferenceSerializer.java +++ b/eXoApplication/wiki/service/src/main/java/org/exoplatform/wiki/rendering/render/confluence/ConfluenceResourceReferenceSerializer.java @@ -1,47 +1,47 @@ /* * Copyright (C) 2003-2011 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.wiki.rendering.render.confluence; import org.xwiki.component.annotation.Component; import org.xwiki.rendering.listener.reference.ResourceReference; import org.xwiki.rendering.renderer.reference.ResourceReferenceSerializer; /** * Created by The eXo Platform SAS * Author : Lai Trung Hieu * [email protected] * 9 Mar 2011 */ @Component("confluence/1.0/link") public class ConfluenceResourceReferenceSerializer implements ResourceReferenceSerializer { /** * Prefix to use for {@link org.xwiki.rendering.renderer.reference.ResourceReferenceTypeSerializer} role hints. */ private static final String COMPONENT_PREFIX = "confluence/1.0"; /** * {@inheritDoc} * * @see org.xwiki.rendering.renderer.reference.ResourceReferenceTypeSerializer */ @Override - public String serialize(ResourceReference reference) { - return reference.getReference().replace("|", "~|"); + public String serialize(ResourceReference reference) { + return COMPONENT_PREFIX + "/" + reference.getType().getScheme(); } }
true
true
public String serialize(ResourceReference reference) { return reference.getReference().replace("|", "~|"); }
public String serialize(ResourceReference reference) { return COMPONENT_PREFIX + "/" + reference.getType().getScheme(); }
diff --git a/java/Transxchange2GoogleTransit/src/transxchange2GoogleTransit/Transxchange2GoogleTransit.java b/java/Transxchange2GoogleTransit/src/transxchange2GoogleTransit/Transxchange2GoogleTransit.java index 985a5aa..fd74ac3 100755 --- a/java/Transxchange2GoogleTransit/src/transxchange2GoogleTransit/Transxchange2GoogleTransit.java +++ b/java/Transxchange2GoogleTransit/src/transxchange2GoogleTransit/Transxchange2GoogleTransit.java @@ -1,225 +1,225 @@ package transxchange2GoogleTransit; /* * Copyright 2007, 2008, 2009, 2010, 2011, 2012 GoogleTransitDataFeed * * 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. */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import transxchange2GoogleTransit.handler.NaPTANHelper; import transxchange2GoogleTransit.handler.TransxchangeHandler; /* * Transxchange2GTFS * $ transxchange2GoogleTransit <transxchange input filename> <url> <timezone> <default route type> <output-directory> <stopfile> * * <default route type>: 0 - Tram, 1 - Subway, 2 - Rail, 3 - Bus, 4 - Ferry, 5 - Cable car, 6 - Gondola, 7 - Funicular */ public class Transxchange2GoogleTransit { public static void main(String[] args) { TransxchangeHandler handler = null; Configuration config = new Configuration(); System.out.println("transxchange2GTFS 1.7.5"); System.out.println("Please refer to LICENSE file for licensing information"); int foundConfigFile = -1; int i = 0; while (i < args.length && foundConfigFile == -1) if (args[i].toLowerCase().equals("-c")) foundConfigFile = i; else i++; if (foundConfigFile == -1 && (args.length < 5 || args.length > 6) || foundConfigFile >= 0 && (args.length < 3 || args.length > 5)) { System.out.println(); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> -c <configuration file name>"); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> <output-directory> -c <configuration file name>"); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> <output-directory> <agency name> -c <configuration file name>"); - System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> -"); + System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> "); System.out.println(" <url> <timezone> <default route type> <output-directory> [<stopfile> [<lang> <phone>]]"); System.out.println(); System.out.println(" Please refer to "); System.out.println(" http://code.google.com/transit/spec/transit_feed_specification.html"); System.out.println(" for instructions about the values of the arguments <url>, <timezone>, <default route type>, <lang> and <phone>."); System.exit(1); } // Parse transxchange input file and create initial GTFS output files try { handler = new TransxchangeHandler(); // v1.6.4: Read configuration file if (args.length == 3){ config = readConfigFile(args[0], args[2]); } else if (args.length == 4 && foundConfigFile == 2) { String outdir = args[1]; config = readConfigFile(args[0], args[3]); config.outputDirectory = outdir;// Copy work directory over } else if (args.length == 5 && foundConfigFile == 3) { handler.setAgencyOverride(args[2]); String outdir = args[1]; config = readConfigFile(args[0], args[4]); config.outputDirectory = outdir; // Copy work directory over } else if (args.length == 8 || args.length == 6 || args.length == 5){ config.inputFileName = args[0]; config.url = args[1]; config.timezone = args[2]; config.defaultRouteType = args[3]; config.outputDirectory = args[4]; if (args.length >= 6){ config.stopFile = args[5]; if (args.length == 8){ config.lang = args[6]; config.phone = args[7]; } } } handler.parse(config); } catch (ParserConfigurationException e) { System.err.println("transxchange2GTFS ParserConfiguration parse error:"); e.printStackTrace(); System.exit(1); } catch (SAXException e) { System.err.println("transxchange2GTFS SAX parse error:"); e.printStackTrace(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.println("transxchange2GTFS NaPTAN stop file:"); e.printStackTrace(); System.exit(1); } catch (IOException e) { System.err.println("transxchange2GTFS IO parse error:"); e.printStackTrace(); System.exit(1); } // Create final GTFS output files try { handler.writeOutput(config); } catch (IOException e) { System.err.println("transxchange2GTFS write error:"); System.err.println(e.getMessage()); System.exit(1); } System.exit(0); } private static Configuration readConfigFile(String inputFileName, String configFilename) throws IOException { Configuration config = new Configuration(); config.inputFileName = inputFileName; BufferedReader in = new BufferedReader(new FileReader(configFilename)); String line; int tokenCount; String configValues[] = {"", "", ""}; // String tagToken = "", configurationValue; String txcMode = null; while ((line = in.readLine()) != null) { tokenCount = 0; StringTokenizer st = new StringTokenizer(line, "="); while (st.hasMoreTokens() && tokenCount <= 2) { configValues[tokenCount] = st.nextToken(); if (tokenCount == 1) { configValues[0] = configValues[0].trim().toLowerCase(); // configurationValue = st.nextToken().trim(); if (configValues[0].equals("url")) config.url = configValues[1]; if (configValues[0].equals("timezone")) config.timezone = configValues[1]; if (configValues[0].equals("default-route-type")) config.defaultRouteType = configValues[1]; if (configValues[0].equals("lang")) config.lang = configValues[1]; if (configValues[0].equals("phone")) config.phone = configValues[1]; if (configValues[0].equals("output-directory")) config.outputDirectory = configValues[1]; if (configValues[0].equals("stopfile")) { config.stopFile = configValues[1]; if (config.naptanStops == null) config.naptanStops = NaPTANHelper.readStopfile(configValues[1]); } if (configValues[0].equals("naptanstopcolumn")) { if (config.stopColumns == null) config.stopColumns = new ArrayList<String>(); config.stopColumns.add(configValues[1]); } if (configValues[0].equals("naptanstophelper")) if (config.stopColumns == null) config.naptanHelperStopColumn = 0; else config.naptanHelperStopColumn = config.stopColumns.size(); if (configValues[0].equals("stopfileColumnSeparator")) config.stopfileColumnSeparator = new String(configValues[1]); if (configValues[0].equals("useagencyshortname") && configValues[1] != null && configValues[1].trim().toLowerCase().equals("true")) config.useAgencyShortName = true; if (configValues[0].equals("skipemptyservice") && configValues[1] != null && configValues[1].trim().toLowerCase().equals("true")) config.skipEmptyService = true; if (configValues[0].equals("skiporphanstops") && configValues[1] != null && configValues[1].trim().toLowerCase().equals("true")) config.skipOrphanStops = true; if (configValues[0].equals("geocodemissingstops") && configValues[1] != null && configValues[1].trim().toLowerCase().equals("true")) config.geocodeMissingStops = true; if (txcMode != null) if (txcMode.length() > 0 && configValues[1].length() > 0) { if (config.modeList == null) config.modeList = new HashMap<String, String>(); config.modeList.put(txcMode, configValues[1]); } txcMode = null; } if (configValues[0].length() >= 7 && configValues[0].substring(0, 7).equals("agency:")) { configValues[1] = configValues[0].substring(7, configValues[0].length()); configValues[0] = "agency"; tokenCount++; } if (tokenCount == 2) { if (configValues[0].equals("agency")) { if (config.agencyMap == null) config.agencyMap = new HashMap<String, String>(); config.agencyMap.put(configValues[1], configValues[2]); } } if (configValues[0].length() >= 5 && configValues[0].substring(0, 5).equals("mode:")) txcMode = configValues[0].substring(5, configValues[0].length()); tokenCount++; } } in.close(); return config; } }
true
true
public static void main(String[] args) { TransxchangeHandler handler = null; Configuration config = new Configuration(); System.out.println("transxchange2GTFS 1.7.5"); System.out.println("Please refer to LICENSE file for licensing information"); int foundConfigFile = -1; int i = 0; while (i < args.length && foundConfigFile == -1) if (args[i].toLowerCase().equals("-c")) foundConfigFile = i; else i++; if (foundConfigFile == -1 && (args.length < 5 || args.length > 6) || foundConfigFile >= 0 && (args.length < 3 || args.length > 5)) { System.out.println(); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> -c <configuration file name>"); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> <output-directory> -c <configuration file name>"); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> <output-directory> <agency name> -c <configuration file name>"); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> -"); System.out.println(" <url> <timezone> <default route type> <output-directory> [<stopfile> [<lang> <phone>]]"); System.out.println(); System.out.println(" Please refer to "); System.out.println(" http://code.google.com/transit/spec/transit_feed_specification.html"); System.out.println(" for instructions about the values of the arguments <url>, <timezone>, <default route type>, <lang> and <phone>."); System.exit(1); } // Parse transxchange input file and create initial GTFS output files try { handler = new TransxchangeHandler(); // v1.6.4: Read configuration file if (args.length == 3){ config = readConfigFile(args[0], args[2]); } else if (args.length == 4 && foundConfigFile == 2) { String outdir = args[1]; config = readConfigFile(args[0], args[3]); config.outputDirectory = outdir;// Copy work directory over } else if (args.length == 5 && foundConfigFile == 3) { handler.setAgencyOverride(args[2]); String outdir = args[1]; config = readConfigFile(args[0], args[4]); config.outputDirectory = outdir; // Copy work directory over } else if (args.length == 8 || args.length == 6 || args.length == 5){ config.inputFileName = args[0]; config.url = args[1]; config.timezone = args[2]; config.defaultRouteType = args[3]; config.outputDirectory = args[4]; if (args.length >= 6){ config.stopFile = args[5]; if (args.length == 8){ config.lang = args[6]; config.phone = args[7]; } } } handler.parse(config); } catch (ParserConfigurationException e) { System.err.println("transxchange2GTFS ParserConfiguration parse error:"); e.printStackTrace(); System.exit(1); } catch (SAXException e) { System.err.println("transxchange2GTFS SAX parse error:"); e.printStackTrace(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.println("transxchange2GTFS NaPTAN stop file:"); e.printStackTrace(); System.exit(1); } catch (IOException e) { System.err.println("transxchange2GTFS IO parse error:"); e.printStackTrace(); System.exit(1); } // Create final GTFS output files try { handler.writeOutput(config); } catch (IOException e) { System.err.println("transxchange2GTFS write error:"); System.err.println(e.getMessage()); System.exit(1); } System.exit(0); }
public static void main(String[] args) { TransxchangeHandler handler = null; Configuration config = new Configuration(); System.out.println("transxchange2GTFS 1.7.5"); System.out.println("Please refer to LICENSE file for licensing information"); int foundConfigFile = -1; int i = 0; while (i < args.length && foundConfigFile == -1) if (args[i].toLowerCase().equals("-c")) foundConfigFile = i; else i++; if (foundConfigFile == -1 && (args.length < 5 || args.length > 6) || foundConfigFile >= 0 && (args.length < 3 || args.length > 5)) { System.out.println(); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> -c <configuration file name>"); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> <output-directory> -c <configuration file name>"); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> <output-directory> <agency name> -c <configuration file name>"); System.out.println("Usage: $ transxchange2GoogleTransit <transxchange input filename> "); System.out.println(" <url> <timezone> <default route type> <output-directory> [<stopfile> [<lang> <phone>]]"); System.out.println(); System.out.println(" Please refer to "); System.out.println(" http://code.google.com/transit/spec/transit_feed_specification.html"); System.out.println(" for instructions about the values of the arguments <url>, <timezone>, <default route type>, <lang> and <phone>."); System.exit(1); } // Parse transxchange input file and create initial GTFS output files try { handler = new TransxchangeHandler(); // v1.6.4: Read configuration file if (args.length == 3){ config = readConfigFile(args[0], args[2]); } else if (args.length == 4 && foundConfigFile == 2) { String outdir = args[1]; config = readConfigFile(args[0], args[3]); config.outputDirectory = outdir;// Copy work directory over } else if (args.length == 5 && foundConfigFile == 3) { handler.setAgencyOverride(args[2]); String outdir = args[1]; config = readConfigFile(args[0], args[4]); config.outputDirectory = outdir; // Copy work directory over } else if (args.length == 8 || args.length == 6 || args.length == 5){ config.inputFileName = args[0]; config.url = args[1]; config.timezone = args[2]; config.defaultRouteType = args[3]; config.outputDirectory = args[4]; if (args.length >= 6){ config.stopFile = args[5]; if (args.length == 8){ config.lang = args[6]; config.phone = args[7]; } } } handler.parse(config); } catch (ParserConfigurationException e) { System.err.println("transxchange2GTFS ParserConfiguration parse error:"); e.printStackTrace(); System.exit(1); } catch (SAXException e) { System.err.println("transxchange2GTFS SAX parse error:"); e.printStackTrace(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.println("transxchange2GTFS NaPTAN stop file:"); e.printStackTrace(); System.exit(1); } catch (IOException e) { System.err.println("transxchange2GTFS IO parse error:"); e.printStackTrace(); System.exit(1); } // Create final GTFS output files try { handler.writeOutput(config); } catch (IOException e) { System.err.println("transxchange2GTFS write error:"); System.err.println(e.getMessage()); System.exit(1); } System.exit(0); }
diff --git a/src/me/libraryaddict/Hungergames/Managers/PlayerManager.java b/src/me/libraryaddict/Hungergames/Managers/PlayerManager.java index 02a33e8..34dc581 100644 --- a/src/me/libraryaddict/Hungergames/Managers/PlayerManager.java +++ b/src/me/libraryaddict/Hungergames/Managers/PlayerManager.java @@ -1,288 +1,288 @@ package me.libraryaddict.Hungergames.Managers; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.ConcurrentLinkedQueue; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.BlockFace; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Ocelot; import org.bukkit.entity.Player; import org.bukkit.entity.Tameable; import org.bukkit.entity.Wolf; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.util.Vector; import me.libraryaddict.Hungergames.Hungergames; import me.libraryaddict.Hungergames.Events.PlayerKilledEvent; import me.libraryaddict.Hungergames.Types.Damage; import me.libraryaddict.Hungergames.Types.HungergamesApi; import me.libraryaddict.Hungergames.Types.Gamer; public class PlayerManager { public static int returnChance(int start, int end) { return start + (int) (Math.random() * ((end - start) + 1)); } private TranslationManager cm = HungergamesApi.getTranslationManager(); private ConcurrentLinkedQueue<Gamer> gamers = new ConcurrentLinkedQueue<Gamer>(); private Hungergames hg = HungergamesApi.getHungergames(); private KitManager kits = HungergamesApi.getKitManager(); public HashMap<Gamer, Damage> lastDamager = new HashMap<Gamer, Damage>(); public ConcurrentLinkedQueue<Gamer> loadGamer = new ConcurrentLinkedQueue<Gamer>(); private ArrayList<Integer> nonSolid = new ArrayList<Integer>(); private Iterator<Location> spawnItel; private HashMap<Location, Integer[]> spawns = new HashMap<Location, Integer[]>(); public PlayerManager() { nonSolid.add(0); for (int b = 8; b < 12; b++) nonSolid.add(b); nonSolid.add(Material.SNOW.getId()); nonSolid.add(Material.LONG_GRASS.getId()); nonSolid.add(Material.RED_MUSHROOM.getId()); nonSolid.add(Material.RED_ROSE.getId()); nonSolid.add(Material.YELLOW_FLOWER.getId()); nonSolid.add(Material.BROWN_MUSHROOM.getId()); nonSolid.add(Material.SIGN_POST.getId()); nonSolid.add(Material.WALL_SIGN.getId()); nonSolid.add(Material.FIRE.getId()); nonSolid.add(Material.TORCH.getId()); nonSolid.add(Material.REDSTONE_WIRE.getId()); nonSolid.add(Material.REDSTONE_TORCH_OFF.getId()); nonSolid.add(Material.REDSTONE_TORCH_ON.getId()); nonSolid.add(Material.VINE.getId()); } public void addSpawnPoint(Location loc, int radius, int height) { spawns.put(loc, new Integer[] { radius, height }); } private String formatDeathMessage(String deathMessage, Player p) { String kitName = cm.getKillMessageNoKit(); if (kits.getKitByPlayer(p) != null) kitName = kits.getKitByPlayer(p).getName(); return deathMessage.replaceAll(p.getName(), String.format(cm.getKillMessageFormatPlayerKit(), p.getName(), kitName)); } public List<Gamer> getAliveGamers() { List<Gamer> aliveGamers = new ArrayList<Gamer>(); for (Gamer gamer : gamers) if (gamer.isAlive()) aliveGamers.add(gamer); return aliveGamers; } public synchronized Gamer getGamer(Entity entity) { for (Gamer g : gamers) if (g.getPlayer() == entity) return g; return null; } public synchronized Gamer getGamer(String name) { for (Gamer g : gamers) if (g.getName().equals(name)) return g; return null; } public List<Gamer> getGamers() { List<Gamer> game = new ArrayList<Gamer>(); for (Gamer g : gamers) game.add(g); return game; } public Gamer getKiller(Gamer victim) { Damage dmg = lastDamager.get(victim); Gamer backup = null; if (dmg != null) if (dmg.getTime() >= System.currentTimeMillis()) backup = dmg.getDamager(); return backup; } public void killPlayer(Gamer gamer, Entity killer, Location dropLoc, List<ItemStack> drops, String deathMsg) { if (!hg.doSeconds || hg.currentTime < 0) return; PlayerKilledEvent event = new PlayerKilledEvent(gamer, killer, getKiller(gamer), deathMsg, dropLoc, drops); Bukkit.getPluginManager().callEvent(event); manageDeath(event); } public void manageDeath(PlayerKilledEvent event) { Gamer killed = event.getKilled(); final Player p = killed.getPlayer(); p.setHealth(20); if (event.isCancelled()) return; for (HumanEntity human : p.getInventory().getViewers()) human.closeInventory(); p.leaveVehicle(); p.eject(); p.setLevel(0); p.setExp(0F); if (event.getDeathMessage().equals(ChatColor.stripColor(event.getDeathMessage()))) - event.setDeathMessage(ChatColor.DARK_RED - + event.getDeathMessage().replace("%Remaining%", "" + (getAliveGamers().size() - 1))); - event.setDeathMessage(this.formatDeathMessage(event.getDeathMessage(), p)); + event.setDeathMessage(ChatColor.DARK_RED + event.getDeathMessage()); + event.setDeathMessage(this.formatDeathMessage( + event.getDeathMessage().replace("%Remaining%", "" + (getAliveGamers().size() - 1)), p)); if (event.getKillerPlayer() != null) { event.getKillerPlayer().addKill(); event.setDeathMessage(this.formatDeathMessage(event.getDeathMessage(), event.getKillerPlayer().getPlayer())); } Bukkit.broadcastMessage(event.getDeathMessage()); int reward = hg.getPrize(getAliveGamers().size()); if (reward > 0) killed.addBalance(reward); hg.cannon(); killed.clearInventory(); World world = p.getWorld(); for (ItemStack item : event.getDrops()) { if (item == null || item.getType() == Material.AIR || item.containsEnchantment(EnchantmentManager.UNLOOTABLE)) continue; else if (item.hasItemMeta()) world.dropItemNaturally(event.getDropsLocation(), item.clone()).getItemStack().setItemMeta(item.getItemMeta()); else world.dropItemNaturally(event.getDropsLocation(), item); } setSpectator(killed); ScoreboardManager.makeScore("Main", DisplaySlot.SIDEBAR, cm.getScoreboardPlayersLength(), getAliveGamers().size()); hg.checkWinner(); p.setVelocity(new Vector()); for (PotionEffect effect : p.getActivePotionEffects()) p.removePotionEffect(effect.getType()); p.teleport(p.getWorld().getHighestBlockAt(p.getLocation()).getLocation().clone().add(0, 10, 0)); p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 40, 9), true); p.sendBlockChange(p.getLocation(), Material.PORTAL.getId(), (byte) 0); p.sendBlockChange(p.getLocation(), Material.AIR.getId(), (byte) 0); for (Entity entity : p.getWorld().getEntities()) { if (entity instanceof Tameable && ((Tameable) entity).isTamed() && ((Tameable) entity).getOwner().getName().equals(p.getName())) { if (entity instanceof Wolf) ((Wolf) entity).setSitting(true); else if (entity instanceof Ocelot) ((Ocelot) entity).setSitting(true); else entity.remove(); } if (entity instanceof Creature && ((Creature) entity).getTarget() == p) ((Creature) entity).setTarget(null); } if (HungergamesApi.getConfigManager().isKickOnDeath() && !p.hasPermission("hungergames.spectate")) p.kickPlayer(String.format(HungergamesApi.getTranslationManager().getKickDeathMessage(), event.getDeathMessage())); HungergamesApi.getAbilityManager().unregisterPlayer(p); HungergamesApi.getInventoryManager().updateSpectatorHeads(); } public Gamer registerGamer(Player p) { Gamer gamer = new Gamer(p); gamers.add(gamer); return gamer; } public void removeKilled(Gamer gamer) { lastDamager.remove(gamer); Iterator<Gamer> itel = lastDamager.keySet().iterator(); while (itel.hasNext()) { Gamer g = itel.next(); if (lastDamager.get(g).getDamager() == gamer) itel.remove(); } } public void sendToSpawn(Gamer gamer) { final Player p = gamer.getPlayer(); Location originalSpawn = p.getWorld().getSpawnLocation(); int spawnRadius = 8; int spawnHeight = 5; if (spawns.size() > 0) { if (spawnItel == null || !spawnItel.hasNext()) spawnItel = spawns.keySet().iterator(); originalSpawn = spawnItel.next(); spawnRadius = spawns.get(originalSpawn)[0]; spawnHeight = spawns.get(originalSpawn)[1]; } Location spawn = originalSpawn.clone(); int chances = 0; if (p.isInsideVehicle()) p.leaveVehicle(); p.eject(); while (chances < 100) { chances++; Location newLoc = new Location(p.getWorld(), spawn.getX() + returnChance(-spawnRadius, spawnRadius), spawn.getY() + new Random().nextInt(spawnHeight), spawn.getZ() + returnChance(-spawnRadius, spawnRadius)); if (nonSolid.contains(newLoc.getBlock().getTypeId()) && nonSolid.contains(newLoc.getBlock().getRelative(BlockFace.UP).getTypeId())) { while (newLoc.getBlockY() >= 1 && nonSolid.contains(newLoc.getBlock().getRelative(BlockFace.DOWN).getTypeId())) { newLoc = newLoc.add(0, -1, 0); } if (newLoc.getBlockY() <= 1) continue; spawn = newLoc; break; } } if (spawn.equals(originalSpawn)) { spawn = new Location(p.getWorld(), spawn.getX() + returnChance(-spawnRadius, spawnRadius), 0, spawn.getZ() + returnChance(-spawnRadius, spawnRadius)); spawn.setY(spawn.getWorld().getHighestBlockYAt(spawn)); if (gamer.isAlive() && spawn.getY() <= 1) { spawn.getBlock().setType(Material.GLASS); spawn.setY(spawn.getY() + 1); } } final Location destination = spawn.add(0.5, 0.1, 0.5); p.teleport(destination); Bukkit.getScheduler().scheduleSyncDelayedTask(hg, new Runnable() { public void run() { p.teleport(destination); } }); } public void setSpectator(final Gamer gamer) { gamer.setAlive(false); gamer.getPlayer().getInventory().remove(HungergamesApi.getInventoryManager().getKitSelector()); Bukkit.getScheduler().scheduleSyncDelayedTask(hg, new Runnable() { public void run() { ItemStack compass = new ItemStack(Material.COMPASS); compass.addEnchantment(EnchantmentManager.UNDROPPABLE, 1); EnchantmentManager.updateEnchants(compass); if (!gamer.getPlayer().getInventory().contains(compass)) gamer.getPlayer().getInventory().addItem(compass); } }); } public Gamer unregisterGamer(Entity entity) { Iterator<Gamer> itel = gamers.iterator(); while (itel.hasNext()) { Gamer g = itel.next(); if (g.getPlayer() == entity) { itel.remove(); return g; } } return null; } public void unregisterGamer(Gamer gamer) { gamers.remove(gamer); } }
true
true
public void manageDeath(PlayerKilledEvent event) { Gamer killed = event.getKilled(); final Player p = killed.getPlayer(); p.setHealth(20); if (event.isCancelled()) return; for (HumanEntity human : p.getInventory().getViewers()) human.closeInventory(); p.leaveVehicle(); p.eject(); p.setLevel(0); p.setExp(0F); if (event.getDeathMessage().equals(ChatColor.stripColor(event.getDeathMessage()))) event.setDeathMessage(ChatColor.DARK_RED + event.getDeathMessage().replace("%Remaining%", "" + (getAliveGamers().size() - 1))); event.setDeathMessage(this.formatDeathMessage(event.getDeathMessage(), p)); if (event.getKillerPlayer() != null) { event.getKillerPlayer().addKill(); event.setDeathMessage(this.formatDeathMessage(event.getDeathMessage(), event.getKillerPlayer().getPlayer())); } Bukkit.broadcastMessage(event.getDeathMessage()); int reward = hg.getPrize(getAliveGamers().size()); if (reward > 0) killed.addBalance(reward); hg.cannon(); killed.clearInventory(); World world = p.getWorld(); for (ItemStack item : event.getDrops()) { if (item == null || item.getType() == Material.AIR || item.containsEnchantment(EnchantmentManager.UNLOOTABLE)) continue; else if (item.hasItemMeta()) world.dropItemNaturally(event.getDropsLocation(), item.clone()).getItemStack().setItemMeta(item.getItemMeta()); else world.dropItemNaturally(event.getDropsLocation(), item); } setSpectator(killed); ScoreboardManager.makeScore("Main", DisplaySlot.SIDEBAR, cm.getScoreboardPlayersLength(), getAliveGamers().size()); hg.checkWinner(); p.setVelocity(new Vector()); for (PotionEffect effect : p.getActivePotionEffects()) p.removePotionEffect(effect.getType()); p.teleport(p.getWorld().getHighestBlockAt(p.getLocation()).getLocation().clone().add(0, 10, 0)); p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 40, 9), true); p.sendBlockChange(p.getLocation(), Material.PORTAL.getId(), (byte) 0); p.sendBlockChange(p.getLocation(), Material.AIR.getId(), (byte) 0); for (Entity entity : p.getWorld().getEntities()) { if (entity instanceof Tameable && ((Tameable) entity).isTamed() && ((Tameable) entity).getOwner().getName().equals(p.getName())) { if (entity instanceof Wolf) ((Wolf) entity).setSitting(true); else if (entity instanceof Ocelot) ((Ocelot) entity).setSitting(true); else entity.remove(); } if (entity instanceof Creature && ((Creature) entity).getTarget() == p) ((Creature) entity).setTarget(null); } if (HungergamesApi.getConfigManager().isKickOnDeath() && !p.hasPermission("hungergames.spectate")) p.kickPlayer(String.format(HungergamesApi.getTranslationManager().getKickDeathMessage(), event.getDeathMessage())); HungergamesApi.getAbilityManager().unregisterPlayer(p); HungergamesApi.getInventoryManager().updateSpectatorHeads(); }
public void manageDeath(PlayerKilledEvent event) { Gamer killed = event.getKilled(); final Player p = killed.getPlayer(); p.setHealth(20); if (event.isCancelled()) return; for (HumanEntity human : p.getInventory().getViewers()) human.closeInventory(); p.leaveVehicle(); p.eject(); p.setLevel(0); p.setExp(0F); if (event.getDeathMessage().equals(ChatColor.stripColor(event.getDeathMessage()))) event.setDeathMessage(ChatColor.DARK_RED + event.getDeathMessage()); event.setDeathMessage(this.formatDeathMessage( event.getDeathMessage().replace("%Remaining%", "" + (getAliveGamers().size() - 1)), p)); if (event.getKillerPlayer() != null) { event.getKillerPlayer().addKill(); event.setDeathMessage(this.formatDeathMessage(event.getDeathMessage(), event.getKillerPlayer().getPlayer())); } Bukkit.broadcastMessage(event.getDeathMessage()); int reward = hg.getPrize(getAliveGamers().size()); if (reward > 0) killed.addBalance(reward); hg.cannon(); killed.clearInventory(); World world = p.getWorld(); for (ItemStack item : event.getDrops()) { if (item == null || item.getType() == Material.AIR || item.containsEnchantment(EnchantmentManager.UNLOOTABLE)) continue; else if (item.hasItemMeta()) world.dropItemNaturally(event.getDropsLocation(), item.clone()).getItemStack().setItemMeta(item.getItemMeta()); else world.dropItemNaturally(event.getDropsLocation(), item); } setSpectator(killed); ScoreboardManager.makeScore("Main", DisplaySlot.SIDEBAR, cm.getScoreboardPlayersLength(), getAliveGamers().size()); hg.checkWinner(); p.setVelocity(new Vector()); for (PotionEffect effect : p.getActivePotionEffects()) p.removePotionEffect(effect.getType()); p.teleport(p.getWorld().getHighestBlockAt(p.getLocation()).getLocation().clone().add(0, 10, 0)); p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 40, 9), true); p.sendBlockChange(p.getLocation(), Material.PORTAL.getId(), (byte) 0); p.sendBlockChange(p.getLocation(), Material.AIR.getId(), (byte) 0); for (Entity entity : p.getWorld().getEntities()) { if (entity instanceof Tameable && ((Tameable) entity).isTamed() && ((Tameable) entity).getOwner().getName().equals(p.getName())) { if (entity instanceof Wolf) ((Wolf) entity).setSitting(true); else if (entity instanceof Ocelot) ((Ocelot) entity).setSitting(true); else entity.remove(); } if (entity instanceof Creature && ((Creature) entity).getTarget() == p) ((Creature) entity).setTarget(null); } if (HungergamesApi.getConfigManager().isKickOnDeath() && !p.hasPermission("hungergames.spectate")) p.kickPlayer(String.format(HungergamesApi.getTranslationManager().getKickDeathMessage(), event.getDeathMessage())); HungergamesApi.getAbilityManager().unregisterPlayer(p); HungergamesApi.getInventoryManager().updateSpectatorHeads(); }
diff --git a/widgets/src/java/org/sakaiproject/jsf/renderer/ToolBarRenderer.java b/widgets/src/java/org/sakaiproject/jsf/renderer/ToolBarRenderer.java index d282ff3..0652342 100644 --- a/widgets/src/java/org/sakaiproject/jsf/renderer/ToolBarRenderer.java +++ b/widgets/src/java/org/sakaiproject/jsf/renderer/ToolBarRenderer.java @@ -1,60 +1,64 @@ /********************************************************************************** * * Header: * *********************************************************************************** * * Copyright (c) 2003, 2004 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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.sakaiproject.jsf.renderer; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.Renderer; /** * <p>This does not render children, but can deal with children by surrounding them in a comment.</p> * */ public class ToolBarRenderer extends Renderer { public boolean supportsComponentType(UIComponent component) { return (component instanceof org.sakaiproject.jsf.component.ToolBarComponent); } public void encodeBegin(FacesContext context, UIComponent component) throws IOException { + if(!component.isRendered()){ + //tool_bar tag is not to be rendered, return now + return; + } ResponseWriter writer = context.getResponseWriter(); writer.write("<div class=\"navIntraTool\">"); return; } public void encodeEnd(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.write("</div>"); } }
true
true
public void encodeBegin(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.write("<div class=\"navIntraTool\">"); return; }
public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if(!component.isRendered()){ //tool_bar tag is not to be rendered, return now return; } ResponseWriter writer = context.getResponseWriter(); writer.write("<div class=\"navIntraTool\">"); return; }
diff --git a/broker-tests/src/pt/com/broker/functests/negative/MessegeOversizedTest.java b/broker-tests/src/pt/com/broker/functests/negative/MessegeOversizedTest.java index 7c3b1eda..1afe28ee 100644 --- a/broker-tests/src/pt/com/broker/functests/negative/MessegeOversizedTest.java +++ b/broker-tests/src/pt/com/broker/functests/negative/MessegeOversizedTest.java @@ -1,19 +1,19 @@ package pt.com.broker.functests.negative; import pt.com.broker.functests.helpers.GenericNegativeTest; public class MessegeOversizedTest extends GenericNegativeTest { public MessegeOversizedTest() { super("Message oversize"); setDataToSend(new byte[] { 0, (byte) getEncodingProtocolType().ordinal(), 0, 0, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0, 0 }); setFaultCode("1101"); setFaultMessage("Invalid message size"); - //setOkToTimeOut(true); + setOkToTimeOut(true); } }
true
true
public MessegeOversizedTest() { super("Message oversize"); setDataToSend(new byte[] { 0, (byte) getEncodingProtocolType().ordinal(), 0, 0, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0, 0 }); setFaultCode("1101"); setFaultMessage("Invalid message size"); //setOkToTimeOut(true); }
public MessegeOversizedTest() { super("Message oversize"); setDataToSend(new byte[] { 0, (byte) getEncodingProtocolType().ordinal(), 0, 0, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0, 0 }); setFaultCode("1101"); setFaultMessage("Invalid message size"); setOkToTimeOut(true); }
diff --git a/nuxeo-core-persistence/src/main/java/org/nuxeo/ecm/core/persistence/HibernateConfiguration.java b/nuxeo-core-persistence/src/main/java/org/nuxeo/ecm/core/persistence/HibernateConfiguration.java index e247f6e08..9189388c5 100644 --- a/nuxeo-core-persistence/src/main/java/org/nuxeo/ecm/core/persistence/HibernateConfiguration.java +++ b/nuxeo-core-persistence/src/main/java/org/nuxeo/ecm/core/persistence/HibernateConfiguration.java @@ -1,248 +1,254 @@ /* * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * "Stephane Lacoin (aka matic) <[email protected]>" */ package org.nuxeo.ecm.core.persistence; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.naming.NamingException; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceUnitTransactionType; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.ejb.HibernatePersistence; import org.hibernate.ejb.transaction.JoinableCMTTransactionFactory; import org.hibernate.transaction.JDBCTransactionFactory; import org.hibernate.transaction.TransactionManagerLookup; import org.nuxeo.common.xmap.XMap; import org.nuxeo.common.xmap.annotation.XNode; import org.nuxeo.common.xmap.annotation.XNodeList; import org.nuxeo.common.xmap.annotation.XNodeMap; import org.nuxeo.common.xmap.annotation.XObject; import org.nuxeo.runtime.api.DataSourceHelper; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.transaction.TransactionHelper; /** * @author "Stephane Lacoin (aka matic) <[email protected]>" */ @XObject("hibernateConfiguration") public class HibernateConfiguration implements EntityManagerFactoryProvider { public static final String RESOURCE_LOCAL = PersistenceUnitTransactionType.RESOURCE_LOCAL.name(); public static final String JTA = PersistenceUnitTransactionType.JTA.name(); public static final String TXTYPE_PROPERTY_NAME = "org.nuxeo.runtime.txType"; private static final Log log = LogFactory.getLog(HibernateConfiguration.class); @XNode("@name") public String name; @XNode("datasource") public void setDatasource(String name) { String expandedValue = Framework.expandVars(name); if (expandedValue.startsWith("$")) { throw new PersistenceError("Cannot expand " + name + " for datasource"); } hibernateProperties.put("hibernate.connection.datasource", DataSourceHelper.getDataSourceJNDIName(name)); } @XNodeMap(value = "properties/property", key = "@name", type = Properties.class, componentType = String.class) public final Properties hibernateProperties = new Properties(); @XNodeList(value = "classes/class", type = ArrayList.class, componentType = Class.class) public final List<Class<?>> annotedClasses = new ArrayList<Class<?>>(); public void addAnnotedClass(Class<?> annotedClass) { annotedClasses.add(annotedClass); } public void removeAnnotedClass(Class<?> annotedClass) { annotedClasses.remove(annotedClass); } protected Ejb3Configuration cfg; public Ejb3Configuration setupConfiguration() { return setupConfiguration(null); } public Ejb3Configuration setupConfiguration(Map<String, String> properties) { cfg = new Ejb3Configuration(); if (properties!=null) { cfg.configure(name, properties); } else { cfg.configure(name, Collections.emptyMap()); } // Load hibernate properties cfg.addProperties(hibernateProperties); // Add annnoted classes if any for (Class<?> annotedClass : annotedClasses) { cfg.addAnnotatedClass(annotedClass); } return cfg; } @Override public EntityManagerFactory getFactory(String txType) { Map<String, String> properties = new HashMap<String, String>(); if (txType == null) { txType = getTxType(); } properties.put(HibernatePersistence.TRANSACTION_TYPE, txType); if (txType.equals(JTA)) { Class<?> klass; try { // Hibernate 4.1 klass = Class.forName("org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory"); } catch (ClassNotFoundException e) { // Hibernate 3.4 klass = JoinableCMTTransactionFactory.class; } properties.put(Environment.TRANSACTION_STRATEGY, klass.getName()); properties.put(Environment.TRANSACTION_MANAGER_STRATEGY, NuxeoTransactionManagerLookup.class.getName()); } else if (txType.equals(RESOURCE_LOCAL)) { properties.put(Environment.TRANSACTION_STRATEGY, JDBCTransactionFactory.class.getName()); } - properties.put(Environment.CONNECTION_PROVIDER, - NuxeoConnectionProvider.class.getName()); if (cfg == null) { setupConfiguration(properties); } + Properties props = cfg.getProperties(); + if (props.get(Environment.URL) == null) { + // don't set up our connection provider for unit tests + // that use an explicit driver + connection URL and so use + // a DriverManagerConnectionProvider + props.put(Environment.CONNECTION_PROVIDER, + NuxeoConnectionProvider.class.getName()); + } if (txType.equals(RESOURCE_LOCAL)) { - cfg.getProperties().remove(Environment.DATASOURCE); + props.remove(Environment.DATASOURCE); } return createEntityManagerFactory(properties); } // this must be executed always outside a transaction // because SchemaUpdate tries to setAutoCommit(true) // so we use a new thread protected EntityManagerFactory createEntityManagerFactory( final Map<String, String> properties) { final EntityManagerFactory[] emf = new EntityManagerFactory[1]; Thread t = new Thread() { @SuppressWarnings("deprecation") @Override public void run() { emf[0] = cfg.createEntityManagerFactory(properties); }; }; try { t.start(); t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } return emf[0]; } /** * Hibernate Transaction Manager Lookup that uses our framework. */ public static class NuxeoTransactionManagerLookup implements TransactionManagerLookup { public NuxeoTransactionManagerLookup() { // look up UserTransaction once to know its JNDI name try { TransactionHelper.lookupUserTransaction(); } catch (NamingException e) { // ignore } } @Override public TransactionManager getTransactionManager(Properties props) { try { return TransactionHelper.lookupTransactionManager(); } catch (NamingException e) { throw new HibernateException(e.getMessage(), e); } } @Override public String getUserTransactionName() { return TransactionHelper.getUserTransactionJNDIName(); } @Override public Object getTransactionIdentifier(Transaction transaction) { return transaction; } } @Override public EntityManagerFactory getFactory() { return getFactory(null); } public static String getTxType() { String txType; if (Framework.isInitialized()) { txType = Framework.getProperty(TXTYPE_PROPERTY_NAME); if (txType == null) { try { TransactionHelper.lookupTransactionManager(); txType = JTA; } catch (NamingException e) { txType = RESOURCE_LOCAL; } } } else { txType = RESOURCE_LOCAL; } return txType; } public static HibernateConfiguration load(URL location) { XMap map = new XMap(); map.register(HibernateConfiguration.class); try { return (HibernateConfiguration) map.load(location); } catch (Exception e) { throw new PersistenceError( "Cannot load hibernate configuration from " + location, e); } } public void merge(HibernateConfiguration other) { assert name.equals(other.name) : " cannot merge configuration that do not have the same persistence unit"; annotedClasses.addAll(other.annotedClasses); hibernateProperties.clear(); hibernateProperties.putAll(other.hibernateProperties); } }
false
true
public EntityManagerFactory getFactory(String txType) { Map<String, String> properties = new HashMap<String, String>(); if (txType == null) { txType = getTxType(); } properties.put(HibernatePersistence.TRANSACTION_TYPE, txType); if (txType.equals(JTA)) { Class<?> klass; try { // Hibernate 4.1 klass = Class.forName("org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory"); } catch (ClassNotFoundException e) { // Hibernate 3.4 klass = JoinableCMTTransactionFactory.class; } properties.put(Environment.TRANSACTION_STRATEGY, klass.getName()); properties.put(Environment.TRANSACTION_MANAGER_STRATEGY, NuxeoTransactionManagerLookup.class.getName()); } else if (txType.equals(RESOURCE_LOCAL)) { properties.put(Environment.TRANSACTION_STRATEGY, JDBCTransactionFactory.class.getName()); } properties.put(Environment.CONNECTION_PROVIDER, NuxeoConnectionProvider.class.getName()); if (cfg == null) { setupConfiguration(properties); } if (txType.equals(RESOURCE_LOCAL)) { cfg.getProperties().remove(Environment.DATASOURCE); } return createEntityManagerFactory(properties); }
public EntityManagerFactory getFactory(String txType) { Map<String, String> properties = new HashMap<String, String>(); if (txType == null) { txType = getTxType(); } properties.put(HibernatePersistence.TRANSACTION_TYPE, txType); if (txType.equals(JTA)) { Class<?> klass; try { // Hibernate 4.1 klass = Class.forName("org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory"); } catch (ClassNotFoundException e) { // Hibernate 3.4 klass = JoinableCMTTransactionFactory.class; } properties.put(Environment.TRANSACTION_STRATEGY, klass.getName()); properties.put(Environment.TRANSACTION_MANAGER_STRATEGY, NuxeoTransactionManagerLookup.class.getName()); } else if (txType.equals(RESOURCE_LOCAL)) { properties.put(Environment.TRANSACTION_STRATEGY, JDBCTransactionFactory.class.getName()); } if (cfg == null) { setupConfiguration(properties); } Properties props = cfg.getProperties(); if (props.get(Environment.URL) == null) { // don't set up our connection provider for unit tests // that use an explicit driver + connection URL and so use // a DriverManagerConnectionProvider props.put(Environment.CONNECTION_PROVIDER, NuxeoConnectionProvider.class.getName()); } if (txType.equals(RESOURCE_LOCAL)) { props.remove(Environment.DATASOURCE); } return createEntityManagerFactory(properties); }
diff --git a/xwiki-commons-core/xwiki-commons-script/src/main/java/org/xwiki/script/internal/service/DefaultScriptServiceManager.java b/xwiki-commons-core/xwiki-commons-script/src/main/java/org/xwiki/script/internal/service/DefaultScriptServiceManager.java index 26c1fee3a..7b24a7e5c 100644 --- a/xwiki-commons-core/xwiki-commons-script/src/main/java/org/xwiki/script/internal/service/DefaultScriptServiceManager.java +++ b/xwiki-commons-core/xwiki-commons-script/src/main/java/org/xwiki/script/internal/service/DefaultScriptServiceManager.java @@ -1,75 +1,75 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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.xwiki.script.internal.service; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; import org.slf4j.Logger; import org.xwiki.component.annotation.Component; import org.xwiki.component.manager.ComponentManager; import org.xwiki.script.service.ScriptService; import org.xwiki.script.service.ScriptServiceManager; /** * Locate Script Services by name dynamically at runtime by looking them up agains the Component Manager. * * @version $Id$ * @since 2.3M1 */ @Component @Singleton public class DefaultScriptServiceManager implements ScriptServiceManager { /** * Used to locate Script Services dynamically. Note that since the lookup is done dynamically new Script Services * can be added on the fly in the classloader and they'll be found (after they've been registered against the * component manager obviously). */ @Inject @Named("context") private Provider<ComponentManager> componentManager; /** * The logger to log. */ @Inject private Logger logger; @Override public ScriptService get(String serviceName) { ScriptService scriptService = null; if (this.componentManager.get().hasComponent(ScriptService.class, serviceName)) { try { scriptService = this.componentManager.get().getInstance(ScriptService.class, serviceName); } catch (Exception e) { this.logger.error("Failed to lookup script service for role hint [{}]", serviceName, e); } } else { - this.logger.debug("No script service registred for role hint [{}]", serviceName); + this.logger.debug("No script service registered for role hint [{}]", serviceName); } return scriptService; } }
true
true
public ScriptService get(String serviceName) { ScriptService scriptService = null; if (this.componentManager.get().hasComponent(ScriptService.class, serviceName)) { try { scriptService = this.componentManager.get().getInstance(ScriptService.class, serviceName); } catch (Exception e) { this.logger.error("Failed to lookup script service for role hint [{}]", serviceName, e); } } else { this.logger.debug("No script service registred for role hint [{}]", serviceName); } return scriptService; }
public ScriptService get(String serviceName) { ScriptService scriptService = null; if (this.componentManager.get().hasComponent(ScriptService.class, serviceName)) { try { scriptService = this.componentManager.get().getInstance(ScriptService.class, serviceName); } catch (Exception e) { this.logger.error("Failed to lookup script service for role hint [{}]", serviceName, e); } } else { this.logger.debug("No script service registered for role hint [{}]", serviceName); } return scriptService; }
diff --git a/Core/src/java/de/hattrickorganizer/gui/statistic/SpieleStatistikPanel.java b/Core/src/java/de/hattrickorganizer/gui/statistic/SpieleStatistikPanel.java index cd6b0faa..7aeb8a8f 100644 --- a/Core/src/java/de/hattrickorganizer/gui/statistic/SpieleStatistikPanel.java +++ b/Core/src/java/de/hattrickorganizer/gui/statistic/SpieleStatistikPanel.java @@ -1,732 +1,732 @@ // %119582289:de.hattrickorganizer.gui.statistic% package de.hattrickorganizer.gui.statistic; import gui.HOColorName; import gui.HOIconName; import gui.UserParameter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionListener; import java.awt.event.FocusListener; import java.awt.event.ItemListener; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import plugins.IMatchLineupPlayer; import plugins.IRefreshable; import plugins.ISpielePanel; import plugins.ISpielerPosition; import de.hattrickorganizer.database.DBZugriff; import de.hattrickorganizer.gui.RefreshManager; import de.hattrickorganizer.gui.model.CBItem; import de.hattrickorganizer.gui.model.StatistikModel; import de.hattrickorganizer.gui.templates.ImagePanel; import de.hattrickorganizer.gui.theme.ThemeManager; import de.hattrickorganizer.model.HOVerwaltung; import de.hattrickorganizer.model.matches.MatchKurzInfo; import de.hattrickorganizer.model.matches.MatchLineupPlayer; import de.hattrickorganizer.model.matches.Matchdetails; import de.hattrickorganizer.tools.HOLogger; import de.hattrickorganizer.tools.Helper; import de.hattrickorganizer.tools.PlayerHelper; /** * Das StatistikPanel */ public class SpieleStatistikPanel extends ImagePanel implements ActionListener, FocusListener, ItemListener, IRefreshable { private static final long serialVersionUID = 3954095099686666846L; //~ Static fields/initializers ----------------------------------------------------------------- private Color ratingColor = ThemeManager.getColor(HOColorName.STAT_RATING2); private Color midfieldColor = ThemeManager.getColor(HOColorName.SHIRT_MIDFIELD); private Color rightWingbackColor = ThemeManager.getColor(HOColorName.SHIRT_WINGBACK).darker(); private Color centralDefenceColor = ThemeManager.getColor(HOColorName.SHIRT_CENTRALDEFENCE); private Color leftWingbackColor = ThemeManager.getColor(HOColorName.SHIRT_WINGBACK).brighter(); private Color rightForwardColor = ThemeManager.getColor(HOColorName.SHIRT_WING).darker(); private Color forwardColor = ThemeManager.getColor(HOColorName.SHIRT_FORWARD); private Color leftForwardColor = ThemeManager.getColor(HOColorName.SHIRT_WING).brighter(); private Color totalColor = ThemeManager.getColor(HOColorName.STAT_TOTAL); private Color moodColor = ThemeManager.getColor(HOColorName.STAT_MOOD); private Color confidenceColor = ThemeManager.getColor(HOColorName.STAT_CONFIDENCE); private Color hatStatsColor = ThemeManager.getColor(HOColorName.STAT_HATSTATS); private Color loddarStatsColor = ThemeManager.getColor(HOColorName.STAT_LODDAR); //~ Instance fields ---------------------------------------------------------------------------- private ImageCheckbox m_jchAbwehrzentrum = new ImageCheckbox(HOVerwaltung.instance().getLanguageString("Abwehrzentrum"), centralDefenceColor,UserParameter.instance().statistikSpieleAbwehrzentrum); private ImageCheckbox m_jchAngriffszentrum = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("Angriffszentrum"),forwardColor, UserParameter.instance().statistikSpieleAngriffszentrum); private ImageCheckbox m_jchBewertung = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("Bewertung"),ratingColor, UserParameter.instance().statistikSpieleBewertung); private ImageCheckbox m_jchGesamt = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("Gesamtstaerke"), totalColor, UserParameter.instance().statistikSpieleGesamt); private ImageCheckbox m_jchLinkeAbwehr = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("linkeAbwehrseite"),leftWingbackColor, UserParameter.instance().statistikSpieleLinkeAbwehr); private ImageCheckbox m_jchLinkerAngriff = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("linkeAngriffsseite"),leftForwardColor, UserParameter.instance().statistikSpieleLinkerAngriff); private ImageCheckbox m_jchMittelfeld = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("Mittelfeld"), midfieldColor, UserParameter.instance().statistikSpieleMittelfeld); private ImageCheckbox m_jchRechteAbwehr = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("rechteAbwehrseite"), rightWingbackColor, UserParameter.instance().statistikSpieleRechteAbwehr); private ImageCheckbox m_jchRechterAngriff = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("rechteAngriffsseite"),rightForwardColor, UserParameter.instance().statistikSpieleRechterAngriff); private ImageCheckbox m_jchSelbstvertrauen = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("Selbstvertrauen"), confidenceColor, UserParameter.instance().statistikSpieleSelbstvertrauen); private ImageCheckbox m_jchStimmung = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("Stimmung"),moodColor, UserParameter.instance().statistikSpieleStimmung); private ImageCheckbox m_jchHatStats = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("Hatstats"),hatStatsColor, UserParameter.instance().statistikSpieleHatStats); private ImageCheckbox m_jchLoddarStats = new ImageCheckbox(HOVerwaltung .instance().getLanguageString("LoddarStats"),loddarStatsColor, UserParameter.instance().statistikSpieleLoddarStats); private JButton m_jbDrucken = new JButton(ThemeManager.getIcon(HOIconName.PRINTER)); private JButton m_jbUbernehmen = new JButton(HOVerwaltung.instance() .getLanguageString("Uebernehmen")); private JCheckBox m_jchBeschriftung = new JCheckBox(HOVerwaltung.instance() .getLanguageString("Beschriftung"), UserParameter.instance().statistikSpielerFinanzenBeschriftung); private JCheckBox m_jchHilflinien = new JCheckBox(HOVerwaltung.instance() .getLanguageString("Hilflinien"), UserParameter.instance().statistikSpielerFinanzenHilfslinien); private JComboBox m_jcbSpieleFilter; private JTextField m_jtfAnzahlHRF = new JTextField( UserParameter.instance().statistikSpielerFinanzenAnzahlHRF + "", 5); private StatistikPanel m_clStatistikPanel; private CBItem[] SPIELEFILTER = { new CBItem(HOVerwaltung.instance().getLanguageString( "NurEigeneSpiele"), ISpielePanel.NUR_EIGENE_SPIELE + ISpielePanel.NUR_GESPIELTEN_SPIELE), new CBItem(HOVerwaltung.instance().getLanguageString( "NurEigenePflichtspiele"), ISpielePanel.NUR_EIGENE_PFLICHTSPIELE + ISpielePanel.NUR_GESPIELTEN_SPIELE), new CBItem(HOVerwaltung.instance().getLanguageString( "NurEigenePokalspiele"), ISpielePanel.NUR_EIGENE_POKALSPIELE + ISpielePanel.NUR_GESPIELTEN_SPIELE), new CBItem(HOVerwaltung.instance().getLanguageString( "NurEigeneLigaspiele"), ISpielePanel.NUR_EIGENE_LIGASPIELE + ISpielePanel.NUR_GESPIELTEN_SPIELE), new CBItem(HOVerwaltung.instance().getLanguageString( "NurEigeneFreundschaftsspiele"), ISpielePanel.NUR_EIGENE_FREUNDSCHAFTSSPIELE + ISpielePanel.NUR_GESPIELTEN_SPIELE) }; private boolean m_bInitialisiert; // ~ Constructors // ------------------------------------------------------------------------------- /** * Creates a new SpieleStatistikPanel object. */ public SpieleStatistikPanel() { RefreshManager.instance().registerRefreshable(this); initComponents(); // initStatistik(); } // ~ Methods // ------------------------------------------------------------------------------------ public final void setInitialisiert(boolean init) { m_bInitialisiert = init; } public final boolean isInitialisiert() { return m_bInitialisiert; } // -- Helper public final double getMaxValue(double[] werte) { double max = 0; for (int i = 0; (werte != null) && (i < werte.length); i++) { if (werte[i] > max) { max = werte[i]; } } return (max); } // --------Listener------------------------------- public final void actionPerformed(java.awt.event.ActionEvent actionEvent) { if (actionEvent.getSource().equals(m_jbUbernehmen)) { initStatistik(); } else if (actionEvent.getSource().equals(m_jbDrucken)) { m_clStatistikPanel.doPrint(HOVerwaltung.instance().getLanguageString("Spiele")); } else if (actionEvent.getSource().equals(m_jchHilflinien)) { m_clStatistikPanel.setHilfslinien(m_jchHilflinien.isSelected()); UserParameter.instance().statistikSpielerFinanzenHilfslinien = m_jchHilflinien .isSelected(); } else if (actionEvent.getSource().equals(m_jchBeschriftung)) { m_clStatistikPanel.setBeschriftung(m_jchBeschriftung.isSelected()); UserParameter.instance().statistikSpielerFinanzenBeschriftung = m_jchBeschriftung .isSelected(); } else if (actionEvent.getSource().equals(m_jchBewertung.getCheckbox())) { m_clStatistikPanel.setShow("Bewertung", m_jchBewertung.isSelected()); UserParameter.instance().statistikSpieleBewertung = m_jchBewertung.isSelected(); } else if (actionEvent.getSource().equals(m_jchGesamt.getCheckbox())) { m_clStatistikPanel.setShow("Gesamtstaerke", m_jchGesamt.isSelected()); UserParameter.instance().statistikSpieleGesamt = m_jchGesamt.isSelected(); } else if (actionEvent.getSource().equals(m_jchMittelfeld.getCheckbox())) { m_clStatistikPanel.setShow("Mittelfeld", m_jchMittelfeld.isSelected()); UserParameter.instance().statistikSpieleMittelfeld = m_jchMittelfeld.isSelected(); } else if (actionEvent.getSource().equals(m_jchRechteAbwehr.getCheckbox())) { m_clStatistikPanel.setShow("RechteAbwehr", m_jchRechteAbwehr.isSelected()); UserParameter.instance().statistikSpieleRechteAbwehr = m_jchRechteAbwehr.isSelected(); } else if (actionEvent.getSource().equals(m_jchAbwehrzentrum.getCheckbox())) { m_clStatistikPanel.setShow("Abwehrzentrum", m_jchAbwehrzentrum.isSelected()); UserParameter.instance().statistikSpieleAbwehrzentrum = m_jchAbwehrzentrum .isSelected(); } else if (actionEvent.getSource().equals(m_jchLinkeAbwehr.getCheckbox())) { m_clStatistikPanel.setShow("LinkeAbwehr", m_jchLinkeAbwehr.isSelected()); UserParameter.instance().statistikSpieleLinkeAbwehr = m_jchLinkeAbwehr.isSelected(); } else if (actionEvent.getSource().equals(m_jchRechterAngriff.getCheckbox())) { m_clStatistikPanel.setShow("RechterAngriff", m_jchRechterAngriff.isSelected()); UserParameter.instance().statistikSpieleRechterAngriff = m_jchRechterAngriff .isSelected(); } else if (actionEvent.getSource().equals(m_jchAngriffszentrum.getCheckbox())) { m_clStatistikPanel.setShow("Angriffszentrum", m_jchAngriffszentrum.isSelected()); UserParameter.instance().statistikSpieleAngriffszentrum = m_jchAngriffszentrum .isSelected(); } else if (actionEvent.getSource().equals(m_jchLinkerAngriff.getCheckbox())) { m_clStatistikPanel.setShow("LinkerAngriff", m_jchLinkerAngriff.isSelected()); UserParameter.instance().statistikSpieleLinkerAngriff = m_jchLinkerAngriff .isSelected(); } else if (actionEvent.getSource().equals(m_jchStimmung.getCheckbox())) { m_clStatistikPanel.setShow("Stimmung", m_jchStimmung.isSelected()); UserParameter.instance().statistikSpieleStimmung = m_jchStimmung.isSelected(); } else if (actionEvent.getSource().equals(m_jchHatStats.getCheckbox())) { m_clStatistikPanel.setShow("Hatstats", m_jchHatStats.isSelected()); UserParameter.instance().statistikSpieleHatStats = m_jchHatStats.isSelected(); } else if (actionEvent.getSource().equals(m_jchLoddarStats.getCheckbox())) { m_clStatistikPanel.setShow("LoddarStats", m_jchLoddarStats.isSelected()); UserParameter.instance().statistikSpieleLoddarStats = m_jchLoddarStats.isSelected(); } else if (actionEvent.getSource().equals(m_jchSelbstvertrauen.getCheckbox())) { m_clStatistikPanel.setShow("Selbstvertrauen", m_jchSelbstvertrauen.isSelected()); UserParameter.instance().statistikSpieleSelbstvertrauen = m_jchSelbstvertrauen .isSelected(); } } public final void doInitialisieren() { initStatistik(); m_bInitialisiert = true; } public void focusGained(java.awt.event.FocusEvent focusEvent) { } public final void focusLost(java.awt.event.FocusEvent focusEvent) { Helper.parseInt(de.hattrickorganizer.gui.HOMainFrame.instance(), ((JTextField) focusEvent.getSource()), false); } public final void itemStateChanged(java.awt.event.ItemEvent itemEvent) { if (itemEvent.getStateChange() == java.awt.event.ItemEvent.SELECTED) { initStatistik(); } } //-------Refresh--------------------------------- public final void reInit() { m_bInitialisiert = false; //initStatistik(); } public void refresh() { } private void initComponents() { JLabel label; final GridBagLayout layout = new GridBagLayout(); final GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.weightx = 0.0; constraints.weighty = 0.0; constraints.insets = new Insets(2, 0, 2, 0); setLayout(layout); final JPanel panel2 = new ImagePanel(); final GridBagLayout layout2 = new GridBagLayout(); final GridBagConstraints constraints2 = new GridBagConstraints(); constraints2.fill = GridBagConstraints.HORIZONTAL; constraints2.weightx = 0.0; constraints2.weighty = 0.0; constraints2.insets = new Insets(2, 2, 2, 2); panel2.setLayout(layout2); constraints2.gridx = 0; constraints2.gridy = 0; constraints2.gridwidth = 2; constraints2.fill = GridBagConstraints.NONE; constraints2.anchor = GridBagConstraints.WEST; m_jbDrucken.setToolTipText(HOVerwaltung.instance().getLanguageString("tt_Statistik_drucken")); m_jbDrucken.setPreferredSize(new Dimension(25, 25)); m_jbDrucken.addActionListener(this); layout2.setConstraints(m_jbDrucken, constraints2); panel2.add(m_jbDrucken); label = new JLabel(HOVerwaltung.instance().getLanguageString("Wochen")); constraints2.fill = GridBagConstraints.HORIZONTAL; constraints2.anchor = GridBagConstraints.WEST; constraints2.gridx = 0; constraints2.gridy = 1; constraints2.gridwidth = 1; layout2.setConstraints(label, constraints2); panel2.add(label); m_jtfAnzahlHRF.setHorizontalAlignment(SwingConstants.RIGHT); m_jtfAnzahlHRF.addFocusListener(this); constraints2.gridx = 1; constraints2.gridy = 1; layout2.setConstraints(m_jtfAnzahlHRF, constraints2); panel2.add(m_jtfAnzahlHRF); constraints2.gridx = 0; constraints2.gridy = 2; constraints2.gridwidth = 2; layout2.setConstraints(m_jbUbernehmen, constraints2); m_jbUbernehmen.setToolTipText(HOVerwaltung.instance().getLanguageString("tt_Statistik_HRFAnzahluebernehmen")); m_jbUbernehmen.addActionListener(this); panel2.add(m_jbUbernehmen); constraints2.gridx = 0; constraints2.gridy = 3; constraints2.gridwidth = 2; m_jcbSpieleFilter = new JComboBox(SPIELEFILTER); m_jcbSpieleFilter.setPreferredSize(new Dimension(150, 25)); Helper.markierenComboBox(m_jcbSpieleFilter, UserParameter.instance().statistikSpieleFilter); m_jcbSpieleFilter.addItemListener(this); m_jcbSpieleFilter.setFont(m_jcbSpieleFilter.getFont().deriveFont(Font.BOLD)); layout2.setConstraints(m_jcbSpieleFilter, constraints2); panel2.add(m_jcbSpieleFilter); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 5; m_jchHilflinien.setOpaque(false); m_jchHilflinien.setBackground(Color.white); m_jchHilflinien.addActionListener(this); layout2.setConstraints(m_jchHilflinien, constraints2); panel2.add(m_jchHilflinien); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 6; m_jchBeschriftung.setOpaque(false); m_jchBeschriftung.setBackground(Color.white); m_jchBeschriftung.addActionListener(this); layout2.setConstraints(m_jchBeschriftung, constraints2); panel2.add(m_jchBeschriftung); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 7; m_jchBewertung.setOpaque(false); m_jchBewertung.addActionListener(this); layout2.setConstraints(m_jchBewertung, constraints2); panel2.add(m_jchBewertung); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 8; m_jchHatStats.setOpaque(false); m_jchHatStats.addActionListener(this); layout2.setConstraints(m_jchHatStats, constraints2); panel2.add(m_jchHatStats); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 9; m_jchLoddarStats.setOpaque(false); m_jchLoddarStats.addActionListener(this); layout2.setConstraints(m_jchLoddarStats, constraints2); panel2.add(m_jchLoddarStats); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 10; m_jchGesamt.setOpaque(false); m_jchGesamt.addActionListener(this); layout2.setConstraints(m_jchGesamt, constraints2); panel2.add(m_jchGesamt); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 11; m_jchMittelfeld.setOpaque(false); m_jchMittelfeld.addActionListener(this); layout2.setConstraints(m_jchMittelfeld, constraints2); panel2.add(m_jchMittelfeld); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 12; m_jchRechteAbwehr.setOpaque(false); m_jchRechteAbwehr.addActionListener(this); layout2.setConstraints(m_jchRechteAbwehr, constraints2); panel2.add(m_jchRechteAbwehr); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 13; m_jchAbwehrzentrum.setOpaque(false); m_jchAbwehrzentrum.addActionListener(this); layout2.setConstraints(m_jchAbwehrzentrum, constraints2); panel2.add(m_jchAbwehrzentrum); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 14; m_jchLinkeAbwehr.setOpaque(false); m_jchLinkeAbwehr.addActionListener(this); layout2.setConstraints(m_jchLinkeAbwehr, constraints2); panel2.add(m_jchLinkeAbwehr); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 15; m_jchRechterAngriff.setOpaque(false); m_jchRechterAngriff.addActionListener(this); layout2.setConstraints(m_jchRechterAngriff, constraints2); panel2.add(m_jchRechterAngriff); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 16; m_jchAngriffszentrum.setOpaque(false); m_jchAngriffszentrum.addActionListener(this); layout2.setConstraints(m_jchAngriffszentrum, constraints2); panel2.add(m_jchAngriffszentrum); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 17; m_jchLinkerAngriff.setOpaque(false); m_jchLinkerAngriff.addActionListener(this); layout2.setConstraints(m_jchLinkerAngriff, constraints2); panel2.add(m_jchLinkerAngriff); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 18; m_jchStimmung.setOpaque(false); m_jchStimmung.addActionListener(this); layout2.setConstraints(m_jchStimmung, constraints2); panel2.add(m_jchStimmung); constraints2.gridwidth = 2; constraints2.gridx = 0; constraints2.gridy = 19; m_jchSelbstvertrauen.setOpaque(false); m_jchSelbstvertrauen.addActionListener(this); layout2.setConstraints(m_jchSelbstvertrauen, constraints2); panel2.add(m_jchSelbstvertrauen); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 1; constraints.weightx = 0.01; constraints.weighty = 0.001; constraints.anchor = GridBagConstraints.NORTH; layout.setConstraints(panel2, constraints); add(panel2); //Table final JPanel panel = new ImagePanel(); panel.setLayout(new BorderLayout()); m_clStatistikPanel = new StatistikPanel(false); panel.add(m_clStatistikPanel); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 1; constraints.gridwidth = 1; constraints.weighty = 1.0; constraints.weightx = 1.0; constraints.anchor = GridBagConstraints.NORTH; panel.setBorder(BorderFactory.createLineBorder(ThemeManager.getColor(HOColorName.PANEL_BORDER))); layout.setConstraints(panel, constraints); add(panel); } /** * TODO Missing Method Documentation */ private void initStatistik() { try { int anzahlHRF = Integer.parseInt(m_jtfAnzahlHRF.getText()); if (anzahlHRF <= 0) { anzahlHRF = 1; } UserParameter.instance().statistikSpielerFinanzenAnzahlHRF = anzahlHRF; UserParameter.instance().statistikSpieleFilter = ((CBItem) m_jcbSpieleFilter.getSelectedItem()).getId(); final java.text.NumberFormat format = Helper.DEFAULTDEZIMALFORMAT; final java.text.NumberFormat format2 = Helper.INTEGERFORMAT; final java.text.NumberFormat format3 = Helper.DEZIMALFORMAT_2STELLEN; final MatchKurzInfo[] matchkurzinfos = DBZugriff .instance() .getMatchesKurzInfo( HOVerwaltung.instance().getModel().getBasics() .getTeamId(), ((CBItem) m_jcbSpieleFilter.getSelectedItem()).getId(), true); final int anzahl = Math.min(matchkurzinfos.length, anzahlHRF); final int teamid = HOVerwaltung.instance().getModel().getBasics().getTeamId(); final double[][] statistikWerte = new double[14][anzahl]; // Infos zusammenstellen for (int i = 0; i < anzahl; i++) { final Matchdetails details = DBZugriff.instance() .getMatchDetails(matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchID()); int bewertungwert = 0; double loddarStats = 0; // Für match int sublevel = 0; // Für gesamtstärke double temp = 0d; if (details.getHeimId() == teamid) { sublevel = (details.getHomeMidfield()) % 4; // (int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidfield() - 1) / 4) + 1; statistikWerte[1][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeRightDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeRightDef() - 1) / 4) + 1; statistikWerte[2][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeMidDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidDef() - 1) / 4) + 1; statistikWerte[3][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeLeftDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeLeftDef() - 1) / 4) + 1; statistikWerte[4][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeRightAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeRightAtt() - 1) / 4) + 1; statistikWerte[5][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeMidAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidAtt() - 1) / 4) + 1; statistikWerte[6][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeLeftAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeLeftAtt() - 1) / 4) + 1; statistikWerte[7][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); temp = details.getHomeGesamtstaerke(false); sublevel = ((int) temp) % 4; statistikWerte[8][i] = (((int) temp - 1) / 4) + 1 + PlayerHelper.getValue4Sublevel(sublevel); statistikWerte[11][i] = details.getHomeHatStats(); // Calculate and return the LoddarStats rating statistikWerte[12][i] = details.getHomeLoddarStats(); } else { sublevel = (details.getGuestMidfield()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidfield() - 1) / 4) + 1; statistikWerte[1][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestRightDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestRightDef() - 1) / 4) + 1; statistikWerte[2][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestMidDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidDef() - 1) / 4) + 1; statistikWerte[3][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestLeftDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestLeftDef() - 1) / 4) + 1; statistikWerte[4][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestRightAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestRightAtt() - 1) / 4) + 1; statistikWerte[5][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestMidAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidAtt() - 1) / 4) + 1; statistikWerte[6][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestLeftAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestLeftAtt() - 1) / 4) + 1; statistikWerte[7][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); temp = details.getGuestGesamtstaerke(false); sublevel = ((int) temp) % 4; statistikWerte[8][i] = (((int) temp - 1) / 4) + 1 + PlayerHelper.getValue4Sublevel(sublevel); statistikWerte[11][i] = details.getAwayHatStats(); // Calculate and return the LoddarStats rating statistikWerte[12][i] = details.getAwayLoddarStats(); } //Stimmung, Selbstvertrauen final int hrfid = DBZugriff.instance().getHRFID4Date( matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchDateAsTimestamp()); final int[] stimmungSelbstvertrauen = DBZugriff.instance() .getStimmmungSelbstvertrauenValues(hrfid); statistikWerte[9][i] = stimmungSelbstvertrauen[0]; statistikWerte[10][i] = stimmungSelbstvertrauen[1]; statistikWerte[13][i] = matchkurzinfos[matchkurzinfos.length - i - 1].getMatchDateAsTimestamp().getTime(); final Vector<IMatchLineupPlayer> team = DBZugriff.instance() .getMatchLineupPlayers( matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchID(), teamid); float sterne = 0; // Sterne for (int j = 0; j < team.size(); j++) { final MatchLineupPlayer player = (MatchLineupPlayer) team.get(j); - if (player.getId() < ISpielerPosition.startReserves) { + if (player.getId() < ISpielerPosition.substKeeper) { float rating = (float) player.getRating(); if (rating > 0) { sterne += rating; } } } statistikWerte[0][i] = sterne; } final StatistikModel[] models = new StatistikModel[statistikWerte.length]; //Es sind 13 Werte! if (statistikWerte.length > 0) { double faktor = 20 / getMaxValue(statistikWerte[0]); models[0] = new StatistikModel(statistikWerte[0], "Bewertung", m_jchBewertung.isSelected(), ratingColor, format, faktor); models[1] = new StatistikModel(statistikWerte[1], "Mittelfeld", m_jchMittelfeld.isSelected(), midfieldColor, format); models[2] = new StatistikModel(statistikWerte[2], "RechteAbwehr", m_jchRechteAbwehr.isSelected(), rightWingbackColor, format); models[3] = new StatistikModel(statistikWerte[3], "Abwehrzentrum", m_jchAbwehrzentrum.isSelected(), centralDefenceColor, format); models[4] = new StatistikModel(statistikWerte[4], "LinkeAbwehr", m_jchRechteAbwehr.isSelected(), leftWingbackColor, format); models[5] = new StatistikModel(statistikWerte[5], "RechterAngriff", m_jchRechterAngriff.isSelected(), rightForwardColor, format); models[6] = new StatistikModel(statistikWerte[6], "Angriffszentrum", m_jchAngriffszentrum.isSelected(), forwardColor, format); models[7] = new StatistikModel(statistikWerte[7], "LinkerAngriff", m_jchLinkerAngriff.isSelected(), leftForwardColor, format); models[8] = new StatistikModel(statistikWerte[8], "Gesamtstaerke", m_jchGesamt.isSelected(), totalColor, format3); models[9] = new StatistikModel(statistikWerte[9], "Stimmung", m_jchStimmung.isSelected(), moodColor, format2); models[10] = new StatistikModel(statistikWerte[10], "Selbstvertrauen", m_jchSelbstvertrauen.isSelected(), confidenceColor, format2); faktor = 20 / getMaxValue(statistikWerte[11]); models[11] = new StatistikModel(statistikWerte[11], "Hatstats", m_jchHatStats.isSelected(), hatStatsColor, format2, faktor); faktor = 20 / getMaxValue(statistikWerte[12]); models[12] = new StatistikModel(statistikWerte[12], "LoddarStats", m_jchLoddarStats.isSelected(), loddarStatsColor, format3, faktor); } final String[] yBezeichnungen = Helper.convertTimeMillisToFormatString(statistikWerte[13]); m_clStatistikPanel.setAllValues(models, yBezeichnungen, format, HOVerwaltung.instance().getLanguageString("Spiele"), "", m_jchBeschriftung.isSelected(), m_jchHilflinien.isSelected()); } catch (Exception e) { HOLogger.instance().log(getClass(),"SpieleStatistikPanel.initStatistik : " + e); HOLogger.instance().log(getClass(),e); } //Test //double[] werte = { 1d, 2d, 1.5d, 3d, 2.5d }; //StatistikModel[] model = { new StatistikModel( werte, "Fuehrung", true, FUEHRUNG ) }; //m_clStatistikPanel.setModel ( model ); } private double hq(double value) { return (2 * value) / (value + 80); } }
true
true
private void initStatistik() { try { int anzahlHRF = Integer.parseInt(m_jtfAnzahlHRF.getText()); if (anzahlHRF <= 0) { anzahlHRF = 1; } UserParameter.instance().statistikSpielerFinanzenAnzahlHRF = anzahlHRF; UserParameter.instance().statistikSpieleFilter = ((CBItem) m_jcbSpieleFilter.getSelectedItem()).getId(); final java.text.NumberFormat format = Helper.DEFAULTDEZIMALFORMAT; final java.text.NumberFormat format2 = Helper.INTEGERFORMAT; final java.text.NumberFormat format3 = Helper.DEZIMALFORMAT_2STELLEN; final MatchKurzInfo[] matchkurzinfos = DBZugriff .instance() .getMatchesKurzInfo( HOVerwaltung.instance().getModel().getBasics() .getTeamId(), ((CBItem) m_jcbSpieleFilter.getSelectedItem()).getId(), true); final int anzahl = Math.min(matchkurzinfos.length, anzahlHRF); final int teamid = HOVerwaltung.instance().getModel().getBasics().getTeamId(); final double[][] statistikWerte = new double[14][anzahl]; // Infos zusammenstellen for (int i = 0; i < anzahl; i++) { final Matchdetails details = DBZugriff.instance() .getMatchDetails(matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchID()); int bewertungwert = 0; double loddarStats = 0; // Für match int sublevel = 0; // Für gesamtstärke double temp = 0d; if (details.getHeimId() == teamid) { sublevel = (details.getHomeMidfield()) % 4; // (int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidfield() - 1) / 4) + 1; statistikWerte[1][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeRightDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeRightDef() - 1) / 4) + 1; statistikWerte[2][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeMidDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidDef() - 1) / 4) + 1; statistikWerte[3][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeLeftDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeLeftDef() - 1) / 4) + 1; statistikWerte[4][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeRightAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeRightAtt() - 1) / 4) + 1; statistikWerte[5][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeMidAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidAtt() - 1) / 4) + 1; statistikWerte[6][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeLeftAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeLeftAtt() - 1) / 4) + 1; statistikWerte[7][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); temp = details.getHomeGesamtstaerke(false); sublevel = ((int) temp) % 4; statistikWerte[8][i] = (((int) temp - 1) / 4) + 1 + PlayerHelper.getValue4Sublevel(sublevel); statistikWerte[11][i] = details.getHomeHatStats(); // Calculate and return the LoddarStats rating statistikWerte[12][i] = details.getHomeLoddarStats(); } else { sublevel = (details.getGuestMidfield()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidfield() - 1) / 4) + 1; statistikWerte[1][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestRightDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestRightDef() - 1) / 4) + 1; statistikWerte[2][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestMidDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidDef() - 1) / 4) + 1; statistikWerte[3][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestLeftDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestLeftDef() - 1) / 4) + 1; statistikWerte[4][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestRightAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestRightAtt() - 1) / 4) + 1; statistikWerte[5][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestMidAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidAtt() - 1) / 4) + 1; statistikWerte[6][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestLeftAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestLeftAtt() - 1) / 4) + 1; statistikWerte[7][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); temp = details.getGuestGesamtstaerke(false); sublevel = ((int) temp) % 4; statistikWerte[8][i] = (((int) temp - 1) / 4) + 1 + PlayerHelper.getValue4Sublevel(sublevel); statistikWerte[11][i] = details.getAwayHatStats(); // Calculate and return the LoddarStats rating statistikWerte[12][i] = details.getAwayLoddarStats(); } //Stimmung, Selbstvertrauen final int hrfid = DBZugriff.instance().getHRFID4Date( matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchDateAsTimestamp()); final int[] stimmungSelbstvertrauen = DBZugriff.instance() .getStimmmungSelbstvertrauenValues(hrfid); statistikWerte[9][i] = stimmungSelbstvertrauen[0]; statistikWerte[10][i] = stimmungSelbstvertrauen[1]; statistikWerte[13][i] = matchkurzinfos[matchkurzinfos.length - i - 1].getMatchDateAsTimestamp().getTime(); final Vector<IMatchLineupPlayer> team = DBZugriff.instance() .getMatchLineupPlayers( matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchID(), teamid); float sterne = 0; // Sterne for (int j = 0; j < team.size(); j++) { final MatchLineupPlayer player = (MatchLineupPlayer) team.get(j); if (player.getId() < ISpielerPosition.startReserves) { float rating = (float) player.getRating(); if (rating > 0) { sterne += rating; } } } statistikWerte[0][i] = sterne; } final StatistikModel[] models = new StatistikModel[statistikWerte.length]; //Es sind 13 Werte! if (statistikWerte.length > 0) { double faktor = 20 / getMaxValue(statistikWerte[0]); models[0] = new StatistikModel(statistikWerte[0], "Bewertung", m_jchBewertung.isSelected(), ratingColor, format, faktor); models[1] = new StatistikModel(statistikWerte[1], "Mittelfeld", m_jchMittelfeld.isSelected(), midfieldColor, format); models[2] = new StatistikModel(statistikWerte[2], "RechteAbwehr", m_jchRechteAbwehr.isSelected(), rightWingbackColor, format); models[3] = new StatistikModel(statistikWerte[3], "Abwehrzentrum", m_jchAbwehrzentrum.isSelected(), centralDefenceColor, format); models[4] = new StatistikModel(statistikWerte[4], "LinkeAbwehr", m_jchRechteAbwehr.isSelected(), leftWingbackColor, format); models[5] = new StatistikModel(statistikWerte[5], "RechterAngriff", m_jchRechterAngriff.isSelected(), rightForwardColor, format); models[6] = new StatistikModel(statistikWerte[6], "Angriffszentrum", m_jchAngriffszentrum.isSelected(), forwardColor, format); models[7] = new StatistikModel(statistikWerte[7], "LinkerAngriff", m_jchLinkerAngriff.isSelected(), leftForwardColor, format); models[8] = new StatistikModel(statistikWerte[8], "Gesamtstaerke", m_jchGesamt.isSelected(), totalColor, format3); models[9] = new StatistikModel(statistikWerte[9], "Stimmung", m_jchStimmung.isSelected(), moodColor, format2); models[10] = new StatistikModel(statistikWerte[10], "Selbstvertrauen", m_jchSelbstvertrauen.isSelected(), confidenceColor, format2); faktor = 20 / getMaxValue(statistikWerte[11]); models[11] = new StatistikModel(statistikWerte[11], "Hatstats", m_jchHatStats.isSelected(), hatStatsColor, format2, faktor); faktor = 20 / getMaxValue(statistikWerte[12]); models[12] = new StatistikModel(statistikWerte[12], "LoddarStats", m_jchLoddarStats.isSelected(), loddarStatsColor, format3, faktor); } final String[] yBezeichnungen = Helper.convertTimeMillisToFormatString(statistikWerte[13]); m_clStatistikPanel.setAllValues(models, yBezeichnungen, format, HOVerwaltung.instance().getLanguageString("Spiele"), "", m_jchBeschriftung.isSelected(), m_jchHilflinien.isSelected()); } catch (Exception e) { HOLogger.instance().log(getClass(),"SpieleStatistikPanel.initStatistik : " + e); HOLogger.instance().log(getClass(),e); } //Test //double[] werte = { 1d, 2d, 1.5d, 3d, 2.5d }; //StatistikModel[] model = { new StatistikModel( werte, "Fuehrung", true, FUEHRUNG ) }; //m_clStatistikPanel.setModel ( model ); }
private void initStatistik() { try { int anzahlHRF = Integer.parseInt(m_jtfAnzahlHRF.getText()); if (anzahlHRF <= 0) { anzahlHRF = 1; } UserParameter.instance().statistikSpielerFinanzenAnzahlHRF = anzahlHRF; UserParameter.instance().statistikSpieleFilter = ((CBItem) m_jcbSpieleFilter.getSelectedItem()).getId(); final java.text.NumberFormat format = Helper.DEFAULTDEZIMALFORMAT; final java.text.NumberFormat format2 = Helper.INTEGERFORMAT; final java.text.NumberFormat format3 = Helper.DEZIMALFORMAT_2STELLEN; final MatchKurzInfo[] matchkurzinfos = DBZugriff .instance() .getMatchesKurzInfo( HOVerwaltung.instance().getModel().getBasics() .getTeamId(), ((CBItem) m_jcbSpieleFilter.getSelectedItem()).getId(), true); final int anzahl = Math.min(matchkurzinfos.length, anzahlHRF); final int teamid = HOVerwaltung.instance().getModel().getBasics().getTeamId(); final double[][] statistikWerte = new double[14][anzahl]; // Infos zusammenstellen for (int i = 0; i < anzahl; i++) { final Matchdetails details = DBZugriff.instance() .getMatchDetails(matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchID()); int bewertungwert = 0; double loddarStats = 0; // Für match int sublevel = 0; // Für gesamtstärke double temp = 0d; if (details.getHeimId() == teamid) { sublevel = (details.getHomeMidfield()) % 4; // (int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidfield() - 1) / 4) + 1; statistikWerte[1][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeRightDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeRightDef() - 1) / 4) + 1; statistikWerte[2][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeMidDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidDef() - 1) / 4) + 1; statistikWerte[3][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeLeftDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeLeftDef() - 1) / 4) + 1; statistikWerte[4][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeRightAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeRightAtt() - 1) / 4) + 1; statistikWerte[5][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeMidAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeMidAtt() - 1) / 4) + 1; statistikWerte[6][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getHomeLeftAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getHomeLeftAtt() - 1) / 4) + 1; statistikWerte[7][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); temp = details.getHomeGesamtstaerke(false); sublevel = ((int) temp) % 4; statistikWerte[8][i] = (((int) temp - 1) / 4) + 1 + PlayerHelper.getValue4Sublevel(sublevel); statistikWerte[11][i] = details.getHomeHatStats(); // Calculate and return the LoddarStats rating statistikWerte[12][i] = details.getHomeLoddarStats(); } else { sublevel = (details.getGuestMidfield()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidfield() - 1) / 4) + 1; statistikWerte[1][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestRightDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestRightDef() - 1) / 4) + 1; statistikWerte[2][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestMidDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidDef() - 1) / 4) + 1; statistikWerte[3][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestLeftDef()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestLeftDef() - 1) / 4) + 1; statistikWerte[4][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestRightAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestRightAtt() - 1) / 4) + 1; statistikWerte[5][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestMidAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestMidAtt() - 1) / 4) + 1; statistikWerte[6][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); sublevel = (details.getGuestLeftAtt()) % 4; //(int)Math.floor ( ( (float)bewertungwert)/4f ) +1; bewertungwert = ((details.getGuestLeftAtt() - 1) / 4) + 1; statistikWerte[7][i] = bewertungwert + PlayerHelper.getValue4Sublevel(sublevel); temp = details.getGuestGesamtstaerke(false); sublevel = ((int) temp) % 4; statistikWerte[8][i] = (((int) temp - 1) / 4) + 1 + PlayerHelper.getValue4Sublevel(sublevel); statistikWerte[11][i] = details.getAwayHatStats(); // Calculate and return the LoddarStats rating statistikWerte[12][i] = details.getAwayLoddarStats(); } //Stimmung, Selbstvertrauen final int hrfid = DBZugriff.instance().getHRFID4Date( matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchDateAsTimestamp()); final int[] stimmungSelbstvertrauen = DBZugriff.instance() .getStimmmungSelbstvertrauenValues(hrfid); statistikWerte[9][i] = stimmungSelbstvertrauen[0]; statistikWerte[10][i] = stimmungSelbstvertrauen[1]; statistikWerte[13][i] = matchkurzinfos[matchkurzinfos.length - i - 1].getMatchDateAsTimestamp().getTime(); final Vector<IMatchLineupPlayer> team = DBZugriff.instance() .getMatchLineupPlayers( matchkurzinfos[matchkurzinfos.length - i - 1] .getMatchID(), teamid); float sterne = 0; // Sterne for (int j = 0; j < team.size(); j++) { final MatchLineupPlayer player = (MatchLineupPlayer) team.get(j); if (player.getId() < ISpielerPosition.substKeeper) { float rating = (float) player.getRating(); if (rating > 0) { sterne += rating; } } } statistikWerte[0][i] = sterne; } final StatistikModel[] models = new StatistikModel[statistikWerte.length]; //Es sind 13 Werte! if (statistikWerte.length > 0) { double faktor = 20 / getMaxValue(statistikWerte[0]); models[0] = new StatistikModel(statistikWerte[0], "Bewertung", m_jchBewertung.isSelected(), ratingColor, format, faktor); models[1] = new StatistikModel(statistikWerte[1], "Mittelfeld", m_jchMittelfeld.isSelected(), midfieldColor, format); models[2] = new StatistikModel(statistikWerte[2], "RechteAbwehr", m_jchRechteAbwehr.isSelected(), rightWingbackColor, format); models[3] = new StatistikModel(statistikWerte[3], "Abwehrzentrum", m_jchAbwehrzentrum.isSelected(), centralDefenceColor, format); models[4] = new StatistikModel(statistikWerte[4], "LinkeAbwehr", m_jchRechteAbwehr.isSelected(), leftWingbackColor, format); models[5] = new StatistikModel(statistikWerte[5], "RechterAngriff", m_jchRechterAngriff.isSelected(), rightForwardColor, format); models[6] = new StatistikModel(statistikWerte[6], "Angriffszentrum", m_jchAngriffszentrum.isSelected(), forwardColor, format); models[7] = new StatistikModel(statistikWerte[7], "LinkerAngriff", m_jchLinkerAngriff.isSelected(), leftForwardColor, format); models[8] = new StatistikModel(statistikWerte[8], "Gesamtstaerke", m_jchGesamt.isSelected(), totalColor, format3); models[9] = new StatistikModel(statistikWerte[9], "Stimmung", m_jchStimmung.isSelected(), moodColor, format2); models[10] = new StatistikModel(statistikWerte[10], "Selbstvertrauen", m_jchSelbstvertrauen.isSelected(), confidenceColor, format2); faktor = 20 / getMaxValue(statistikWerte[11]); models[11] = new StatistikModel(statistikWerte[11], "Hatstats", m_jchHatStats.isSelected(), hatStatsColor, format2, faktor); faktor = 20 / getMaxValue(statistikWerte[12]); models[12] = new StatistikModel(statistikWerte[12], "LoddarStats", m_jchLoddarStats.isSelected(), loddarStatsColor, format3, faktor); } final String[] yBezeichnungen = Helper.convertTimeMillisToFormatString(statistikWerte[13]); m_clStatistikPanel.setAllValues(models, yBezeichnungen, format, HOVerwaltung.instance().getLanguageString("Spiele"), "", m_jchBeschriftung.isSelected(), m_jchHilflinien.isSelected()); } catch (Exception e) { HOLogger.instance().log(getClass(),"SpieleStatistikPanel.initStatistik : " + e); HOLogger.instance().log(getClass(),e); } //Test //double[] werte = { 1d, 2d, 1.5d, 3d, 2.5d }; //StatistikModel[] model = { new StatistikModel( werte, "Fuehrung", true, FUEHRUNG ) }; //m_clStatistikPanel.setModel ( model ); }
diff --git a/src/br/com/tecsinapse/glimpse/views/ReplView.java b/src/br/com/tecsinapse/glimpse/views/ReplView.java index cb4ee48..6bac24e 100644 --- a/src/br/com/tecsinapse/glimpse/views/ReplView.java +++ b/src/br/com/tecsinapse/glimpse/views/ReplView.java @@ -1,93 +1,95 @@ package br.com.tecsinapse.glimpse.views; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.part.ViewPart; import br.com.tecsinapse.glimpse.client.DefaultReplManager; import br.com.tecsinapse.glimpse.client.Repl; import br.com.tecsinapse.glimpse.client.ReplManager; import br.com.tecsinapse.glimpse.client.http.HttpConnector; import br.com.tecsinapse.glimpse.preferences.PreferenceUtils; public class ReplView extends ViewPart { private ReplManager replManager; private Repl repl; @Override public void createPartControl(Composite parent) { HttpConnector connector = new HttpConnector(PreferenceUtils.getUrl(), PreferenceUtils.getUserName(), PreferenceUtils.getPassword()); replManager = new DefaultReplManager(connector); SashForm split = new SashForm(parent, SWT.VERTICAL); + split.setBackground(Display.getDefault().getSystemColor( + SWT.COLOR_GRAY)); Font font = JFaceResources.getTextFont(); final StyledText console = new StyledText(split, SWT.V_SCROLL | SWT.WRAP); console.setFont(font); console.setEditable(false); final StyledText command = new StyledText(split, SWT.V_SCROLL | SWT.WRAP); command.setFont(font); command.addVerifyKeyListener(new VerifyKeyListener() { @Override public void verifyKey(VerifyEvent e) { if (e.stateMask == SWT.CTRL && (e.keyCode == SWT.LF || e.keyCode == SWT.CR)) { e.doit = false; Display display = PlatformUI.getWorkbench().getDisplay(); if (!display.isDisposed()) { display.asyncExec(new Runnable() { @Override public void run() { if (repl == null) { repl = replManager.createRepl(); } String exp = command.getText(); console.append(exp); String result = repl.eval(exp); StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append("=> "); builder.append(result); builder.append("\n"); String resultText = builder.toString(); StyleRange resultStyle = new StyleRange(console .getCharCount(), resultText.length(), Display.getDefault().getSystemColor( SWT.COLOR_DARK_GREEN), null); console.append(resultText); console.setStyleRange(resultStyle); console.setCaretOffset(console.getCharCount()); console.showSelection(); command.setText(""); } }); } } } }); } @Override public void setFocus() { } }
true
true
public void createPartControl(Composite parent) { HttpConnector connector = new HttpConnector(PreferenceUtils.getUrl(), PreferenceUtils.getUserName(), PreferenceUtils.getPassword()); replManager = new DefaultReplManager(connector); SashForm split = new SashForm(parent, SWT.VERTICAL); Font font = JFaceResources.getTextFont(); final StyledText console = new StyledText(split, SWT.V_SCROLL | SWT.WRAP); console.setFont(font); console.setEditable(false); final StyledText command = new StyledText(split, SWT.V_SCROLL | SWT.WRAP); command.setFont(font); command.addVerifyKeyListener(new VerifyKeyListener() { @Override public void verifyKey(VerifyEvent e) { if (e.stateMask == SWT.CTRL && (e.keyCode == SWT.LF || e.keyCode == SWT.CR)) { e.doit = false; Display display = PlatformUI.getWorkbench().getDisplay(); if (!display.isDisposed()) { display.asyncExec(new Runnable() { @Override public void run() { if (repl == null) { repl = replManager.createRepl(); } String exp = command.getText(); console.append(exp); String result = repl.eval(exp); StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append("=> "); builder.append(result); builder.append("\n"); String resultText = builder.toString(); StyleRange resultStyle = new StyleRange(console .getCharCount(), resultText.length(), Display.getDefault().getSystemColor( SWT.COLOR_DARK_GREEN), null); console.append(resultText); console.setStyleRange(resultStyle); console.setCaretOffset(console.getCharCount()); console.showSelection(); command.setText(""); } }); } } } }); }
public void createPartControl(Composite parent) { HttpConnector connector = new HttpConnector(PreferenceUtils.getUrl(), PreferenceUtils.getUserName(), PreferenceUtils.getPassword()); replManager = new DefaultReplManager(connector); SashForm split = new SashForm(parent, SWT.VERTICAL); split.setBackground(Display.getDefault().getSystemColor( SWT.COLOR_GRAY)); Font font = JFaceResources.getTextFont(); final StyledText console = new StyledText(split, SWT.V_SCROLL | SWT.WRAP); console.setFont(font); console.setEditable(false); final StyledText command = new StyledText(split, SWT.V_SCROLL | SWT.WRAP); command.setFont(font); command.addVerifyKeyListener(new VerifyKeyListener() { @Override public void verifyKey(VerifyEvent e) { if (e.stateMask == SWT.CTRL && (e.keyCode == SWT.LF || e.keyCode == SWT.CR)) { e.doit = false; Display display = PlatformUI.getWorkbench().getDisplay(); if (!display.isDisposed()) { display.asyncExec(new Runnable() { @Override public void run() { if (repl == null) { repl = replManager.createRepl(); } String exp = command.getText(); console.append(exp); String result = repl.eval(exp); StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append("=> "); builder.append(result); builder.append("\n"); String resultText = builder.toString(); StyleRange resultStyle = new StyleRange(console .getCharCount(), resultText.length(), Display.getDefault().getSystemColor( SWT.COLOR_DARK_GREEN), null); console.append(resultText); console.setStyleRange(resultStyle); console.setCaretOffset(console.getCharCount()); console.showSelection(); command.setText(""); } }); } } } }); }
diff --git a/assets/fyresmodjam/PillarGen.java b/assets/fyresmodjam/PillarGen.java index fd09826..b660030 100644 --- a/assets/fyresmodjam/PillarGen.java +++ b/assets/fyresmodjam/PillarGen.java @@ -1,43 +1,43 @@ package assets.fyresmodjam; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; import cpw.mods.fml.common.IWorldGenerator; public class PillarGen implements IWorldGenerator { @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { if(world.provider.dimensionId == 0 && random.nextInt(25) == 0) { boolean placed = false; for(int y = 127, added = 0; y > 30 && !placed && added < 4; y--) { for(int x = chunkX * 16; x < chunkX * 16 + 16 && !placed && added < 4; x++) { for(int z = chunkZ * 16; z < chunkZ * 16 + 16 && !placed && added < 4; z++) { - if(random.nextInt(10) != 0 || world.isAirBlock(x, y, z) || Block.blocksList[world.getBlockId(x, y, z)].isBlockReplaceable(world, x, y, z) || world.getBlockId(x, y, z) == ModjamMod.blockTrap.blockID) {continue;} + if(random.nextInt(10) != 0 || world.isAirBlock(x, y, z) || Block.blocksList[world.getBlockId(x, y, z)].isBlockReplaceable(world, x, y, z) || world.getBlockId(x, y, z) == ModjamMod.blockTrap.blockID || world.getBlockId(x, y, z) == Block.leaves.blockID) {continue;} Block block = ModjamMod.blockPillar; if(block.canPlaceBlockAt(world, x, y + 1, z)) { world.setBlock(x, y + 1, z, block.blockID); world.setBlockMetadataWithNotify(x, y + 1, z, 0, 0); world.setBlock(x, y + 2, z, block.blockID); world.setBlockMetadataWithNotify(x, y + 2, z, 1, 0); placed = random.nextBoolean(); y -= 10; added++; //System.out.println(x + ", " + y + ", " + z); } } } } } } }
true
true
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { if(world.provider.dimensionId == 0 && random.nextInt(25) == 0) { boolean placed = false; for(int y = 127, added = 0; y > 30 && !placed && added < 4; y--) { for(int x = chunkX * 16; x < chunkX * 16 + 16 && !placed && added < 4; x++) { for(int z = chunkZ * 16; z < chunkZ * 16 + 16 && !placed && added < 4; z++) { if(random.nextInt(10) != 0 || world.isAirBlock(x, y, z) || Block.blocksList[world.getBlockId(x, y, z)].isBlockReplaceable(world, x, y, z) || world.getBlockId(x, y, z) == ModjamMod.blockTrap.blockID) {continue;} Block block = ModjamMod.blockPillar; if(block.canPlaceBlockAt(world, x, y + 1, z)) { world.setBlock(x, y + 1, z, block.blockID); world.setBlockMetadataWithNotify(x, y + 1, z, 0, 0); world.setBlock(x, y + 2, z, block.blockID); world.setBlockMetadataWithNotify(x, y + 2, z, 1, 0); placed = random.nextBoolean(); y -= 10; added++; //System.out.println(x + ", " + y + ", " + z); } } } } } }
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider) { if(world.provider.dimensionId == 0 && random.nextInt(25) == 0) { boolean placed = false; for(int y = 127, added = 0; y > 30 && !placed && added < 4; y--) { for(int x = chunkX * 16; x < chunkX * 16 + 16 && !placed && added < 4; x++) { for(int z = chunkZ * 16; z < chunkZ * 16 + 16 && !placed && added < 4; z++) { if(random.nextInt(10) != 0 || world.isAirBlock(x, y, z) || Block.blocksList[world.getBlockId(x, y, z)].isBlockReplaceable(world, x, y, z) || world.getBlockId(x, y, z) == ModjamMod.blockTrap.blockID || world.getBlockId(x, y, z) == Block.leaves.blockID) {continue;} Block block = ModjamMod.blockPillar; if(block.canPlaceBlockAt(world, x, y + 1, z)) { world.setBlock(x, y + 1, z, block.blockID); world.setBlockMetadataWithNotify(x, y + 1, z, 0, 0); world.setBlock(x, y + 2, z, block.blockID); world.setBlockMetadataWithNotify(x, y + 2, z, 1, 0); placed = random.nextBoolean(); y -= 10; added++; //System.out.println(x + ", " + y + ", " + z); } } } } } }
diff --git a/src/java-common/org/xins/common/text/TextUtils.java b/src/java-common/org/xins/common/text/TextUtils.java index f4ee16c..e52c0f1 100644 --- a/src/java-common/org/xins/common/text/TextUtils.java +++ b/src/java-common/org/xins/common/text/TextUtils.java @@ -1,650 +1,650 @@ /* * $Id: TextUtils.java,v 1.29 2007/05/22 09:36:09 agoubard Exp $ * * Copyright 2003-2007 Orange Nederland Breedband B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.common.text; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.Properties; import java.security.MessageDigest; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.ProgrammingException; import org.xins.common.Utils; /** * Text-related utility functions. * * @version $Revision: 1.29 $ $Date: 2007/05/22 09:36:09 $ * @author <a href="mailto:[email protected]">Ernst de Haan</a> * * @since XINS 1.0.0 */ public final class TextUtils { /** * Constructs a new <code>TextUtils</code> object. */ private TextUtils() { // empty } /** * Quotes the specified string, or returns <code>"(null)"</code> if it is * <code>null</code>. * * @param s * the input string, or <code>null</code>. * * @return * if <code>s != null</code> the quoted string, otherwise the string * <code>"(null)"</code>. */ public static String quote(String s) { return s == null ? "(null)" : "\"" + s + '"'; } /** * Quotes the textual presentation (returned by <code>toString()</code>) of * the specified object, or returns <code>"(null)"</code> if the object is * <code>null</code>. * * @param o * the object, or <code>null</code>. * * @return * if <code>o != null</code> then <code>o.toString()</code> quoted, * otherwise the string <code>"(null)"</code>. * * @since XINS 1.0.1 */ public static String quote(Object o) { String s = (o == null) ? null : o.toString(); return quote(s); } /** * Determines if the specified string is <code>null</code> or an empty * string. * * @param s * the string, or <code>null</code>. * * @return * <code>true</code> if <code>s == null || s.length() &lt; 1</code>. * * @since XINS 1.0.1 */ public static boolean isEmpty(String s) { return (s == null) || (s.length() == 0); } /** * Determines if the specified string is <code>null</code> or an empty * string, optionally considering whitespace as empty. * * @param s * the string, or <code>null</code>. * * @param trim * flag that indicates whether the string should be trimmed before * checking if the length is 0. * * @return * <code>true</code> if the specified string is <code>null</code> or * empty. * * @since XINS 3.0 */ public static boolean isEmpty(String s, boolean trim) { if (s == null) { return true; } else if (s.length() == 0) { return true; } else if (trim && s.trim().length() == 0) { return true; } else { return false; } } /** * Trims the specified string, or returns the indicated string if the * argument is <code>null</code>. * * @param s * the string, or <code>null</code>. * * @param ifEmpty * the string to return if * <code>s == null || s.trim().length &lt; 1</code>; * can itself be <code>null</code>. * * @return * the trimmed version of the string (see {@link String#trim()}) or * (in case <code>s == null</code> or <code>s.trim().length &lt; 1</code>): * <code>ifEmpty</code>. * * @since XINS 1.3.0 */ public static String trim(String s, String ifEmpty) { if (s != null) { s = s.trim(); if (s.length() >= 1) { return s; } } return ifEmpty; } /** * Removes all leading and trailing whitespace from a string, and replaces * all internal whitespace with a single space character. * If <code>null</code> is passed, then <code>""</code> is returned. * * @param s * the string, or <code>null</code>. * * @return * the string with all leading and trailing whitespace removed and all * internal whitespace normalized, never <code>null</code>. * * @since XINS 3.0 */ public static String normalizeWhitespace(String s) { String normalized = ""; if (s != null) { s = s.trim(); boolean prevIsWhitespace = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean thisIsWhitespace = (c <= 0x20); if (thisIsWhitespace && prevIsWhitespace) { // skip this one } else if (thisIsWhitespace) { normalized += ' '; prevIsWhitespace = true; } else { normalized += c; prevIsWhitespace = false; } } } return normalized; } /** * Removes all whitespace from a string. * If <code>null</code> is passed, then <code>""</code> is returned. * * @param s * the string, or <code>null</code>. * * @return * a string without any whitespace characters, * never <code>null</code>. * * @since XINS 3.0 */ public static String removeWhitespace(String s) { String normalized = ""; if (s != null) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean thisIsWhitespace = (c <= 0x20); if (thisIsWhitespace) { // skip this one } else { normalized += c; } } } return normalized; } /** * Replaces substrings in a string. The substrings to be replaced are * passed in a {@link Properties} object. A prefix and a suffix can be * specified. These are prepended/appended to each of the search keys. * * <p />Example: If you have a string <code>"Hello ${name}"</code> and you * would like to replace <code>"${name}"</code> with <code>"John"</code> * and you would like to replace <code>${surname}</code> with * <code>"Doe"</code>, use the following code: * * <p /><blockquote><code>String s = "Hello ${name}"; * <br />Properties replacements = new Properties(); * <br />replacements.put("name", "John"); * <br />replacements.put("surname", "Doe"); * <br /> * <br />StringUtils.replace(s, replacements, "${", "}");</code></blockquote> * * <p />The result string will be <code>"Hello John"</code>. * * @param s * the text string to which replacements should be applied, not <code>null</code>. * * @param replacements * the replacements to apply, not <code>null</code>. * * @param prefix * the optional prefix for the search keys, or <code>null</code>. * * @param suffix * the optional prefix for the search keys, or <code>null</code>. * * @return the String with the replacements. * * @throws IllegalArgumentException * if one of the mandatory arguments is missing. * * @since XINS 1.4.0. */ public static String replace(String s, Properties replacements, String prefix, String suffix) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("s", s, "replacements", replacements); // Make sure prefix and suffix are not null prefix = (prefix == null) ? "" : prefix; suffix = (suffix == null) ? "" : suffix; Enumeration keys = replacements.propertyNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String search = prefix + key + suffix; int index = s.indexOf(search); while (index >= 0) { String replacement = replacements.getProperty(key); s = s.substring(0, index) + replacement + s.substring(index + search.length()); index = s.indexOf(search); } } return s; } /** * Tranforms the given <code>String</code> to the similar <code>String</code>, * but starting with an uppercase. * * @param text * the text to transform, can be <code>null</code> * * @return * the transformed text, the return value will start with an uppercase. * <code>null</code> is returned if the text was <code>null</code>. * * @since XINS 2.0. */ public static String firstCharUpper(String text) { if (text == null) { return null; } else if (text.length() == 0) { return text; } else if (!Character.isLowerCase(text.charAt(0))) { return text; } else if (text.length() == 1) { return text.toUpperCase(); } else { return text.substring(0, 1).toUpperCase() + text.substring(1); } } /** * Tranforms the given <code>String</code> to the similar <code>String</code>, * but starting with a lowercase. * * @param text * the text to transform, can be <code>null</code> * * @return * the transformed text, the return value will start with a lowercase. * <code>null</code> is returned if the text was <code>null</code>. * * @since XINS 2.0. */ public static String firstCharLower(String text) { if (text == null) { return null; } else if (text.length() == 0) { return text; } else if (!Character.isUpperCase(text.charAt(0))) { return text; } else if (text.length() == 1) { return text.toLowerCase(); } else { return text.substring(0, 1).toLowerCase() + text.substring(1); } } /** * Removes the given character from the given <code>String</code>. * * @param charToRemove * the character that should be removed from the String. * * @param text * the text from which the charecter should be removed, can be <code>null</code>. * * @return * the text without the character or <code>null</code> if the input text is <code>null</code>. * * @since XINS 2.0. */ public static String removeCharacter(char charToRemove, String text) { if (text == null) { return null; } if (text.indexOf(charToRemove) == -1) { return text; } char[] inputText = text.toCharArray(); StringBuffer result = new StringBuffer(inputText.length); for (int i = 0; i < inputText.length; i++) { if (inputText[i] != charToRemove) { result.append(inputText[i]); } } if (result.length() == inputText.length) { return text; } else { return result.toString(); } } /** * Computes the message digest of the specified string. The text string is * first converted to bytes using the UTF-8 encoding. * * <p>If an unsupported algorithm is passed, then a * {@link ProgrammingException} will be thrown. * * <p>Hint: to convert the returned <code>byte</code> array to a string, * you may want to use {@link #hashToString(String,String)}. * * @param algorithm * the algorithm to use, such as <code>"SHA-1"</code>, * <code>"SHA-256"</code> or <code>"MD5"</code>; * cannot be <code>null</code>. * * @param s * the text {@link String} to hash, cannot be <code>null</code>. * * @return * the hash as a <code>byte</code> array, as a <code>long</code>. * * @throws IllegalArgumentException * if <code>algorithm == null || s == null</code> * * @since XINS 3.0 */ public static final byte[] hash(String algorithm, String s) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("algorithm", algorithm, "s", s); // Compute the message digest MessageDigest md = null; String className = "java.lang.String"; String methodName = "getBytes(java.lang.String)"; try { // Convert the string to bytes byte[] bytes = s.getBytes("UTF-8"); // Get a MessageDigest instance for the SHA-256 algorithm className = "MessageDigest"; methodName = "getInstance(java.lang.String)"; md = MessageDigest.getInstance(algorithm); // Add the bytes to the digest computer methodName = "update(byte[])"; md.update(bytes); // Something went wrong } catch (Throwable cause) { throw Utils.logProgrammingError(TextUtils.class.getName(), "hash(java.lang.String)", className, methodName, cause); } return md.digest(); } /** * Computes the message digest of the specified string and converts it to a * hex string. * * <p>If an unsupported algorithm is passed, then a * {@link ProgrammingException} will be thrown. * * @param algorithm * the algorithm to use, such as <code>"SHA-1"</code>, * <code>"SHA-256"</code> or <code>"MD5"</code>; * cannot be <code>null</code>. * * @param s * the text {@link String} to hash, cannot be <code>null</code>. * * @return * the hash, converted to a hex string, e.g. * <code>"7b0b662c93ccc19e"</code>, never <code>null</code>. * * @throws IllegalArgumentException * if <code>algorithm == null || s == null</code> * * @since XINS 3.0 */ public static final String hashToString(String algorithm, String s) throws IllegalArgumentException { return HexConverter.toHexString(hash(algorithm, s)); } /** * Returns the specified character string or <code>null</code> if the * string is empty. The function {@link #isEmpty(String)} is used to * determine if the string is considered empty. * * @param s * the character {@link String}, can be <code>null</code>. * * @return * the input string (<code>s</code>) if it is not empty, * otherwise <code>null</code>. * * @since XINS 3.0 */ public static final String nullIfEmpty(String s) { return TextUtils.isEmpty(s) ? null : s; } /** * Converts the specified string to bytes, using the UTF-8 encoding. This * method is equivalent to calling: * * <blockquote><pre>string.getBytes("UTF-8")</pre></blockquote> * * expect that this method does not throw a checked exception. * * @param string * the string to convert, cannot be <code>null</code>. * * @throws IllegalArgumentException * if <code>string == null</code>. * * @throws ProgrammingException * if the UTF-8 encoding is not supported. * * @since XINS 3.0 */ public static byte[] toUTF8(String string) throws IllegalArgumentException, ProgrammingException { // Check preconditions MandatoryArgumentChecker.check("string", string); String encoding = "UTF-8"; try { return string.getBytes(encoding); } catch (UnsupportedEncodingException cause) { throw Utils.logProgrammingError(Utils.class.getName(), "toUTF8(String)", "java.lang.String", "getBytes(String)", "Encoding \"" + encoding + "\" is not supported.", cause); } } /** * Converts the specified collection of strings into a textual list. For * example, consider a list with the following items: * * <ol> * <li><code>"bla"</code> * <li><code>"foo"</code> * <li><code>"bar"</code> * </li> * * <p>When this method is called with <code>between</code> set to * <code>", "</code> and <code>beforeLast</code> set to * <code>" and "</code>, the result is: * * <blockquote><pre>"bla, foo and bar"</pre></blockquote> * * @param input * the elements, cannot be <code>null</code>. * * @param between * the text in between items, except before the last one, * cannot be <code>null</code>. * * @param beforeLast * the text before the last item, * cannot be <code>null</code>. * * @param quote * flag that indicates if each item should be quoted * (see {@link #quote(String)}). * * @return * the result string, never <code>null</code>. * * @throws IllegalArgumentException * if <code>input == null * || between == null * || beforeLast == null</code>. * * @since XINS 3.0 */ public static String list(Collection input, String between, String beforeLast, boolean quote) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("input", input, "between", between, "beforeLast", beforeLast); // No items, empty result int itemCount = input.size(); if (itemCount < 1) { return ""; } // First one - Iterator<Object> iterator = input.iterator(); - Object item = iterator.next(); - String result = quote ? quote(item) : String.valueOf(item); + Iterator iterator = input.iterator(); + Object item = iterator.next(); + String result = quote ? quote(item) : String.valueOf(item); // All in between for (int i = 1; i < (itemCount - 1); i++) { result += between; item = iterator.next(); result += quote ? quote(item) : String.valueOf(item); } // Last one if (itemCount > 1) { result += beforeLast; item = iterator.next(); result += quote ? quote(item) : String.valueOf(item); } return result; } /** * Retrieves an enumeration item by name. A flag indicates if the character * string can be normalized before finding an enum item. * * @param enumType * the {@link Enum} class, cannot be <code>null</code>. * * @param name * the name of the item to find, cannot be <code>null</code>. * * @param fuzzy * <code>true</code> if a fuzzy match is allowed, * <code>false</code> if an exact match is required. * * @return * the matching {@link Enum} item, * or <code>null</code> if none could be found. * * @throws IllegalArgumentException * if <code>enumType == null || name == null</code>. * * @since XINS 3.0 */ public static final <T extends Enum<T>> T getEnumItem(Class<T> enumType, String name, boolean fuzzy) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("enumType", enumType, "name", name); if (fuzzy) { name = name.trim().replaceAll("\\s+", "_").toUpperCase(); } // Find an enum item by that name try { return Enum.valueOf(enumType, name); // No such Enum item } catch (IllegalArgumentException cause) { return null; } } /** * Retrieves an enumeration item by name, normalizing the name. * * @param enumType * the {@link Enum} class, cannot be <code>null</code>. * * @param name * the name of the item to find, cannot be <code>null</code>. * * @return * the matching {@link Enum} item, * or <code>null</code> if none could be found. * * @throws IllegalArgumentException * if <code>enumType == null || name == null</code>. * * @since XINS 3.0 */ public static final <T extends Enum<T>> T getEnumItem(Class<T> enumType, String name) throws IllegalArgumentException { return getEnumItem(enumType, name, true); } }
true
true
public static String list(Collection input, String between, String beforeLast, boolean quote) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("input", input, "between", between, "beforeLast", beforeLast); // No items, empty result int itemCount = input.size(); if (itemCount < 1) { return ""; } // First one Iterator<Object> iterator = input.iterator(); Object item = iterator.next(); String result = quote ? quote(item) : String.valueOf(item); // All in between for (int i = 1; i < (itemCount - 1); i++) { result += between; item = iterator.next(); result += quote ? quote(item) : String.valueOf(item); } // Last one if (itemCount > 1) { result += beforeLast; item = iterator.next(); result += quote ? quote(item) : String.valueOf(item); } return result; }
public static String list(Collection input, String between, String beforeLast, boolean quote) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("input", input, "between", between, "beforeLast", beforeLast); // No items, empty result int itemCount = input.size(); if (itemCount < 1) { return ""; } // First one Iterator iterator = input.iterator(); Object item = iterator.next(); String result = quote ? quote(item) : String.valueOf(item); // All in between for (int i = 1; i < (itemCount - 1); i++) { result += between; item = iterator.next(); result += quote ? quote(item) : String.valueOf(item); } // Last one if (itemCount > 1) { result += beforeLast; item = iterator.next(); result += quote ? quote(item) : String.valueOf(item); } return result; }
diff --git a/bootstrap/WyvernCompiler/src/compiler/lex/CharLexerGenerator.java b/bootstrap/WyvernCompiler/src/compiler/lex/CharLexerGenerator.java index 8845f98..efbac1c 100644 --- a/bootstrap/WyvernCompiler/src/compiler/lex/CharLexerGenerator.java +++ b/bootstrap/WyvernCompiler/src/compiler/lex/CharLexerGenerator.java @@ -1,135 +1,136 @@ /** * */ package compiler.lex; import java.io.*; import java.util.*; import compiler.*; /** * A simple lexer generator which handles only single-character strings and the * empty string (the empty string is interpreted as matching any character) * * @author Michael */ public class CharLexerGenerator extends LexerGenerator.AbstractLexerGenerator { @Override protected Result generateImpl(final Context context, LinkedHashSet<LexerAction> allActions, final Map<String, LinkedHashMap<String, LexerAction>> groupedActions) { for (LexerAction la : allActions) Utils.check(la.pattern().length() <= 1, String.format("Pattern \"%s\" is too long!", la.pattern())); final Lexer lexer = new Lexer() { @Override public boolean isCompiled() { return false; } @Override public Iterator<Symbol> lex(Reader reader) { + @SuppressWarnings("resource") // valid since the inner reader will be closed by the caller final LineNumberAndPositionBufferedReader bufferedReader = new LineNumberAndPositionBufferedReader( reader); return new Iterator<Symbol>() { private boolean sentEOF = false; private Deque<String> stateStack = new ArrayDeque<String>( LexerAction.DEFAULT_SET); private LinkedHashMap<String, LexerAction> stateActions = groupedActions .get(Lexer.DEFAULT_STATE); @Override public boolean hasNext() { return !this.sentEOF; } @Override public Symbol next() { SymbolType tokenType = null; Symbol token = null; // loop until we find a token to return or send eof do { // read the next character int c = bufferedReader.uncheckedRead(); // if there are no more chars to send, send eof if (c == -1) { if (!this.hasNext()) throw new NoSuchElementException(); this.sentEOF = true; return context.eofType().createSymbol("", bufferedReader.lineNumber(), bufferedReader.position()); } String text = String.valueOf((char) c); LexerAction action = this.stateActions.get(text); if (action == null) action = this.stateActions.get(""); if (action == null) { tokenType = context.unrecognizedType(); } else { tokenType = action.symbolType(); switch (action.actionType()) { case Swap: this.stateStack.pop(); // fall through case Enter: this.stateStack.push(action.endState()); this.stateActions = groupedActions .get(action.endState()); break; case Leave: this.stateStack.pop(); this.stateActions = groupedActions .get(this.stateStack.peekFirst()); break; case None: break; } } // if we have a token type, create a token if (tokenType != null) token = tokenType.createSymbol(text, bufferedReader.lineNumber(), bufferedReader.position()); } while (token == null); return token; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }; } }; return new LexerGenerator.Result() { @Override public List<String> warnings() { return Collections.emptyList(); } @Override public Lexer lexer() { return lexer; } @Override public List<String> errors() { return Collections.emptyList(); } }; } }
true
true
protected Result generateImpl(final Context context, LinkedHashSet<LexerAction> allActions, final Map<String, LinkedHashMap<String, LexerAction>> groupedActions) { for (LexerAction la : allActions) Utils.check(la.pattern().length() <= 1, String.format("Pattern \"%s\" is too long!", la.pattern())); final Lexer lexer = new Lexer() { @Override public boolean isCompiled() { return false; } @Override public Iterator<Symbol> lex(Reader reader) { final LineNumberAndPositionBufferedReader bufferedReader = new LineNumberAndPositionBufferedReader( reader); return new Iterator<Symbol>() { private boolean sentEOF = false; private Deque<String> stateStack = new ArrayDeque<String>( LexerAction.DEFAULT_SET); private LinkedHashMap<String, LexerAction> stateActions = groupedActions .get(Lexer.DEFAULT_STATE); @Override public boolean hasNext() { return !this.sentEOF; } @Override public Symbol next() { SymbolType tokenType = null; Symbol token = null; // loop until we find a token to return or send eof do { // read the next character int c = bufferedReader.uncheckedRead(); // if there are no more chars to send, send eof if (c == -1) { if (!this.hasNext()) throw new NoSuchElementException(); this.sentEOF = true; return context.eofType().createSymbol("", bufferedReader.lineNumber(), bufferedReader.position()); } String text = String.valueOf((char) c); LexerAction action = this.stateActions.get(text); if (action == null) action = this.stateActions.get(""); if (action == null) { tokenType = context.unrecognizedType(); } else { tokenType = action.symbolType(); switch (action.actionType()) { case Swap: this.stateStack.pop(); // fall through case Enter: this.stateStack.push(action.endState()); this.stateActions = groupedActions .get(action.endState()); break; case Leave: this.stateStack.pop(); this.stateActions = groupedActions .get(this.stateStack.peekFirst()); break; case None: break; } } // if we have a token type, create a token if (tokenType != null) token = tokenType.createSymbol(text, bufferedReader.lineNumber(), bufferedReader.position()); } while (token == null); return token; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }; } }; return new LexerGenerator.Result() { @Override public List<String> warnings() { return Collections.emptyList(); } @Override public Lexer lexer() { return lexer; } @Override public List<String> errors() { return Collections.emptyList(); } }; }
protected Result generateImpl(final Context context, LinkedHashSet<LexerAction> allActions, final Map<String, LinkedHashMap<String, LexerAction>> groupedActions) { for (LexerAction la : allActions) Utils.check(la.pattern().length() <= 1, String.format("Pattern \"%s\" is too long!", la.pattern())); final Lexer lexer = new Lexer() { @Override public boolean isCompiled() { return false; } @Override public Iterator<Symbol> lex(Reader reader) { @SuppressWarnings("resource") // valid since the inner reader will be closed by the caller final LineNumberAndPositionBufferedReader bufferedReader = new LineNumberAndPositionBufferedReader( reader); return new Iterator<Symbol>() { private boolean sentEOF = false; private Deque<String> stateStack = new ArrayDeque<String>( LexerAction.DEFAULT_SET); private LinkedHashMap<String, LexerAction> stateActions = groupedActions .get(Lexer.DEFAULT_STATE); @Override public boolean hasNext() { return !this.sentEOF; } @Override public Symbol next() { SymbolType tokenType = null; Symbol token = null; // loop until we find a token to return or send eof do { // read the next character int c = bufferedReader.uncheckedRead(); // if there are no more chars to send, send eof if (c == -1) { if (!this.hasNext()) throw new NoSuchElementException(); this.sentEOF = true; return context.eofType().createSymbol("", bufferedReader.lineNumber(), bufferedReader.position()); } String text = String.valueOf((char) c); LexerAction action = this.stateActions.get(text); if (action == null) action = this.stateActions.get(""); if (action == null) { tokenType = context.unrecognizedType(); } else { tokenType = action.symbolType(); switch (action.actionType()) { case Swap: this.stateStack.pop(); // fall through case Enter: this.stateStack.push(action.endState()); this.stateActions = groupedActions .get(action.endState()); break; case Leave: this.stateStack.pop(); this.stateActions = groupedActions .get(this.stateStack.peekFirst()); break; case None: break; } } // if we have a token type, create a token if (tokenType != null) token = tokenType.createSymbol(text, bufferedReader.lineNumber(), bufferedReader.position()); } while (token == null); return token; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } }; } }; return new LexerGenerator.Result() { @Override public List<String> warnings() { return Collections.emptyList(); } @Override public Lexer lexer() { return lexer; } @Override public List<String> errors() { return Collections.emptyList(); } }; }
diff --git a/src/main/java/DataStorage/regalowl/hyperconomy/HyperPlayer.java b/src/main/java/DataStorage/regalowl/hyperconomy/HyperPlayer.java index f6e43c5..366d523 100644 --- a/src/main/java/DataStorage/regalowl/hyperconomy/HyperPlayer.java +++ b/src/main/java/DataStorage/regalowl/hyperconomy/HyperPlayer.java @@ -1,118 +1,118 @@ package regalowl.hyperconomy; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class HyperPlayer { private HyperConomy hc; private String name; private String economy; private double balance; private double x; private double y; private double z; private String world; private String hash; HyperPlayer() { hc = HyperConomy.hc; } HyperPlayer(String player) { hc = HyperConomy.hc; SQLWrite sw = hc.getSQLWrite(); for (Player p:Bukkit.getOnlinePlayers()) { if (p.getName().equalsIgnoreCase(player)) { name = p.getName(); economy = "default"; balance = 0.0; x = p.getLocation().getX(); y = p.getLocation().getY(); z = p.getLocation().getZ(); world = p.getLocation().getWorld().getName(); - sw.executeSQL("INSERT INTO hyperconomy_players (PLAYER, ECONOMY, BALANCE)" + " VALUES ('" + name + "','" + economy + "','" + balance + "')"); + sw.executeSQL("INSERT INTO hyperconomy_players (PLAYER, ECONOMY, BALANCE, X, Y, Z, WORLD, HASH)" + " VALUES ('" + name + "','" + economy + "','" + balance + "','" + x + "','" + y + "','" + z + "','" + world + "','" + "none" + "')"); return; } } name = player; economy = "default"; balance = 0.0; - sw.executeSQL("INSERT INTO hyperconomy_players (PLAYER, ECONOMY, BALANCE)" + " VALUES ('" + name + "','" + economy + "','" + balance + "')"); + sw.executeSQL("INSERT INTO hyperconomy_players (PLAYER, ECONOMY, BALANCE, X, Y, Z, WORLD, HASH)" + " VALUES ('" + name + "','" + economy + "','" + balance + "','" + 0 + "','" + 0 + "','" + 0 + "','" + "world" + "','" + "none" + "')"); } public String getName() { return name; } public String getEconomy() { return economy; } public double getBalance() { return balance; } public double getX() { return x; } public double getY() { return y; } public double getZ() { return z; } public String getWorld() { return world; } public String getHash() { return hash; } public void setName(String name) { String statement = "UPDATE hyperconomy_players SET PLAYER='" + name + "' WHERE PLAYER = '" + this.name + "'"; hc.getSQLWrite().executeSQL(statement); this.name = name; } public void setEconomy(String economy) { String statement = "UPDATE hyperconomy_players SET ECONOMY='" + economy + "' WHERE PLAYER = '" + name + "'"; hc.getSQLWrite().executeSQL(statement); this.economy = economy; } public void setBalance(double balance) { String statement = "UPDATE hyperconomy_players SET BALANCE='" + balance + "' WHERE PLAYER = '" + name + "'"; hc.getSQLWrite().executeSQL(statement); this.balance = balance; } public void setX(double x) { String statement = "UPDATE hyperconomy_players SET X='" + x + "' WHERE PLAYER = '" + name + "'"; hc.getSQLWrite().executeSQL(statement); this.x = x; } public void setY(double y) { String statement = "UPDATE hyperconomy_players SET Y='" + y + "' WHERE PLAYER = '" + name + "'"; hc.getSQLWrite().executeSQL(statement); this.y = y; } public void setZ(double z) { String statement = "UPDATE hyperconomy_players SET Z='" + z + "' WHERE PLAYER = '" + name + "'"; hc.getSQLWrite().executeSQL(statement); this.z = z; } public void setWorld(String world) { String statement = "UPDATE hyperconomy_players SET WORLD='" + world + "' WHERE PLAYER = '" + name + "'"; hc.getSQLWrite().executeSQL(statement); this.world = world; } public void setHash(String hash) { String statement = "UPDATE hyperconomy_players SET HASH='" + hash + "' WHERE PLAYER = '" + name + "'"; hc.getSQLWrite().executeSQL(statement); this.hash = hash; } }
false
true
HyperPlayer(String player) { hc = HyperConomy.hc; SQLWrite sw = hc.getSQLWrite(); for (Player p:Bukkit.getOnlinePlayers()) { if (p.getName().equalsIgnoreCase(player)) { name = p.getName(); economy = "default"; balance = 0.0; x = p.getLocation().getX(); y = p.getLocation().getY(); z = p.getLocation().getZ(); world = p.getLocation().getWorld().getName(); sw.executeSQL("INSERT INTO hyperconomy_players (PLAYER, ECONOMY, BALANCE)" + " VALUES ('" + name + "','" + economy + "','" + balance + "')"); return; } } name = player; economy = "default"; balance = 0.0; sw.executeSQL("INSERT INTO hyperconomy_players (PLAYER, ECONOMY, BALANCE)" + " VALUES ('" + name + "','" + economy + "','" + balance + "')"); }
HyperPlayer(String player) { hc = HyperConomy.hc; SQLWrite sw = hc.getSQLWrite(); for (Player p:Bukkit.getOnlinePlayers()) { if (p.getName().equalsIgnoreCase(player)) { name = p.getName(); economy = "default"; balance = 0.0; x = p.getLocation().getX(); y = p.getLocation().getY(); z = p.getLocation().getZ(); world = p.getLocation().getWorld().getName(); sw.executeSQL("INSERT INTO hyperconomy_players (PLAYER, ECONOMY, BALANCE, X, Y, Z, WORLD, HASH)" + " VALUES ('" + name + "','" + economy + "','" + balance + "','" + x + "','" + y + "','" + z + "','" + world + "','" + "none" + "')"); return; } } name = player; economy = "default"; balance = 0.0; sw.executeSQL("INSERT INTO hyperconomy_players (PLAYER, ECONOMY, BALANCE, X, Y, Z, WORLD, HASH)" + " VALUES ('" + name + "','" + economy + "','" + balance + "','" + 0 + "','" + 0 + "','" + 0 + "','" + "world" + "','" + "none" + "')"); }
diff --git a/jmbs_maven/Client/src/main/java/jmbs/client/Graphics/ProfilePanel.java b/jmbs_maven/Client/src/main/java/jmbs/client/Graphics/ProfilePanel.java index ba2f2fa..2fa7042 100644 --- a/jmbs_maven/Client/src/main/java/jmbs/client/Graphics/ProfilePanel.java +++ b/jmbs_maven/Client/src/main/java/jmbs/client/Graphics/ProfilePanel.java @@ -1,388 +1,388 @@ /* * JMBS: Java Micro Blogging System * * Copyright (C) 2012 * * 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. * 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/>. * @author Younes CHEIKH http://cyounes.com * @author Benjamin Babic http://bbabic.com * */ package jmbs.client.Graphics; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JSeparator; import javax.swing.SwingConstants; import java.awt.Font; import java.awt.Color; import javax.swing.JTextField; import javax.swing.JPasswordField; import javax.swing.JButton; import jmbs.client.CurrentUser; import jmbs.client.HashPassword; import jmbs.client.RemoteRequests; import jmbs.common.User; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.HashMap; import java.util.regex.Pattern; public class ProfilePanel extends JPanel { /** * */ private static final long serialVersionUID = -398362580268810333L; private JTextField nameTextField; private JTextField fnameTextField; private JTextField emailTextField; private JPasswordField passwordField; private JPasswordField newpasswordField; private JPasswordField confirmpasswordField; private JTextField textField; /** * Create * the * panel. */ public ProfilePanel(User currentUser) { JLabel lblName = new JLabel("Name:"); lblName.setBounds(9, 46, 40, 16); JLabel lblLastName = new JLabel("Last Name:"); lblLastName.setBounds(9, 86, 70, 16); JLabel lblEmailAdress = new JLabel("Email Adress:"); lblEmailAdress.setBounds(9, 126, 85, 16); JSeparator separator = new JSeparator(); separator.setBounds(9, 154, 267, 12); JLabel lblPublicInformations = new JLabel("Public Informations"); lblPublicInformations.setBounds(84, 8, 162, 20); lblPublicInformations.setHorizontalAlignment(SwingConstants.CENTER); lblPublicInformations.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JLabel lblChangePassword = new JLabel("Change Password"); lblChangePassword.setBounds(82, 172, 163, 20); lblChangePassword.setForeground(Color.RED); lblChangePassword.setHorizontalAlignment(SwingConstants.CENTER); lblChangePassword.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JLabel lblOldPassword = new JLabel("Old Password:"); lblOldPassword.setBounds(6, 204, 89, 16); JLabel lblNewPassword = new JLabel("New Password:"); lblNewPassword.setBounds(6, 238, 94, 16); JLabel lblConfirmPassword = new JLabel("Confirm Password:"); lblConfirmPassword.setBounds(9, 272, 118, 16); nameTextField = new JTextField(currentUser.getName()); nameTextField.setBorder(BorderFactory.createLineBorder(null)); nameTextField.setBounds(142, 40, 180, 28); nameTextField.setColumns(10); fnameTextField = new JTextField(currentUser.getFname()); fnameTextField.setBounds(142, 80, 180, 28); fnameTextField.setColumns(10); fnameTextField.setBorder(BorderFactory.createLineBorder(null)); emailTextField = new JTextField(currentUser.getMail()); emailTextField.setBounds(142, 120, 180, 28); emailTextField.setColumns(10); emailTextField.setBorder(BorderFactory.createLineBorder(null)); passwordField = new JPasswordField(); passwordField.setBounds(142, 198, 180, 28); passwordField.setBorder(BorderFactory.createLineBorder(null)); newpasswordField = new JPasswordField(); newpasswordField.setBounds(142, 232, 180, 28); newpasswordField.setBorder(BorderFactory.createLineBorder(null)); confirmpasswordField = new JPasswordField(); confirmpasswordField.setBounds(142, 266, 180, 28); confirmpasswordField.setBorder(BorderFactory.createLineBorder(null)); JPanel panel = new JPanel(); panel.setBounds(6, 324, 70, 70); panel.setBackground(Color.GRAY); JSeparator separator_1 = new JSeparator(); separator_1.setBounds(9, 306, 264, 12); JLabel lblProfilePicture = new JLabel("Profile Picture"); lblProfilePicture.setBounds(88, 326, 115, 20); lblProfilePicture.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JButton btnUploadNewPhoto = new JButton("Upload"); btnUploadNewPhoto.setBounds(263, 365, 89, 29); textField = new JTextField(); textField.setBounds(84, 364, 159, 28); textField.setColumns(10); setLayout(null); add(lblPublicInformations); add(lblChangePassword); add(lblOldPassword); add(newpasswordField); add(passwordField); add(lblNewPassword); add(lblProfilePicture); add(separator); add(lblName); add(lblLastName); add(lblEmailAdress); add(emailTextField); add(fnameTextField); add(nameTextField); add(panel); add(textField); add(btnUploadNewPhoto); add(separator_1); add(lblConfirmPassword); add(confirmpasswordField); JSeparator separator_2 = new JSeparator(); separator_2.setBounds(9, 406, 343, 12); add(separator_2); JButton btnUpdate = new JButton("Update"); btnUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // This hashMap contains the values which we want to update HashMap<String, Boolean> valuesToEdit = new HashMap<String, Boolean>(); // Put the values we want to edit in the HashMap with the false // as default if (passwordChanged()) { valuesToEdit.put("pass", false); } if (nameEdited()) { valuesToEdit.put("name", false); } if (fNameEdited()) { valuesToEdit.put("fname", false); } if (mailEdited()) { valuesToEdit.put("mail", false); } // Coloring the textFileds if (valuesToEdit.containsKey("pass")) { if (newPassConfirmed()) { valuesToEdit.put("pass", true); newpasswordField.setBorder(BorderFactory.createLineBorder(Color.green)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { newpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("name")) { if (!nameTextField.getText().equals(CurrentUser.getName()) && nameTextField.getText().length() > 0) { valuesToEdit.put("name", true); nameTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { nameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("fname")) { if (!fnameTextField.getText().equals(CurrentUser.getFname()) && fnameTextField.getText().length() > 0) { valuesToEdit.put("fname", true); fnameTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { fnameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("mail")) { if (!emailTextField.getText().equals(CurrentUser.getMail()) && Pattern.matches( "^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)+$", emailTextField.getText()) && passwordField.getPassword().length >= 4) { valuesToEdit.put("mail", true); emailTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { emailTextField.setBorder(BorderFactory.createLineBorder(Color.red)); passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } HashMap<String, Boolean> editingResults = new HashMap<String, Boolean>(); if (!valuesToEdit.containsValue(false)) { if (valuesToEdit.containsKey("name")) { editingResults.put("name", RemoteRequests.changName( CurrentUser.getId(), nameTextField.getText())); } if (valuesToEdit.containsKey("fname")) { editingResults.put("fname", RemoteRequests.changeFname( CurrentUser.getId(), fnameTextField.getText())); } if (valuesToEdit.containsKey("mail")) { editingResults.put("mail", RemoteRequests.changeMail( CurrentUser.getId(), new HashPassword( passwordField.getPassword()).getHashed(), emailTextField.getText())); } if (valuesToEdit.containsKey("pass")) { editingResults.put("pass", RemoteRequests.changePassword( CurrentUser.getId(), new HashPassword(passwordField.getPassword()).getHashed(), - new HashPassword(passwordField.getPassword()).getHashed())); + new HashPassword(newpasswordField.getPassword()).getHashed())); } String updateSucess = "<b>Updates : <b><br />"; String updateFailure = "<b>Failures : </b><br />"; if (editingResults.containsKey("name")) { if (editingResults.get("name")) { updateSucess += "name<br />"; CurrentUser.get().setName(nameTextField.getText()); } else { updateFailure += "name<br />"; nameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("fname")) { if (editingResults.get("fname")) { updateSucess += "forname<br />"; CurrentUser.get().setFname(fnameTextField.getText()); } else { updateFailure += "forname<br />"; fnameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("mail")) { if (editingResults.get("mail")) { updateSucess += "Email Adress<br />"; CurrentUser.get().setMail(emailTextField.getText()); } else { updateFailure += "Email Adress<br />"; emailTextField.setBorder(BorderFactory.createLineBorder(Color.red)); passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("pass")) { if (editingResults.get("pass")) { updateSucess += "Password<br />"; } else { updateFailure += "Password<br />"; passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); newpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (!updateSucess.equals("<b>Updates : <b><br />")) { if (updateFailure.equals("<b>Failures : </b><br />")) { SayToUser.success("Update Successed", updateSucess); } else { SayToUser.warning("Update Warning", updateSucess + updateFailure); } } else if (!updateFailure.equals("<b>Failures : </b><br />")) { SayToUser.error("Update Failure", updateFailure); } else { SayToUser.warning("", "No thing to update :)"); } if (!mailEdited() && !passwordChanged()) { passwordField.setBorder(BorderFactory.createLineBorder(Color.black)); } } } }); btnUpdate.setBounds(116, 425, 117, 29); add(btnUpdate); } public void resetAll(User currentUser) { nameTextField.setText(currentUser.getName()); fnameTextField.setText(currentUser.getFname()); emailTextField.setText(currentUser.getMail()); } private boolean passwordChanged() { boolean retVal = false; if (newpasswordField.getPassword().length > 0 || confirmpasswordField.getPassword().length > 0) { retVal = true; } else { newpasswordField.setBorder(BorderFactory.createLineBorder(Color.black)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.black)); } return retVal; } private boolean nameEdited() { boolean retVal = false; if (!nameTextField.getText().equals(CurrentUser.getName())) { retVal = true; } else { nameTextField.setBorder(BorderFactory.createLineBorder(Color.black)); } return retVal; } private boolean fNameEdited() { boolean retVal = false; if (!fnameTextField.getText().equals(CurrentUser.getFname())) { retVal = true; } else { fnameTextField.setBorder(BorderFactory.createLineBorder(Color.black)); } return retVal; } private boolean mailEdited() { boolean retVal = false; if (!emailTextField.getText().equals(CurrentUser.getMail())) { retVal = true; } else { emailTextField.setBorder(BorderFactory.createLineBorder(Color.black)); } return retVal; } private boolean newPassConfirmed() { boolean passConfirmed = newpasswordField.getPassword().length == confirmpasswordField.getPassword().length; if (!passConfirmed) { return false; } passConfirmed = newpasswordField.getPassword().length >= 4; if (passConfirmed) { for (int i = 0; i < newpasswordField.getPassword().length; i++) { if (newpasswordField.getPassword()[i] != confirmpasswordField.getPassword()[i]) { passConfirmed = false; break; } } } return passConfirmed; } }
true
true
public ProfilePanel(User currentUser) { JLabel lblName = new JLabel("Name:"); lblName.setBounds(9, 46, 40, 16); JLabel lblLastName = new JLabel("Last Name:"); lblLastName.setBounds(9, 86, 70, 16); JLabel lblEmailAdress = new JLabel("Email Adress:"); lblEmailAdress.setBounds(9, 126, 85, 16); JSeparator separator = new JSeparator(); separator.setBounds(9, 154, 267, 12); JLabel lblPublicInformations = new JLabel("Public Informations"); lblPublicInformations.setBounds(84, 8, 162, 20); lblPublicInformations.setHorizontalAlignment(SwingConstants.CENTER); lblPublicInformations.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JLabel lblChangePassword = new JLabel("Change Password"); lblChangePassword.setBounds(82, 172, 163, 20); lblChangePassword.setForeground(Color.RED); lblChangePassword.setHorizontalAlignment(SwingConstants.CENTER); lblChangePassword.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JLabel lblOldPassword = new JLabel("Old Password:"); lblOldPassword.setBounds(6, 204, 89, 16); JLabel lblNewPassword = new JLabel("New Password:"); lblNewPassword.setBounds(6, 238, 94, 16); JLabel lblConfirmPassword = new JLabel("Confirm Password:"); lblConfirmPassword.setBounds(9, 272, 118, 16); nameTextField = new JTextField(currentUser.getName()); nameTextField.setBorder(BorderFactory.createLineBorder(null)); nameTextField.setBounds(142, 40, 180, 28); nameTextField.setColumns(10); fnameTextField = new JTextField(currentUser.getFname()); fnameTextField.setBounds(142, 80, 180, 28); fnameTextField.setColumns(10); fnameTextField.setBorder(BorderFactory.createLineBorder(null)); emailTextField = new JTextField(currentUser.getMail()); emailTextField.setBounds(142, 120, 180, 28); emailTextField.setColumns(10); emailTextField.setBorder(BorderFactory.createLineBorder(null)); passwordField = new JPasswordField(); passwordField.setBounds(142, 198, 180, 28); passwordField.setBorder(BorderFactory.createLineBorder(null)); newpasswordField = new JPasswordField(); newpasswordField.setBounds(142, 232, 180, 28); newpasswordField.setBorder(BorderFactory.createLineBorder(null)); confirmpasswordField = new JPasswordField(); confirmpasswordField.setBounds(142, 266, 180, 28); confirmpasswordField.setBorder(BorderFactory.createLineBorder(null)); JPanel panel = new JPanel(); panel.setBounds(6, 324, 70, 70); panel.setBackground(Color.GRAY); JSeparator separator_1 = new JSeparator(); separator_1.setBounds(9, 306, 264, 12); JLabel lblProfilePicture = new JLabel("Profile Picture"); lblProfilePicture.setBounds(88, 326, 115, 20); lblProfilePicture.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JButton btnUploadNewPhoto = new JButton("Upload"); btnUploadNewPhoto.setBounds(263, 365, 89, 29); textField = new JTextField(); textField.setBounds(84, 364, 159, 28); textField.setColumns(10); setLayout(null); add(lblPublicInformations); add(lblChangePassword); add(lblOldPassword); add(newpasswordField); add(passwordField); add(lblNewPassword); add(lblProfilePicture); add(separator); add(lblName); add(lblLastName); add(lblEmailAdress); add(emailTextField); add(fnameTextField); add(nameTextField); add(panel); add(textField); add(btnUploadNewPhoto); add(separator_1); add(lblConfirmPassword); add(confirmpasswordField); JSeparator separator_2 = new JSeparator(); separator_2.setBounds(9, 406, 343, 12); add(separator_2); JButton btnUpdate = new JButton("Update"); btnUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // This hashMap contains the values which we want to update HashMap<String, Boolean> valuesToEdit = new HashMap<String, Boolean>(); // Put the values we want to edit in the HashMap with the false // as default if (passwordChanged()) { valuesToEdit.put("pass", false); } if (nameEdited()) { valuesToEdit.put("name", false); } if (fNameEdited()) { valuesToEdit.put("fname", false); } if (mailEdited()) { valuesToEdit.put("mail", false); } // Coloring the textFileds if (valuesToEdit.containsKey("pass")) { if (newPassConfirmed()) { valuesToEdit.put("pass", true); newpasswordField.setBorder(BorderFactory.createLineBorder(Color.green)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { newpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("name")) { if (!nameTextField.getText().equals(CurrentUser.getName()) && nameTextField.getText().length() > 0) { valuesToEdit.put("name", true); nameTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { nameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("fname")) { if (!fnameTextField.getText().equals(CurrentUser.getFname()) && fnameTextField.getText().length() > 0) { valuesToEdit.put("fname", true); fnameTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { fnameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("mail")) { if (!emailTextField.getText().equals(CurrentUser.getMail()) && Pattern.matches( "^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)+$", emailTextField.getText()) && passwordField.getPassword().length >= 4) { valuesToEdit.put("mail", true); emailTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { emailTextField.setBorder(BorderFactory.createLineBorder(Color.red)); passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } HashMap<String, Boolean> editingResults = new HashMap<String, Boolean>(); if (!valuesToEdit.containsValue(false)) { if (valuesToEdit.containsKey("name")) { editingResults.put("name", RemoteRequests.changName( CurrentUser.getId(), nameTextField.getText())); } if (valuesToEdit.containsKey("fname")) { editingResults.put("fname", RemoteRequests.changeFname( CurrentUser.getId(), fnameTextField.getText())); } if (valuesToEdit.containsKey("mail")) { editingResults.put("mail", RemoteRequests.changeMail( CurrentUser.getId(), new HashPassword( passwordField.getPassword()).getHashed(), emailTextField.getText())); } if (valuesToEdit.containsKey("pass")) { editingResults.put("pass", RemoteRequests.changePassword( CurrentUser.getId(), new HashPassword(passwordField.getPassword()).getHashed(), new HashPassword(passwordField.getPassword()).getHashed())); } String updateSucess = "<b>Updates : <b><br />"; String updateFailure = "<b>Failures : </b><br />"; if (editingResults.containsKey("name")) { if (editingResults.get("name")) { updateSucess += "name<br />"; CurrentUser.get().setName(nameTextField.getText()); } else { updateFailure += "name<br />"; nameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("fname")) { if (editingResults.get("fname")) { updateSucess += "forname<br />"; CurrentUser.get().setFname(fnameTextField.getText()); } else { updateFailure += "forname<br />"; fnameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("mail")) { if (editingResults.get("mail")) { updateSucess += "Email Adress<br />"; CurrentUser.get().setMail(emailTextField.getText()); } else { updateFailure += "Email Adress<br />"; emailTextField.setBorder(BorderFactory.createLineBorder(Color.red)); passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("pass")) { if (editingResults.get("pass")) { updateSucess += "Password<br />"; } else { updateFailure += "Password<br />"; passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); newpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (!updateSucess.equals("<b>Updates : <b><br />")) { if (updateFailure.equals("<b>Failures : </b><br />")) { SayToUser.success("Update Successed", updateSucess); } else { SayToUser.warning("Update Warning", updateSucess + updateFailure); } } else if (!updateFailure.equals("<b>Failures : </b><br />")) { SayToUser.error("Update Failure", updateFailure); } else { SayToUser.warning("", "No thing to update :)"); } if (!mailEdited() && !passwordChanged()) { passwordField.setBorder(BorderFactory.createLineBorder(Color.black)); } } } }); btnUpdate.setBounds(116, 425, 117, 29); add(btnUpdate); }
public ProfilePanel(User currentUser) { JLabel lblName = new JLabel("Name:"); lblName.setBounds(9, 46, 40, 16); JLabel lblLastName = new JLabel("Last Name:"); lblLastName.setBounds(9, 86, 70, 16); JLabel lblEmailAdress = new JLabel("Email Adress:"); lblEmailAdress.setBounds(9, 126, 85, 16); JSeparator separator = new JSeparator(); separator.setBounds(9, 154, 267, 12); JLabel lblPublicInformations = new JLabel("Public Informations"); lblPublicInformations.setBounds(84, 8, 162, 20); lblPublicInformations.setHorizontalAlignment(SwingConstants.CENTER); lblPublicInformations.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JLabel lblChangePassword = new JLabel("Change Password"); lblChangePassword.setBounds(82, 172, 163, 20); lblChangePassword.setForeground(Color.RED); lblChangePassword.setHorizontalAlignment(SwingConstants.CENTER); lblChangePassword.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JLabel lblOldPassword = new JLabel("Old Password:"); lblOldPassword.setBounds(6, 204, 89, 16); JLabel lblNewPassword = new JLabel("New Password:"); lblNewPassword.setBounds(6, 238, 94, 16); JLabel lblConfirmPassword = new JLabel("Confirm Password:"); lblConfirmPassword.setBounds(9, 272, 118, 16); nameTextField = new JTextField(currentUser.getName()); nameTextField.setBorder(BorderFactory.createLineBorder(null)); nameTextField.setBounds(142, 40, 180, 28); nameTextField.setColumns(10); fnameTextField = new JTextField(currentUser.getFname()); fnameTextField.setBounds(142, 80, 180, 28); fnameTextField.setColumns(10); fnameTextField.setBorder(BorderFactory.createLineBorder(null)); emailTextField = new JTextField(currentUser.getMail()); emailTextField.setBounds(142, 120, 180, 28); emailTextField.setColumns(10); emailTextField.setBorder(BorderFactory.createLineBorder(null)); passwordField = new JPasswordField(); passwordField.setBounds(142, 198, 180, 28); passwordField.setBorder(BorderFactory.createLineBorder(null)); newpasswordField = new JPasswordField(); newpasswordField.setBounds(142, 232, 180, 28); newpasswordField.setBorder(BorderFactory.createLineBorder(null)); confirmpasswordField = new JPasswordField(); confirmpasswordField.setBounds(142, 266, 180, 28); confirmpasswordField.setBorder(BorderFactory.createLineBorder(null)); JPanel panel = new JPanel(); panel.setBounds(6, 324, 70, 70); panel.setBackground(Color.GRAY); JSeparator separator_1 = new JSeparator(); separator_1.setBounds(9, 306, 264, 12); JLabel lblProfilePicture = new JLabel("Profile Picture"); lblProfilePicture.setBounds(88, 326, 115, 20); lblProfilePicture.setFont(new Font("Lucida Grande", Font.BOLD, 16)); JButton btnUploadNewPhoto = new JButton("Upload"); btnUploadNewPhoto.setBounds(263, 365, 89, 29); textField = new JTextField(); textField.setBounds(84, 364, 159, 28); textField.setColumns(10); setLayout(null); add(lblPublicInformations); add(lblChangePassword); add(lblOldPassword); add(newpasswordField); add(passwordField); add(lblNewPassword); add(lblProfilePicture); add(separator); add(lblName); add(lblLastName); add(lblEmailAdress); add(emailTextField); add(fnameTextField); add(nameTextField); add(panel); add(textField); add(btnUploadNewPhoto); add(separator_1); add(lblConfirmPassword); add(confirmpasswordField); JSeparator separator_2 = new JSeparator(); separator_2.setBounds(9, 406, 343, 12); add(separator_2); JButton btnUpdate = new JButton("Update"); btnUpdate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // This hashMap contains the values which we want to update HashMap<String, Boolean> valuesToEdit = new HashMap<String, Boolean>(); // Put the values we want to edit in the HashMap with the false // as default if (passwordChanged()) { valuesToEdit.put("pass", false); } if (nameEdited()) { valuesToEdit.put("name", false); } if (fNameEdited()) { valuesToEdit.put("fname", false); } if (mailEdited()) { valuesToEdit.put("mail", false); } // Coloring the textFileds if (valuesToEdit.containsKey("pass")) { if (newPassConfirmed()) { valuesToEdit.put("pass", true); newpasswordField.setBorder(BorderFactory.createLineBorder(Color.green)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { newpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("name")) { if (!nameTextField.getText().equals(CurrentUser.getName()) && nameTextField.getText().length() > 0) { valuesToEdit.put("name", true); nameTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { nameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("fname")) { if (!fnameTextField.getText().equals(CurrentUser.getFname()) && fnameTextField.getText().length() > 0) { valuesToEdit.put("fname", true); fnameTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { fnameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (valuesToEdit.containsKey("mail")) { if (!emailTextField.getText().equals(CurrentUser.getMail()) && Pattern.matches( "^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)+$", emailTextField.getText()) && passwordField.getPassword().length >= 4) { valuesToEdit.put("mail", true); emailTextField.setBorder(BorderFactory.createLineBorder(Color.green)); } else { emailTextField.setBorder(BorderFactory.createLineBorder(Color.red)); passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } HashMap<String, Boolean> editingResults = new HashMap<String, Boolean>(); if (!valuesToEdit.containsValue(false)) { if (valuesToEdit.containsKey("name")) { editingResults.put("name", RemoteRequests.changName( CurrentUser.getId(), nameTextField.getText())); } if (valuesToEdit.containsKey("fname")) { editingResults.put("fname", RemoteRequests.changeFname( CurrentUser.getId(), fnameTextField.getText())); } if (valuesToEdit.containsKey("mail")) { editingResults.put("mail", RemoteRequests.changeMail( CurrentUser.getId(), new HashPassword( passwordField.getPassword()).getHashed(), emailTextField.getText())); } if (valuesToEdit.containsKey("pass")) { editingResults.put("pass", RemoteRequests.changePassword( CurrentUser.getId(), new HashPassword(passwordField.getPassword()).getHashed(), new HashPassword(newpasswordField.getPassword()).getHashed())); } String updateSucess = "<b>Updates : <b><br />"; String updateFailure = "<b>Failures : </b><br />"; if (editingResults.containsKey("name")) { if (editingResults.get("name")) { updateSucess += "name<br />"; CurrentUser.get().setName(nameTextField.getText()); } else { updateFailure += "name<br />"; nameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("fname")) { if (editingResults.get("fname")) { updateSucess += "forname<br />"; CurrentUser.get().setFname(fnameTextField.getText()); } else { updateFailure += "forname<br />"; fnameTextField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("mail")) { if (editingResults.get("mail")) { updateSucess += "Email Adress<br />"; CurrentUser.get().setMail(emailTextField.getText()); } else { updateFailure += "Email Adress<br />"; emailTextField.setBorder(BorderFactory.createLineBorder(Color.red)); passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (editingResults.containsKey("pass")) { if (editingResults.get("pass")) { updateSucess += "Password<br />"; } else { updateFailure += "Password<br />"; passwordField.setBorder(BorderFactory.createLineBorder(Color.red)); newpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); confirmpasswordField.setBorder(BorderFactory.createLineBorder(Color.red)); } } if (!updateSucess.equals("<b>Updates : <b><br />")) { if (updateFailure.equals("<b>Failures : </b><br />")) { SayToUser.success("Update Successed", updateSucess); } else { SayToUser.warning("Update Warning", updateSucess + updateFailure); } } else if (!updateFailure.equals("<b>Failures : </b><br />")) { SayToUser.error("Update Failure", updateFailure); } else { SayToUser.warning("", "No thing to update :)"); } if (!mailEdited() && !passwordChanged()) { passwordField.setBorder(BorderFactory.createLineBorder(Color.black)); } } } }); btnUpdate.setBounds(116, 425, 117, 29); add(btnUpdate); }
diff --git a/src/model/Movie_Info.java b/src/model/Movie_Info.java index 75627c5..1a4d87a 100644 --- a/src/model/Movie_Info.java +++ b/src/model/Movie_Info.java @@ -1,124 +1,124 @@ package model; import java.util.ArrayList; import util.RegexUtil; public class Movie_Info{ private String movie_name = null; private String haibao_path = null; private ArrayList<String> names = new ArrayList<String>(); private ArrayList<String> downloadlinks = new ArrayList<String>(); private ArrayList<String> downloadnames = new ArrayList<String>(); public Movie_Info(){} public Movie_Info(String name, String path){ this.movie_name = name; this.haibao_path = path; } private Movie_Info(Movie_Info info){ this.movie_name = info.movie_name; this.haibao_path = info.haibao_path; this.names = info.names; this.downloadlinks = info.downloadlinks; this.downloadnames = info.downloadnames; } public boolean hasName(){ return this.movie_name != null; } public boolean hasHaiBaoPath(){ return this.haibao_path != null; } public void setMovieName(String movie_name){ this.movie_name = movie_name; } public void setHaiBaoPath(String haibao_path){ this.haibao_path = haibao_path; } public void setNames(ArrayList<String> names){ this.names = names; } // public void setDownLoadLinks(ArrayList<String> downloadlinks){ // this.downloadlinks = downloadlinks; // } // public void setDownLoadNames(ArrayList<String> downloadnames){ // this.downloadnames = downloadnames; // } public void addName(String name){ this.names.add(name); } public void addDownLoadLinks(ArrayList<String> downloadlinks, String downloadname){ this.downloadlinks.addAll(downloadlinks); for(int i = 0; i < downloadlinks.size() ; i++){ this.downloadnames.add(downloadname); } } public void addDownLoadLinks(String downloadlink, String downloadname){ this.downloadlinks.add(downloadlink); this.downloadnames.add(downloadname); } public String getMovieName(){ return this.movie_name; } public String getHaiBaoPath(){ return this.haibao_path; } public ArrayList<String> getNames(){ return this.names; } public ArrayList<String> getDownLoadLinks(){ return this.downloadlinks; } public ArrayList<String> getDownLoadNames(){ return this.downloadnames; } @Override public String toString(){ StringBuffer sb = new StringBuffer("movie name: " + movie_name + "\nhaibao path: " + haibao_path + "\n"); if(names.size() != 0){ sb.append("movie has names: "); for(int i = 0; i < names.size(); i ++){ sb.append(names.get(i) + " "); } } sb.append("\n"); if(downloadlinks.size() != 0){ sb.append("movie has down loads : "); for(int i = 0; i < downloadlinks.size(); i ++){ sb.append("\n " + downloadnames.get(i) + " " + downloadlinks.get(i)); } } return sb.toString(); } @Override public Movie_Info clone(){ return new Movie_Info(this); } public Movie_Info convertForMySQL(){ try { if(movie_name != null){ movie_name = movie_name.replaceAll("'","''"); movie_name = RegexUtil.formatMovieName(movie_name); } if(haibao_path != null){ haibao_path = haibao_path.replaceAll("'","''"); } for(int i = 0 ; i < names.size(); i ++){ - names.set(i, names.get(i).replaceAll("'","''")); + names.set(i, RegexUtil.formatMovieName(names.get(i).replaceAll("'","''"))); } for(int i = 0 ; i < downloadlinks.size(); i ++){ downloadlinks.set(i, downloadlinks.get(i).replaceAll("'","''")); } for(int i = 0 ; i < downloadnames.size(); i ++){ - downloadnames.set(i, RegexUtil.formatMovieName(downloadnames.get(i).replaceAll("'","''"))); + downloadnames.set(i, downloadnames.get(i).replaceAll("'","''")); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; } }
false
true
public Movie_Info convertForMySQL(){ try { if(movie_name != null){ movie_name = movie_name.replaceAll("'","''"); movie_name = RegexUtil.formatMovieName(movie_name); } if(haibao_path != null){ haibao_path = haibao_path.replaceAll("'","''"); } for(int i = 0 ; i < names.size(); i ++){ names.set(i, names.get(i).replaceAll("'","''")); } for(int i = 0 ; i < downloadlinks.size(); i ++){ downloadlinks.set(i, downloadlinks.get(i).replaceAll("'","''")); } for(int i = 0 ; i < downloadnames.size(); i ++){ downloadnames.set(i, RegexUtil.formatMovieName(downloadnames.get(i).replaceAll("'","''"))); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; }
public Movie_Info convertForMySQL(){ try { if(movie_name != null){ movie_name = movie_name.replaceAll("'","''"); movie_name = RegexUtil.formatMovieName(movie_name); } if(haibao_path != null){ haibao_path = haibao_path.replaceAll("'","''"); } for(int i = 0 ; i < names.size(); i ++){ names.set(i, RegexUtil.formatMovieName(names.get(i).replaceAll("'","''"))); } for(int i = 0 ; i < downloadlinks.size(); i ++){ downloadlinks.set(i, downloadlinks.get(i).replaceAll("'","''")); } for(int i = 0 ; i < downloadnames.size(); i ++){ downloadnames.set(i, downloadnames.get(i).replaceAll("'","''")); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; }
diff --git a/editor/src/construct/Underline.java b/editor/src/construct/Underline.java index 4e1dc5b..b0ae322 100644 --- a/editor/src/construct/Underline.java +++ b/editor/src/construct/Underline.java @@ -1,8 +1,8 @@ package construct; public class Underline implements Construct { public String toHTML(){ - return "<u></u>\n>"; + return "<u></u>\n"; } }
true
true
public String toHTML(){ return "<u></u>\n>"; }
public String toHTML(){ return "<u></u>\n"; }
diff --git a/src/main/java/net/md_5/bungee/command/CommandIP.java b/src/main/java/net/md_5/bungee/command/CommandIP.java index 8d5f6154..d1b75f4b 100644 --- a/src/main/java/net/md_5/bungee/command/CommandIP.java +++ b/src/main/java/net/md_5/bungee/command/CommandIP.java @@ -1,33 +1,33 @@ package net.md_5.bungee.command; import net.md_5.bungee.BungeeCord; import net.md_5.bungee.ChatColor; import net.md_5.bungee.Permission; import net.md_5.bungee.UserConnection; public class CommandIP extends Command { @Override public void execute(CommandSender sender, String[] args) { - if (getPermission(sender) != Permission.ADMIN) + if (getPermission(sender) != Permission.MODERATOR && getPermission(sender) != Permission.ADMIN) { sender.sendMessage(ChatColor.RED + "You do not have permission to use this command"); return; } if (args.length < 1) { sender.sendMessage(ChatColor.RED + "Please follow this command by a user name"); return; } UserConnection user = BungeeCord.instance.connections.get(args[0]); if (user == null) { sender.sendMessage(ChatColor.RED + "That user is not online"); } else { sender.sendMessage(ChatColor.BLUE + "IP of " + args[0] + " is " + user.getAddress()); } } }
true
true
public void execute(CommandSender sender, String[] args) { if (getPermission(sender) != Permission.ADMIN) { sender.sendMessage(ChatColor.RED + "You do not have permission to use this command"); return; } if (args.length < 1) { sender.sendMessage(ChatColor.RED + "Please follow this command by a user name"); return; } UserConnection user = BungeeCord.instance.connections.get(args[0]); if (user == null) { sender.sendMessage(ChatColor.RED + "That user is not online"); } else { sender.sendMessage(ChatColor.BLUE + "IP of " + args[0] + " is " + user.getAddress()); } }
public void execute(CommandSender sender, String[] args) { if (getPermission(sender) != Permission.MODERATOR && getPermission(sender) != Permission.ADMIN) { sender.sendMessage(ChatColor.RED + "You do not have permission to use this command"); return; } if (args.length < 1) { sender.sendMessage(ChatColor.RED + "Please follow this command by a user name"); return; } UserConnection user = BungeeCord.instance.connections.get(args[0]); if (user == null) { sender.sendMessage(ChatColor.RED + "That user is not online"); } else { sender.sendMessage(ChatColor.BLUE + "IP of " + args[0] + " is " + user.getAddress()); } }
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java index a29d5708f..289df7299 100644 --- a/src/com/android/settings/Settings.java +++ b/src/com/android/settings/Settings.java @@ -1,868 +1,868 @@ /* * 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.settings; import com.android.internal.util.ArrayUtils; import com.android.settings.ChooseLockGeneric.ChooseLockGenericFragment; import com.android.settings.accounts.AccountSyncSettings; import com.android.settings.accounts.AuthenticatorHelper; import com.android.settings.accounts.ManageAccountsSettings; import com.android.settings.applications.InstalledAppDetails; import com.android.settings.applications.ManageApplications; import com.android.settings.bluetooth.BluetoothEnabler; import com.android.settings.deviceinfo.Memory; import com.android.settings.fuelgauge.PowerUsageSummary; import com.android.settings.profiles.ProfileEnabler; import com.android.settings.vpn2.VpnSettings; import com.android.settings.wifi.WifiEnabler; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.OnAccountsUpdateListener; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.INetworkManagementService; import android.os.RemoteException; import android.os.ServiceManager; import android.os.UserHandle; import android.os.UserManager; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.Switch; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; /** * Top-level settings activity to handle single pane and double pane UI layout. */ public class Settings extends PreferenceActivity implements ButtonBarHandler, OnAccountsUpdateListener { private static final String LOG_TAG = "Settings"; private static final String META_DATA_KEY_HEADER_ID = "com.android.settings.TOP_LEVEL_HEADER_ID"; private static final String META_DATA_KEY_FRAGMENT_CLASS = "com.android.settings.FRAGMENT_CLASS"; private static final String META_DATA_KEY_PARENT_TITLE = "com.android.settings.PARENT_FRAGMENT_TITLE"; private static final String META_DATA_KEY_PARENT_FRAGMENT_CLASS = "com.android.settings.PARENT_FRAGMENT_CLASS"; private static final String EXTRA_CLEAR_UI_OPTIONS = "settings:remove_ui_options"; private static final String SAVE_KEY_CURRENT_HEADER = "com.android.settings.CURRENT_HEADER"; private static final String SAVE_KEY_PARENT_HEADER = "com.android.settings.PARENT_HEADER"; private String mFragmentClass; private int mTopLevelHeaderId; private Header mFirstHeader; private Header mCurrentHeader; private Header mParentHeader; private boolean mInLocalHeaderSwitch; // Show only these settings for restricted users private int[] SETTINGS_FOR_RESTRICTED = { R.id.wireless_section, R.id.wifi_settings, R.id.bluetooth_settings, R.id.data_usage_settings, R.id.wireless_settings, R.id.device_section, R.id.sound_settings, R.id.display_settings, R.id.storage_settings, R.id.application_settings, R.id.battery_settings, R.id.personal_section, R.id.location_settings, R.id.security_settings, R.id.language_settings, R.id.user_settings, R.id.account_settings, R.id.account_add, R.id.system_section, R.id.date_time_settings, R.id.about_settings, R.id.accessibility_settings }; private SharedPreferences mDevelopmentPreferences; private SharedPreferences.OnSharedPreferenceChangeListener mDevelopmentPreferencesListener; // TODO: Update Call Settings based on airplane mode state. protected HashMap<Integer, Integer> mHeaderIndexMap = new HashMap<Integer, Integer>(); private AuthenticatorHelper mAuthenticatorHelper; private Header mLastHeader; private boolean mListeningToAccountUpdates; @Override protected void onCreate(Bundle savedInstanceState) { if (getIntent().getBooleanExtra(EXTRA_CLEAR_UI_OPTIONS, false)) { getWindow().setUiOptions(0); } mAuthenticatorHelper = new AuthenticatorHelper(); mAuthenticatorHelper.updateAuthDescriptions(this); mAuthenticatorHelper.onAccountsUpdated(this, null); mDevelopmentPreferences = getSharedPreferences(DevelopmentSettings.PREF_FILE, Context.MODE_PRIVATE); getMetaData(); mInLocalHeaderSwitch = true; super.onCreate(savedInstanceState); mInLocalHeaderSwitch = false; if (!onIsHidingHeaders() && onIsMultiPane()) { highlightHeader(mTopLevelHeaderId); // Force the title so that it doesn't get overridden by a direct launch of // a specific settings screen. setTitle(R.string.settings_label); } // Retrieve any saved state if (savedInstanceState != null) { mCurrentHeader = savedInstanceState.getParcelable(SAVE_KEY_CURRENT_HEADER); mParentHeader = savedInstanceState.getParcelable(SAVE_KEY_PARENT_HEADER); } // If the current header was saved, switch to it if (savedInstanceState != null && mCurrentHeader != null) { //switchToHeaderLocal(mCurrentHeader); showBreadCrumbs(mCurrentHeader.title, null); } if (mParentHeader != null) { setParentTitle(mParentHeader.title, null, new OnClickListener() { public void onClick(View v) { switchToParent(mParentHeader.fragment); } }); } // Override up navigation for multi-pane, since we handle it in the fragment breadcrumbs if (onIsMultiPane()) { getActionBar().setDisplayHomeAsUpEnabled(false); getActionBar().setHomeButtonEnabled(false); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Save the current fragment, if it is the same as originally launched if (mCurrentHeader != null) { outState.putParcelable(SAVE_KEY_CURRENT_HEADER, mCurrentHeader); } if (mParentHeader != null) { outState.putParcelable(SAVE_KEY_PARENT_HEADER, mParentHeader); } } @Override public void onResume() { super.onResume(); mDevelopmentPreferencesListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { invalidateHeaders(); } }; mDevelopmentPreferences.registerOnSharedPreferenceChangeListener( mDevelopmentPreferencesListener); ListAdapter listAdapter = getListAdapter(); if (listAdapter instanceof HeaderAdapter) { ((HeaderAdapter) listAdapter).resume(); } invalidateHeaders(); } @Override public void onPause() { super.onPause(); ListAdapter listAdapter = getListAdapter(); if (listAdapter instanceof HeaderAdapter) { ((HeaderAdapter) listAdapter).pause(); } mDevelopmentPreferences.unregisterOnSharedPreferenceChangeListener( mDevelopmentPreferencesListener); mDevelopmentPreferencesListener = null; } @Override public void onDestroy() { super.onDestroy(); if (mListeningToAccountUpdates) { AccountManager.get(this).removeOnAccountsUpdatedListener(this); } } private void switchToHeaderLocal(Header header) { mInLocalHeaderSwitch = true; switchToHeader(header); mInLocalHeaderSwitch = false; } @Override public void switchToHeader(Header header) { if (!mInLocalHeaderSwitch) { mCurrentHeader = null; mParentHeader = null; } super.switchToHeader(header); } /** * Switch to parent fragment and store the grand parent's info * @param className name of the activity wrapper for the parent fragment. */ private void switchToParent(String className) { final ComponentName cn = new ComponentName(this, className); try { final PackageManager pm = getPackageManager(); final ActivityInfo parentInfo = pm.getActivityInfo(cn, PackageManager.GET_META_DATA); if (parentInfo != null && parentInfo.metaData != null) { String fragmentClass = parentInfo.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS); CharSequence fragmentTitle = parentInfo.loadLabel(pm); Header parentHeader = new Header(); parentHeader.fragment = fragmentClass; parentHeader.title = fragmentTitle; mCurrentHeader = parentHeader; switchToHeaderLocal(parentHeader); highlightHeader(mTopLevelHeaderId); mParentHeader = new Header(); mParentHeader.fragment = parentInfo.metaData.getString(META_DATA_KEY_PARENT_FRAGMENT_CLASS); mParentHeader.title = parentInfo.metaData.getString(META_DATA_KEY_PARENT_TITLE); } } catch (NameNotFoundException nnfe) { Log.w(LOG_TAG, "Could not find parent activity : " + className); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); // If it is not launched from history, then reset to top-level if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) { if (mFirstHeader != null && !onIsHidingHeaders() && onIsMultiPane()) { switchToHeaderLocal(mFirstHeader); } getListView().setSelectionFromTop(0, 0); } } private void highlightHeader(int id) { if (id != 0) { Integer index = mHeaderIndexMap.get(id); if (index != null) { getListView().setItemChecked(index, true); if (isMultiPane()) { getListView().smoothScrollToPosition(index); } } } } @Override public Intent getIntent() { Intent superIntent = super.getIntent(); String startingFragment = getStartingFragmentClass(superIntent); // This is called from super.onCreate, isMultiPane() is not yet reliable // Do not use onIsHidingHeaders either, which relies itself on this method if (startingFragment != null && !onIsMultiPane()) { Intent modIntent = new Intent(superIntent); modIntent.putExtra(EXTRA_SHOW_FRAGMENT, startingFragment); Bundle args = superIntent.getExtras(); if (args != null) { args = new Bundle(args); } else { args = new Bundle(); } args.putParcelable("intent", superIntent); modIntent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, superIntent.getExtras()); return modIntent; } return superIntent; } /** * Checks if the component name in the intent is different from the Settings class and * returns the class name to load as a fragment. */ protected String getStartingFragmentClass(Intent intent) { if (mFragmentClass != null) return mFragmentClass; String intentClass = intent.getComponent().getClassName(); if (intentClass.equals(getClass().getName())) return null; if ("com.android.settings.ManageApplications".equals(intentClass) || "com.android.settings.RunningServices".equals(intentClass) || "com.android.settings.applications.StorageUse".equals(intentClass)) { // Old names of manage apps. intentClass = com.android.settings.applications.ManageApplications.class.getName(); } return intentClass; } /** * Override initial header when an activity-alias is causing Settings to be launched * for a specific fragment encoded in the android:name parameter. */ @Override public Header onGetInitialHeader() { String fragmentClass = getStartingFragmentClass(super.getIntent()); if (fragmentClass != null) { Header header = new Header(); header.fragment = fragmentClass; header.title = getTitle(); header.fragmentArguments = getIntent().getExtras(); mCurrentHeader = header; return header; } return mFirstHeader; } @Override public Intent onBuildStartFragmentIntent(String fragmentName, Bundle args, int titleRes, int shortTitleRes) { Intent intent = super.onBuildStartFragmentIntent(fragmentName, args, titleRes, shortTitleRes); // some fragments want to avoid split actionbar if (DataUsageSummary.class.getName().equals(fragmentName) || PowerUsageSummary.class.getName().equals(fragmentName) || AccountSyncSettings.class.getName().equals(fragmentName) || UserDictionarySettings.class.getName().equals(fragmentName) || Memory.class.getName().equals(fragmentName) || ManageApplications.class.getName().equals(fragmentName) || WirelessSettings.class.getName().equals(fragmentName) || SoundSettings.class.getName().equals(fragmentName) || PrivacySettings.class.getName().equals(fragmentName) || ManageAccountsSettings.class.getName().equals(fragmentName) || VpnSettings.class.getName().equals(fragmentName) || SecuritySettings.class.getName().equals(fragmentName) || InstalledAppDetails.class.getName().equals(fragmentName) || ChooseLockGenericFragment.class.getName().equals(fragmentName)) { intent.putExtra(EXTRA_CLEAR_UI_OPTIONS, true); } intent.setClass(this, SubSettings.class); return intent; } /** * Populate the activity with the top-level headers. */ @Override public void onBuildHeaders(List<Header> headers) { loadHeadersFromResource(R.xml.settings_headers, headers); updateHeaderList(headers); } private void updateHeaderList(List<Header> target) { final boolean showDev = mDevelopmentPreferences.getBoolean( DevelopmentSettings.PREF_SHOW, android.os.Build.TYPE.equals("eng")); int i = 0; mHeaderIndexMap.clear(); while (i < target.size()) { Header header = target.get(i); // Ids are integers, so downcasting int id = (int) header.id; if (id == R.id.operator_settings || id == R.id.manufacturer_settings || id == R.id.advanced_settings) { Utils.updateHeaderToSpecificActivityFromMetaDataOrRemove(this, target, header); } else if (id == R.id.launcher_settings) { Intent launcherIntent = new Intent(Intent.ACTION_MAIN); launcherIntent.addCategory(Intent.CATEGORY_HOME); launcherIntent.addCategory(Intent.CATEGORY_DEFAULT); Intent launcherPreferencesIntent = new Intent(Intent.ACTION_MAIN); launcherPreferencesIntent.addCategory("com.cyanogenmod.category.LAUNCHER_PREFERENCES"); ActivityInfo defaultLauncher = getPackageManager().resolveActivity(launcherIntent, PackageManager.MATCH_DEFAULT_ONLY).activityInfo; launcherPreferencesIntent.setPackage(defaultLauncher.packageName); ResolveInfo launcherPreferences = getPackageManager().resolveActivity(launcherPreferencesIntent, 0); if (launcherPreferences != null) { header.intent = new Intent().setClassName(launcherPreferences.activityInfo.packageName, launcherPreferences.activityInfo.name); } else { target.remove(header); } } else if (id == R.id.wifi_settings) { // Remove WiFi Settings if WiFi service is not available. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) { target.remove(i); } } else if (id == R.id.bluetooth_settings) { // Remove Bluetooth Settings if Bluetooth service is not available. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) { target.remove(i); } } else if (id == R.id.data_usage_settings) { // Remove data usage when kernel module not enabled final INetworkManagementService netManager = INetworkManagementService.Stub .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE)); try { if (!netManager.isBandwidthControlEnabled()) { target.remove(i); } } catch (RemoteException e) { // ignored } } else if (id == R.id.account_settings) { int headerIndex = i + 1; i = insertAccountsHeaders(target, headerIndex); } else if (id == R.id.user_settings) { if (!UserHandle.MU_ENABLED || !UserManager.supportsMultipleUsers() || Utils.isMonkeyRunning()) { target.remove(i); } } else if (id == R.id.development_settings || id == R.id.performance_settings) { if (!showDev) { target.remove(i); } } if (target.get(i) == header && UserHandle.MU_ENABLED && UserHandle.myUserId() != 0 && !ArrayUtils.contains(SETTINGS_FOR_RESTRICTED, id)) { target.remove(i); } // Increment if the current one wasn't removed by the Utils code. if (target.get(i) == header) { // Hold on to the first header, when we need to reset to the top-level if (mFirstHeader == null && HeaderAdapter.getHeaderType(header) != HeaderAdapter.HEADER_TYPE_CATEGORY) { mFirstHeader = header; } mHeaderIndexMap.put(id, i); i++; } } } private int insertAccountsHeaders(List<Header> target, int headerIndex) { String[] accountTypes = mAuthenticatorHelper.getEnabledAccountTypes(); List<Header> accountHeaders = new ArrayList<Header>(accountTypes.length); for (String accountType : accountTypes) { CharSequence label = mAuthenticatorHelper.getLabelForType(this, accountType); if (label == null) { continue; } Account[] accounts = AccountManager.get(this).getAccountsByType(accountType); boolean skipToAccount = accounts.length == 1 && !mAuthenticatorHelper.hasAccountPreferences(accountType); Header accHeader = new Header(); accHeader.title = label; if (accHeader.extras == null) { accHeader.extras = new Bundle(); } if (skipToAccount) { accHeader.breadCrumbTitleRes = R.string.account_sync_settings_title; accHeader.breadCrumbShortTitleRes = R.string.account_sync_settings_title; accHeader.fragment = AccountSyncSettings.class.getName(); accHeader.fragmentArguments = new Bundle(); // Need this for the icon accHeader.extras.putString(ManageAccountsSettings.KEY_ACCOUNT_TYPE, accountType); accHeader.extras.putParcelable(AccountSyncSettings.ACCOUNT_KEY, accounts[0]); accHeader.fragmentArguments.putParcelable(AccountSyncSettings.ACCOUNT_KEY, accounts[0]); } else { accHeader.breadCrumbTitle = label; accHeader.breadCrumbShortTitle = label; accHeader.fragment = ManageAccountsSettings.class.getName(); accHeader.fragmentArguments = new Bundle(); accHeader.extras.putString(ManageAccountsSettings.KEY_ACCOUNT_TYPE, accountType); accHeader.fragmentArguments.putString(ManageAccountsSettings.KEY_ACCOUNT_TYPE, accountType); if (!isMultiPane()) { accHeader.fragmentArguments.putString(ManageAccountsSettings.KEY_ACCOUNT_LABEL, label.toString()); } } accountHeaders.add(accHeader); } // Sort by label Collections.sort(accountHeaders, new Comparator<Header>() { @Override public int compare(Header h1, Header h2) { return h1.title.toString().compareTo(h2.title.toString()); } }); for (Header header : accountHeaders) { target.add(headerIndex++, header); } if (!mListeningToAccountUpdates) { AccountManager.get(this).addOnAccountsUpdatedListener(this, null, true); mListeningToAccountUpdates = true; } return headerIndex; } private void getMetaData() { try { ActivityInfo ai = getPackageManager().getActivityInfo(getComponentName(), PackageManager.GET_META_DATA); if (ai == null || ai.metaData == null) return; mTopLevelHeaderId = ai.metaData.getInt(META_DATA_KEY_HEADER_ID); mFragmentClass = ai.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS); // Check if it has a parent specified and create a Header object final int parentHeaderTitleRes = ai.metaData.getInt(META_DATA_KEY_PARENT_TITLE); String parentFragmentClass = ai.metaData.getString(META_DATA_KEY_PARENT_FRAGMENT_CLASS); if (parentFragmentClass != null) { mParentHeader = new Header(); mParentHeader.fragment = parentFragmentClass; if (parentHeaderTitleRes != 0) { mParentHeader.title = getResources().getString(parentHeaderTitleRes); } } } catch (NameNotFoundException nnfe) { // No recovery } } @Override public boolean hasNextButton() { return super.hasNextButton(); } @Override public Button getNextButton() { return super.getNextButton(); } private static class HeaderAdapter extends ArrayAdapter<Header> { static final int HEADER_TYPE_CATEGORY = 0; static final int HEADER_TYPE_NORMAL = 1; static final int HEADER_TYPE_SWITCH = 2; private static final int HEADER_TYPE_COUNT = HEADER_TYPE_SWITCH + 1; private final WifiEnabler mWifiEnabler; private final BluetoothEnabler mBluetoothEnabler; private final ProfileEnabler mProfileEnabler; private AuthenticatorHelper mAuthHelper; private static class HeaderViewHolder { ImageView icon; TextView title; TextView summary; Switch switch_; } private LayoutInflater mInflater; static int getHeaderType(Header header) { if (header.fragment == null && header.intent == null) { return HEADER_TYPE_CATEGORY; } else if (header.id == R.id.wifi_settings || header.id == R.id.bluetooth_settings || header.id == R.id.profiles_settings) { return HEADER_TYPE_SWITCH; } else { return HEADER_TYPE_NORMAL; } } @Override public int getItemViewType(int position) { Header header = getItem(position); return getHeaderType(header); } @Override public boolean areAllItemsEnabled() { return false; // because of categories } @Override public boolean isEnabled(int position) { return getItemViewType(position) != HEADER_TYPE_CATEGORY; } @Override public int getViewTypeCount() { return HEADER_TYPE_COUNT; } @Override public boolean hasStableIds() { return true; } public HeaderAdapter(Context context, List<Header> objects, AuthenticatorHelper authenticatorHelper) { super(context, 0, objects); mAuthHelper = authenticatorHelper; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Temp Switches provided as placeholder until the adapter replaces these with actual // Switches inflated from their layouts. Must be done before adapter is set in super mWifiEnabler = new WifiEnabler(context, new Switch(context)); mBluetoothEnabler = new BluetoothEnabler(context, new Switch(context)); mProfileEnabler = new ProfileEnabler(context, null, new Switch(context)); } @Override public View getView(int position, View convertView, ViewGroup parent) { HeaderViewHolder holder; Header header = getItem(position); int headerType = getHeaderType(header); View view = null; - if (convertView == null) { + if (convertView == null || headerType == HEADER_TYPE_SWITCH) { holder = new HeaderViewHolder(); switch (headerType) { case HEADER_TYPE_CATEGORY: view = new TextView(getContext(), null, android.R.attr.listSeparatorTextViewStyle); holder.title = (TextView) view; break; case HEADER_TYPE_SWITCH: view = mInflater.inflate(R.layout.preference_header_switch_item, parent, false); holder.icon = (ImageView) view.findViewById(R.id.icon); holder.title = (TextView) view.findViewById(com.android.internal.R.id.title); holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary); holder.switch_ = (Switch) view.findViewById(R.id.switchWidget); break; case HEADER_TYPE_NORMAL: view = mInflater.inflate( R.layout.preference_header_item, parent, false); holder.icon = (ImageView) view.findViewById(R.id.icon); holder.title = (TextView) view.findViewById(com.android.internal.R.id.title); holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary); break; } view.setTag(holder); } else { view = convertView; holder = (HeaderViewHolder) view.getTag(); } // All view fields must be updated every time, because the view may be recycled switch (headerType) { case HEADER_TYPE_CATEGORY: holder.title.setText(header.getTitle(getContext().getResources())); break; case HEADER_TYPE_SWITCH: // Would need a different treatment if the main menu had more switches if (header.id == R.id.wifi_settings) { mWifiEnabler.setSwitch(holder.switch_); } else if (header.id == R.id.bluetooth_settings) { mBluetoothEnabler.setSwitch(holder.switch_); } else if (header.id == R.id.profiles_settings) { mProfileEnabler.setSwitch(holder.switch_); } // No break, fall through on purpose to update common fields //$FALL-THROUGH$ case HEADER_TYPE_NORMAL: if (header.extras != null && header.extras.containsKey(ManageAccountsSettings.KEY_ACCOUNT_TYPE)) { String accType = header.extras.getString( ManageAccountsSettings.KEY_ACCOUNT_TYPE); ViewGroup.LayoutParams lp = holder.icon.getLayoutParams(); lp.width = getContext().getResources().getDimensionPixelSize( R.dimen.header_icon_width); lp.height = lp.width; holder.icon.setLayoutParams(lp); Drawable icon = mAuthHelper.getDrawableForType(getContext(), accType); holder.icon.setImageDrawable(icon); } else { holder.icon.setImageResource(header.iconRes); } holder.title.setText(header.getTitle(getContext().getResources())); CharSequence summary = header.getSummary(getContext().getResources()); if (!TextUtils.isEmpty(summary)) { holder.summary.setVisibility(View.VISIBLE); holder.summary.setText(summary); } else { holder.summary.setVisibility(View.GONE); } break; } return view; } public void resume() { mWifiEnabler.resume(); mBluetoothEnabler.resume(); mProfileEnabler.resume(); } public void pause() { mWifiEnabler.pause(); mBluetoothEnabler.pause(); mProfileEnabler.pause(); } } @Override public void onHeaderClick(Header header, int position) { boolean revert = false; if (header.id == R.id.account_add) { revert = true; } super.onHeaderClick(header, position); if (revert && mLastHeader != null) { highlightHeader((int) mLastHeader.id); } else { mLastHeader = header; } } @Override public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) { // Override the fragment title for Wallpaper settings int titleRes = pref.getTitleRes(); if (pref.getFragment().equals(WallpaperTypeSettings.class.getName())) { titleRes = R.string.wallpaper_settings_fragment_title; } else if (pref.getFragment().equals(OwnerInfoSettings.class.getName()) && UserHandle.myUserId() != UserHandle.USER_OWNER) { titleRes = R.string.user_info_settings_title; } startPreferencePanel(pref.getFragment(), pref.getExtras(), titleRes, pref.getTitle(), null, 0); return true; } public boolean shouldUpRecreateTask(Intent targetIntent) { return super.shouldUpRecreateTask(new Intent(this, Settings.class)); } @Override public void setListAdapter(ListAdapter adapter) { if (adapter == null) { super.setListAdapter(null); } else { super.setListAdapter(new HeaderAdapter(this, getHeaders(), mAuthenticatorHelper)); } } @Override public void onAccountsUpdated(Account[] accounts) { // TODO: watch for package upgrades to invalidate cache; see 7206643 mAuthenticatorHelper.updateAuthDescriptions(this); mAuthenticatorHelper.onAccountsUpdated(this, accounts); invalidateHeaders(); } /* * Settings subclasses for launching independently. */ public static class BluetoothSettingsActivity extends Settings { /* empty */ } public static class WirelessSettingsActivity extends Settings { /* empty */ } public static class TetherSettingsActivity extends Settings { /* empty */ } public static class VpnSettingsActivity extends Settings { /* empty */ } public static class DateTimeSettingsActivity extends Settings { /* empty */ } public static class StorageSettingsActivity extends Settings { /* empty */ } public static class WifiSettingsActivity extends Settings { /* empty */ } public static class WifiP2pSettingsActivity extends Settings { /* empty */ } public static class InputMethodAndLanguageSettingsActivity extends Settings { /* empty */ } public static class KeyboardLayoutPickerActivity extends Settings { /* empty */ } public static class InputMethodAndSubtypeEnablerActivity extends Settings { /* empty */ } public static class SpellCheckersSettingsActivity extends Settings { /* empty */ } public static class LocalePickerActivity extends Settings { /* empty */ } public static class UserDictionarySettingsActivity extends Settings { /* empty */ } public static class SoundSettingsActivity extends Settings { /* empty */ } public static class DisplaySettingsActivity extends Settings { /* empty */ } public static class DeviceInfoSettingsActivity extends Settings { /* empty */ } public static class ApplicationSettingsActivity extends Settings { /* empty */ } public static class ManageApplicationsActivity extends Settings { /* empty */ } public static class StorageUseActivity extends Settings { /* empty */ } public static class DevelopmentSettingsActivity extends Settings { /* empty */ } public static class AccessibilitySettingsActivity extends Settings { /* empty */ } public static class SecuritySettingsActivity extends Settings { /* empty */ } public static class LocationSettingsActivity extends Settings { /* empty */ } public static class PrivacySettingsActivity extends Settings { /* empty */ } public static class RunningServicesActivity extends Settings { /* empty */ } public static class ManageAccountsSettingsActivity extends Settings { /* empty */ } public static class PowerUsageSummaryActivity extends Settings { /* empty */ } public static class AccountSyncSettingsActivity extends Settings { /* empty */ } public static class AccountSyncSettingsInAddAccountActivity extends Settings { /* empty */ } public static class CryptKeeperSettingsActivity extends Settings { /* empty */ } public static class DeviceAdminSettingsActivity extends Settings { /* empty */ } public static class DataUsageSummaryActivity extends Settings { /* empty */ } public static class AdvancedWifiSettingsActivity extends Settings { /* empty */ } public static class TextToSpeechSettingsActivity extends Settings { /* empty */ } public static class AndroidBeamSettingsActivity extends Settings { /* empty */ } public static class WifiDisplaySettingsActivity extends Settings { /* empty */ } public static class ApnSettingsActivity extends Settings { /* empty */ } public static class ApnEditorActivity extends Settings { /* empty */ } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { HeaderViewHolder holder; Header header = getItem(position); int headerType = getHeaderType(header); View view = null; if (convertView == null) { holder = new HeaderViewHolder(); switch (headerType) { case HEADER_TYPE_CATEGORY: view = new TextView(getContext(), null, android.R.attr.listSeparatorTextViewStyle); holder.title = (TextView) view; break; case HEADER_TYPE_SWITCH: view = mInflater.inflate(R.layout.preference_header_switch_item, parent, false); holder.icon = (ImageView) view.findViewById(R.id.icon); holder.title = (TextView) view.findViewById(com.android.internal.R.id.title); holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary); holder.switch_ = (Switch) view.findViewById(R.id.switchWidget); break; case HEADER_TYPE_NORMAL: view = mInflater.inflate( R.layout.preference_header_item, parent, false); holder.icon = (ImageView) view.findViewById(R.id.icon); holder.title = (TextView) view.findViewById(com.android.internal.R.id.title); holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary); break; } view.setTag(holder); } else { view = convertView; holder = (HeaderViewHolder) view.getTag(); } // All view fields must be updated every time, because the view may be recycled switch (headerType) { case HEADER_TYPE_CATEGORY: holder.title.setText(header.getTitle(getContext().getResources())); break; case HEADER_TYPE_SWITCH: // Would need a different treatment if the main menu had more switches if (header.id == R.id.wifi_settings) { mWifiEnabler.setSwitch(holder.switch_); } else if (header.id == R.id.bluetooth_settings) { mBluetoothEnabler.setSwitch(holder.switch_); } else if (header.id == R.id.profiles_settings) { mProfileEnabler.setSwitch(holder.switch_); } // No break, fall through on purpose to update common fields //$FALL-THROUGH$ case HEADER_TYPE_NORMAL: if (header.extras != null && header.extras.containsKey(ManageAccountsSettings.KEY_ACCOUNT_TYPE)) { String accType = header.extras.getString( ManageAccountsSettings.KEY_ACCOUNT_TYPE); ViewGroup.LayoutParams lp = holder.icon.getLayoutParams(); lp.width = getContext().getResources().getDimensionPixelSize( R.dimen.header_icon_width); lp.height = lp.width; holder.icon.setLayoutParams(lp); Drawable icon = mAuthHelper.getDrawableForType(getContext(), accType); holder.icon.setImageDrawable(icon); } else { holder.icon.setImageResource(header.iconRes); } holder.title.setText(header.getTitle(getContext().getResources())); CharSequence summary = header.getSummary(getContext().getResources()); if (!TextUtils.isEmpty(summary)) { holder.summary.setVisibility(View.VISIBLE); holder.summary.setText(summary); } else { holder.summary.setVisibility(View.GONE); } break; } return view; }
public View getView(int position, View convertView, ViewGroup parent) { HeaderViewHolder holder; Header header = getItem(position); int headerType = getHeaderType(header); View view = null; if (convertView == null || headerType == HEADER_TYPE_SWITCH) { holder = new HeaderViewHolder(); switch (headerType) { case HEADER_TYPE_CATEGORY: view = new TextView(getContext(), null, android.R.attr.listSeparatorTextViewStyle); holder.title = (TextView) view; break; case HEADER_TYPE_SWITCH: view = mInflater.inflate(R.layout.preference_header_switch_item, parent, false); holder.icon = (ImageView) view.findViewById(R.id.icon); holder.title = (TextView) view.findViewById(com.android.internal.R.id.title); holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary); holder.switch_ = (Switch) view.findViewById(R.id.switchWidget); break; case HEADER_TYPE_NORMAL: view = mInflater.inflate( R.layout.preference_header_item, parent, false); holder.icon = (ImageView) view.findViewById(R.id.icon); holder.title = (TextView) view.findViewById(com.android.internal.R.id.title); holder.summary = (TextView) view.findViewById(com.android.internal.R.id.summary); break; } view.setTag(holder); } else { view = convertView; holder = (HeaderViewHolder) view.getTag(); } // All view fields must be updated every time, because the view may be recycled switch (headerType) { case HEADER_TYPE_CATEGORY: holder.title.setText(header.getTitle(getContext().getResources())); break; case HEADER_TYPE_SWITCH: // Would need a different treatment if the main menu had more switches if (header.id == R.id.wifi_settings) { mWifiEnabler.setSwitch(holder.switch_); } else if (header.id == R.id.bluetooth_settings) { mBluetoothEnabler.setSwitch(holder.switch_); } else if (header.id == R.id.profiles_settings) { mProfileEnabler.setSwitch(holder.switch_); } // No break, fall through on purpose to update common fields //$FALL-THROUGH$ case HEADER_TYPE_NORMAL: if (header.extras != null && header.extras.containsKey(ManageAccountsSettings.KEY_ACCOUNT_TYPE)) { String accType = header.extras.getString( ManageAccountsSettings.KEY_ACCOUNT_TYPE); ViewGroup.LayoutParams lp = holder.icon.getLayoutParams(); lp.width = getContext().getResources().getDimensionPixelSize( R.dimen.header_icon_width); lp.height = lp.width; holder.icon.setLayoutParams(lp); Drawable icon = mAuthHelper.getDrawableForType(getContext(), accType); holder.icon.setImageDrawable(icon); } else { holder.icon.setImageResource(header.iconRes); } holder.title.setText(header.getTitle(getContext().getResources())); CharSequence summary = header.getSummary(getContext().getResources()); if (!TextUtils.isEmpty(summary)) { holder.summary.setVisibility(View.VISIBLE); holder.summary.setText(summary); } else { holder.summary.setVisibility(View.GONE); } break; } return view; }
diff --git a/src/org/hackystat/dailyprojectdata/resource/issue/IssueResource.java b/src/org/hackystat/dailyprojectdata/resource/issue/IssueResource.java index 82a83d7..50412b8 100644 --- a/src/org/hackystat/dailyprojectdata/resource/issue/IssueResource.java +++ b/src/org/hackystat/dailyprojectdata/resource/issue/IssueResource.java @@ -1,143 +1,143 @@ package org.hackystat.dailyprojectdata.resource.issue; import java.io.StringWriter; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.hackystat.dailyprojectdata.resource.dailyprojectdata.DailyProjectDataResource; import org.hackystat.dailyprojectdata.resource.issue.jaxb.IssueDailyProjectData; import org.hackystat.dailyprojectdata.resource.issue.jaxb.IssueData; import org.hackystat.sensorbase.client.SensorBaseClient; import org.hackystat.sensorbase.resource.sensordata.jaxb.SensorDataIndex; import org.hackystat.sensorbase.resource.sensordata.jaxb.SensorDataRef; import org.hackystat.utilities.tstamp.Tstamp; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.resource.Representation; import org.restlet.resource.Variant; import org.w3c.dom.Document; /** * Implements the Resource for processing GET {host}/issue/{user}/{project}/{starttime} requests. * Requires the authenticated user to be {user} or else the Admin user for the sensorbase * connected to this service. * @author Shaoxuan Zhang */ public class IssueResource extends DailyProjectDataResource { private String status; /** * The standard constructor. * @param context The context. * @param request The request object. * @param response The response object. */ public IssueResource(Context context, Request request, Response response) { super(context, request, response); this.status = (String) request.getAttributes().get("Status"); } /** * Returns an IssueDailyProjectData instance representing the Issue associated with the * Project data, or null if not authorized. * Authenticated user must be the uriUser, or Admin, or project member. * @param variant The representational variant requested. * @return The representation. */ @Override public Representation represent(Variant variant) { Logger logger = this.server.getLogger(); logger.fine("Issue DPD: Starting"); if (variant.getMediaType().equals(MediaType.TEXT_XML)) { try { // [1] get the SensorBaseClient for the user making this request. SensorBaseClient client = super.getSensorBaseClient(); // [2] Check the front side cache and return if the DPD is found and is OK to access. String cachedDpd = this.server.getFrontSideCache().get(uriUser, project, uriString); if ((cachedDpd != null) && client.inProject(uriUser, project)) { return super.getStringRepresentation(cachedDpd); } // [2] get a SensorDataIndex of all Issue data for this Project on the requested day. XMLGregorianCalendar startTime = Tstamp.makeTimestamp(this.timestamp); XMLGregorianCalendar endTime = Tstamp.incrementDays(startTime, 1); logger.fine("Issue DPD: Requesting index: " + uriUser + " " + project); XMLGregorianCalendar projectStartTime = client.getProject(uriUser, project).getStartTime(); SensorDataIndex index = client.getProjectSensorData(uriUser, project, projectStartTime, endTime, "Issue"); logger.fine("Issue DPD: Got index: " + index.getSensorDataRef().size() + " instances"); // [3] prepare the IssueDailyProjectData IssueDailyProjectData issueDpd = new IssueDailyProjectData(); issueDpd.setOwner(uriUser); issueDpd.setProject(project); issueDpd.setStartTime(startTime); // [4] parse Issue SensorData. int openIssue = 0; IssueDataParser parser = new IssueDataParser(this.server.getLogger()); for (SensorDataRef ref : index.getSensorDataRef()) { IssueData issueData = parser.getIssueDpd(client.getSensorData(ref), endTime); boolean isOpen = parser.isOpenStatus(issueData.getStatus()); boolean include = false; - if ((status == null) || - ((status.equalsIgnoreCase("open") && isOpen) || - (status.equalsIgnoreCase("closed") && !isOpen) || - (status.equalsIgnoreCase(issueData.getStatus())))) { + if ((status == null) || (status.equalsIgnoreCase("all")) || + (status.equalsIgnoreCase("open") && isOpen) || + (status.equalsIgnoreCase("closed") && !isOpen) || + (status.equalsIgnoreCase(issueData.getStatus()))) { include = true; issueDpd.getIssueData().add(issueData); } if (include && isOpen) { openIssue++; } } // [5] finish the IssueDailyProjectData and send. issueDpd.setOpenIssues(openIssue); String xmlData = makeIssues(issueDpd); if (!Tstamp.isTodayOrLater(startTime)) { this.server.getFrontSideCache().put(uriUser, project, uriString, xmlData); } logRequest("Issue"); return super.getStringRepresentation(xmlData); } catch (Exception e) { setStatusError("Error creating Issue DPD.", e); return null; } } return null; } /** * Returns the passed SensorData instance as a String encoding of its XML representation. * @param data The SensorData instance. * @return The XML String representation. * @throws Exception If problems occur during translation. */ private String makeIssues (IssueDailyProjectData data) throws Exception { JAXBContext devTimeJAXB = (JAXBContext)this.server.getContext().getAttributes().get("IssueJAXB"); Marshaller marshaller = devTimeJAXB.createMarshaller(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); Document doc = documentBuilder.newDocument(); marshaller.marshal(data, doc); DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } }
true
true
public Representation represent(Variant variant) { Logger logger = this.server.getLogger(); logger.fine("Issue DPD: Starting"); if (variant.getMediaType().equals(MediaType.TEXT_XML)) { try { // [1] get the SensorBaseClient for the user making this request. SensorBaseClient client = super.getSensorBaseClient(); // [2] Check the front side cache and return if the DPD is found and is OK to access. String cachedDpd = this.server.getFrontSideCache().get(uriUser, project, uriString); if ((cachedDpd != null) && client.inProject(uriUser, project)) { return super.getStringRepresentation(cachedDpd); } // [2] get a SensorDataIndex of all Issue data for this Project on the requested day. XMLGregorianCalendar startTime = Tstamp.makeTimestamp(this.timestamp); XMLGregorianCalendar endTime = Tstamp.incrementDays(startTime, 1); logger.fine("Issue DPD: Requesting index: " + uriUser + " " + project); XMLGregorianCalendar projectStartTime = client.getProject(uriUser, project).getStartTime(); SensorDataIndex index = client.getProjectSensorData(uriUser, project, projectStartTime, endTime, "Issue"); logger.fine("Issue DPD: Got index: " + index.getSensorDataRef().size() + " instances"); // [3] prepare the IssueDailyProjectData IssueDailyProjectData issueDpd = new IssueDailyProjectData(); issueDpd.setOwner(uriUser); issueDpd.setProject(project); issueDpd.setStartTime(startTime); // [4] parse Issue SensorData. int openIssue = 0; IssueDataParser parser = new IssueDataParser(this.server.getLogger()); for (SensorDataRef ref : index.getSensorDataRef()) { IssueData issueData = parser.getIssueDpd(client.getSensorData(ref), endTime); boolean isOpen = parser.isOpenStatus(issueData.getStatus()); boolean include = false; if ((status == null) || ((status.equalsIgnoreCase("open") && isOpen) || (status.equalsIgnoreCase("closed") && !isOpen) || (status.equalsIgnoreCase(issueData.getStatus())))) { include = true; issueDpd.getIssueData().add(issueData); } if (include && isOpen) { openIssue++; } } // [5] finish the IssueDailyProjectData and send. issueDpd.setOpenIssues(openIssue); String xmlData = makeIssues(issueDpd); if (!Tstamp.isTodayOrLater(startTime)) { this.server.getFrontSideCache().put(uriUser, project, uriString, xmlData); } logRequest("Issue"); return super.getStringRepresentation(xmlData); } catch (Exception e) { setStatusError("Error creating Issue DPD.", e); return null; } } return null; }
public Representation represent(Variant variant) { Logger logger = this.server.getLogger(); logger.fine("Issue DPD: Starting"); if (variant.getMediaType().equals(MediaType.TEXT_XML)) { try { // [1] get the SensorBaseClient for the user making this request. SensorBaseClient client = super.getSensorBaseClient(); // [2] Check the front side cache and return if the DPD is found and is OK to access. String cachedDpd = this.server.getFrontSideCache().get(uriUser, project, uriString); if ((cachedDpd != null) && client.inProject(uriUser, project)) { return super.getStringRepresentation(cachedDpd); } // [2] get a SensorDataIndex of all Issue data for this Project on the requested day. XMLGregorianCalendar startTime = Tstamp.makeTimestamp(this.timestamp); XMLGregorianCalendar endTime = Tstamp.incrementDays(startTime, 1); logger.fine("Issue DPD: Requesting index: " + uriUser + " " + project); XMLGregorianCalendar projectStartTime = client.getProject(uriUser, project).getStartTime(); SensorDataIndex index = client.getProjectSensorData(uriUser, project, projectStartTime, endTime, "Issue"); logger.fine("Issue DPD: Got index: " + index.getSensorDataRef().size() + " instances"); // [3] prepare the IssueDailyProjectData IssueDailyProjectData issueDpd = new IssueDailyProjectData(); issueDpd.setOwner(uriUser); issueDpd.setProject(project); issueDpd.setStartTime(startTime); // [4] parse Issue SensorData. int openIssue = 0; IssueDataParser parser = new IssueDataParser(this.server.getLogger()); for (SensorDataRef ref : index.getSensorDataRef()) { IssueData issueData = parser.getIssueDpd(client.getSensorData(ref), endTime); boolean isOpen = parser.isOpenStatus(issueData.getStatus()); boolean include = false; if ((status == null) || (status.equalsIgnoreCase("all")) || (status.equalsIgnoreCase("open") && isOpen) || (status.equalsIgnoreCase("closed") && !isOpen) || (status.equalsIgnoreCase(issueData.getStatus()))) { include = true; issueDpd.getIssueData().add(issueData); } if (include && isOpen) { openIssue++; } } // [5] finish the IssueDailyProjectData and send. issueDpd.setOpenIssues(openIssue); String xmlData = makeIssues(issueDpd); if (!Tstamp.isTodayOrLater(startTime)) { this.server.getFrontSideCache().put(uriUser, project, uriString, xmlData); } logRequest("Issue"); return super.getStringRepresentation(xmlData); } catch (Exception e) { setStatusError("Error creating Issue DPD.", e); return null; } } return null; }
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTree.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTree.java index f10dbfcc0..2011a42db 100644 --- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTree.java +++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTree.java @@ -1,564 +1,566 @@ /******************************************************************************* * Copyright (c) 2000, 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 * Martin Oberhuber (Wind River) - [105554] handle cyclic symbolic links * Martin Oberhuber (Wind River) - [232426] shared prefix histories for symlinks * Serge Beauchamp (Freescale Semiconductor) - [252996] add resource filtering * Martin Oberhuber (Wind River) - [292267] OutOfMemoryError due to leak in UnifiedTree *******************************************************************************/ package org.eclipse.core.internal.localstore; import java.io.IOException; import java.util.*; import java.util.regex.Pattern; import org.eclipse.core.filesystem.*; import org.eclipse.core.internal.refresh.RefreshJob; import org.eclipse.core.internal.resources.*; import org.eclipse.core.internal.utils.Queue; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; /** * Represents the workspace's tree merged with the file system's tree. */ public class UnifiedTree { /** special node to mark the separation of a node's children */ protected static final UnifiedTreeNode childrenMarker = new UnifiedTreeNode(null, null, null, null, false); private static final Iterator EMPTY_ITERATOR = Collections.EMPTY_LIST.iterator(); /** special node to mark the beginning of a level in the tree */ protected static final UnifiedTreeNode levelMarker = new UnifiedTreeNode(null, null, null, null, false); private static final IFileInfo[] NO_CHILDREN = new IFileInfo[0]; /** Singleton to indicate no local children */ private static final IResource[] NO_RESOURCES = new IResource[0]; /** * True if the level of the children of the current node are valid according * to the requested refresh depth, false otherwise */ protected boolean childLevelValid = false; /** an IFileTree which can be used to build a unified tree*/ protected IFileTree fileTree = null; /** Spare node objects available for reuse */ protected ArrayList freeNodes = new ArrayList(); /** tree's actual level */ protected int level; /** our queue */ protected Queue queue; /** path prefixes for checking symbolic link cycles */ protected PrefixPool pathPrefixHistory, rootPathHistory; /** tree's root */ protected IResource root; /** * The root must only be a file or a folder. */ public UnifiedTree(IResource root) { setRoot(root); } /** * Pass in a a root for the tree, a file tree containing all of the entries for this * tree and a flag indicating whether the UnifiedTree should consult the fileTree where * possible for entries * @param root * @param fileTree */ public UnifiedTree(IResource root, IFileTree fileTree) { this(root); this.fileTree = fileTree; } public void accept(IUnifiedTreeVisitor visitor) throws CoreException { accept(visitor, IResource.DEPTH_INFINITE); } /** * Performs a breadth-first traversal of the unified tree, passing each * node to the provided visitor. */ public void accept(IUnifiedTreeVisitor visitor, int depth) throws CoreException { Assert.isNotNull(root); initializeQueue(); setLevel(0, depth); while (!queue.isEmpty()) { UnifiedTreeNode node = (UnifiedTreeNode) queue.remove(); if (isChildrenMarker(node)) continue; if (isLevelMarker(node)) { if (!setLevel(getLevel() + 1, depth)) break; continue; } if (visitor.visit(node)) addNodeChildrenToQueue(node); else removeNodeChildrenFromQueue(node); //allow reuse of the node, but don't let the freeNodes list grow infinitely if (freeNodes.size() < 32767) { //free memory-consuming elements of the node for garbage collection node.releaseForGc(); freeNodes.add(node); } //else, the whole node will be garbage collected since there is no //reference to it any more. } } protected void addChildren(UnifiedTreeNode node) { Resource parent = (Resource) node.getResource(); // is there a possibility to have children? int parentType = parent.getType(); if (parentType == IResource.FILE && !node.isFolder()) return; //don't refresh resources in closed or non-existent projects if (!parent.getProject().isAccessible()) return; // get the list of resources in the file system // don't ask for local children if we know it doesn't exist locally IFileInfo[] list = node.existsInFileSystem() ? getLocalList(node) : NO_CHILDREN; int localIndex = 0; // See if the children of this resource have been computed before ResourceInfo resourceInfo = parent.getResourceInfo(false, false); int flags = parent.getFlags(resourceInfo); boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN); // get the list of resources in the workspace if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) { IResource target = null; UnifiedTreeNode child = null; IResource[] members; try { members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS | IContainer.INCLUDE_HIDDEN); } catch (CoreException e) { members = NO_RESOURCES; } int workspaceIndex = 0; //iterate simultaneously over file system and workspace members while (workspaceIndex < members.length) { target = members[workspaceIndex]; String name = target.getName(); IFileInfo localInfo = localIndex < list.length ? list[localIndex] : null; int comp = localInfo != null ? name.compareTo(localInfo.getName()) : -1; //special handling for linked resources if (target.isLinked()) { //child will be null if location is undefined child = createChildForLinkedResource(target); workspaceIndex++; //if there is a matching local file, skip it - it will be blocked by the linked resource if (comp == 0) localIndex++; } else if (comp == 0) { // resource exists in workspace and file system --> localInfo is non-null //create workspace-only node for symbolic link that creates a cycle if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) child = createNode(target, null, null, true); else child = createNode(target, null, localInfo, true); localIndex++; workspaceIndex++; } else if (comp > 0) { // resource exists only in file system //don't create a node for symbolic links that create a cycle - if (!localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) || !localInfo.isDirectory() || !isRecursiveLink(node.getStore(), localInfo)) + if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) + child = null; + else child = createChildNodeFromFileSystem(node, localInfo); localIndex++; } else { // resource exists only in the workspace child = createNode(target, null, null, true); workspaceIndex++; } if (child != null) addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, list, localIndex); /* Mark the children as now known */ if (unknown) { // Don't open the info - we might not be inside a workspace-modifying operation resourceInfo = parent.getResourceInfo(false, false); if (resourceInfo != null) resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN); } /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); } protected void addChildrenFromFileSystem(UnifiedTreeNode node, IFileInfo[] childInfos, int index) { if (childInfos == null) return; for (int i = index; i < childInfos.length; i++) { IFileInfo info = childInfos[i]; //don't create a node for symbolic links that create a cycle if (!info.getAttribute(EFS.ATTRIBUTE_SYMLINK) || !info.isDirectory() || !isRecursiveLink(node.getStore(), info)) addChildToTree(node, createChildNodeFromFileSystem(node, info)); } } protected void addChildrenMarker() { addElementToQueue(childrenMarker); } protected void addChildToTree(UnifiedTreeNode node, UnifiedTreeNode child) { if (node.getFirstChild() == null) node.setFirstChild(child); addElementToQueue(child); } protected void addElementToQueue(UnifiedTreeNode target) { queue.add(target); } protected void addNodeChildrenToQueue(UnifiedTreeNode node) { /* if the first child is not null we already added the children */ /* If the children won't be at a valid level for the refresh depth, don't bother adding them */ if (!childLevelValid || node.getFirstChild() != null) return; addChildren(node); if (queue.isEmpty()) return; //if we're about to change levels, then the children just added //are the last nodes for their level, so add a level marker to the queue UnifiedTreeNode nextNode = (UnifiedTreeNode) queue.peek(); if (isChildrenMarker(nextNode)) queue.remove(); nextNode = (UnifiedTreeNode) queue.peek(); if (isLevelMarker(nextNode)) addElementToQueue(levelMarker); } protected void addRootToQueue() { //don't refresh in closed projects if (!root.getProject().isAccessible()) return; IFileStore store = ((Resource) root).getStore(); IFileInfo fileInfo = fileTree != null ? fileTree.getFileInfo(store) : store.fetchInfo(); UnifiedTreeNode node = createNode(root, store, fileInfo, root.exists()); if (node.existsInFileSystem() || node.existsInWorkspace()) addElementToQueue(node); } /** * Creates a tree node for a resource that is linked in a different file system location. */ protected UnifiedTreeNode createChildForLinkedResource(IResource target) { IFileStore store = ((Resource) target).getStore(); return createNode(target, store, store.fetchInfo(), true); } /** * Creates a child node for a location in the file system. Does nothing and returns null if the location does not correspond to a valid file/folder. */ protected UnifiedTreeNode createChildNodeFromFileSystem(UnifiedTreeNode parent, IFileInfo info) { IPath childPath = parent.getResource().getFullPath().append(info.getName()); int type = info.isDirectory() ? IResource.FOLDER : IResource.FILE; IResource target = getWorkspace().newResource(childPath, type); return createNode(target, null, info, false); } /** * Factory method for creating a node for this tree. If the file exists on * disk, either the parent store or child store can be provided. Providing * only the parent store avoids creation of the child store in cases where * it is not needed. The store object is only needed for directories for * simple file system traversals, so this avoids creating store objects * for all files. */ protected UnifiedTreeNode createNode(IResource resource, IFileStore store, IFileInfo info, boolean existsWorkspace) { //first check for reusable objects UnifiedTreeNode node = null; int size = freeNodes.size(); if (size > 0) { node = (UnifiedTreeNode) freeNodes.remove(size - 1); node.reuse(this, resource, store, info, existsWorkspace); return node; } //none available, so create a new one return new UnifiedTreeNode(this, resource, store, info, existsWorkspace); } protected Iterator getChildren(UnifiedTreeNode node) { /* if first child is null we need to add node's children to queue */ if (node.getFirstChild() == null) addNodeChildrenToQueue(node); /* if the first child is still null, the node does not have any children */ if (node.getFirstChild() == null) return EMPTY_ITERATOR; /* get the index of the first child */ int index = queue.indexOf(node.getFirstChild()); /* if we do not have children, just return an empty enumeration */ if (index == -1) return EMPTY_ITERATOR; /* create an enumeration with node's children */ List result = new ArrayList(10); while (true) { UnifiedTreeNode child = (UnifiedTreeNode) queue.elementAt(index); if (isChildrenMarker(child)) break; result.add(child); index = queue.increment(index); } return result.iterator(); } protected int getLevel() { return level; } protected IFileInfo[] getLocalList(UnifiedTreeNode node) { try { final IFileStore store = node.getStore(); IFileInfo[] list = fileTree != null ? fileTree.getChildInfos(store) : store.childInfos(EFS.NONE, null); if (list == null) return NO_CHILDREN; list = ((Resource) node.getResource()).filterChildren(list); int size = list.length; if (size > 1) quickSort(list, 0, size - 1); return list; } catch (CoreException e) { //treat failure to access the directory as a non-existent directory return NO_CHILDREN; } } protected Workspace getWorkspace() { return (Workspace) root.getWorkspace(); } protected void initializeQueue() { //initialize the queue if (queue == null) queue = new Queue(100, false); else queue.reset(); //initialize the free nodes list if (freeNodes == null) freeNodes = new ArrayList(100); else freeNodes.clear(); addRootToQueue(); addElementToQueue(levelMarker); } protected boolean isChildrenMarker(UnifiedTreeNode node) { return node == childrenMarker; } protected boolean isLevelMarker(UnifiedTreeNode node) { return node == levelMarker; } private static class PatternHolder { //Initialize-on-demand Holder class to avoid compiling Pattern if never needed //Pattern: A UNIX relative path that just points backward public static Pattern trivialSymlinkPattern = Pattern.compile("\\.[./]*"); //$NON-NLS-1$ } /** * Initialize history stores for symbolic links. * This may be done when starting a visitor, or later on demand. */ protected void initLinkHistoriesIfNeeded() { if (pathPrefixHistory == null) { //Bug 232426: Check what life cycle we need for the histories Job job = Job.getJobManager().currentJob(); if (job instanceof RefreshJob) { //we are running from the RefreshJob: use the path history of the job RefreshJob refreshJob = (RefreshJob) job; pathPrefixHistory = refreshJob.getPathPrefixHistory(); rootPathHistory = refreshJob.getRootPathHistory(); } else { //Local Histories pathPrefixHistory = new PrefixPool(20); rootPathHistory = new PrefixPool(20); } } if (rootPathHistory.size() == 0) { //add current root to history IFileStore rootStore = ((Resource) root).getStore(); try { java.io.File rootFile = rootStore.toLocalFile(EFS.NONE, null); if (rootFile != null) { IPath rootProjPath = root.getProject().getLocation(); if (rootProjPath != null) { try { java.io.File rootProjFile = new java.io.File(rootProjPath.toOSString()); rootPathHistory.insertShorter(rootProjFile.getCanonicalPath() + '/'); } catch (IOException ioe) { /*ignore here*/ } } rootPathHistory.insertShorter(rootFile.getCanonicalPath() + '/'); } } catch (CoreException e) { /*ignore*/ } catch (IOException e) { /*ignore*/ } } } /** * Check if the given child represents a recursive symbolic link. * <p> * On remote EFS stores, this check is not exhaustive and just * finds trivial recursive symbolic links pointing up in the tree. * </p><p> * On local stores, where {@link java.io.File#getCanonicalPath()} * is available, the test is exhaustive but may also find some * false positives with transitive symbolic links. This may lead * to suppressing duplicates of already known resources in the * tree, but it will never lead to not finding a resource at * all. See bug 105554 for details. * </p> * @param parentStore EFS IFileStore representing the parent folder * @param localInfo child representing a symbolic link * @return <code>true</code> if the given child represents a * recursive symbolic link. */ private boolean isRecursiveLink(IFileStore parentStore, IFileInfo localInfo) { //Try trivial pattern first - works also on remote EFS stores String linkTarget = localInfo.getStringAttribute(EFS.ATTRIBUTE_LINK_TARGET); if (linkTarget != null && PatternHolder.trivialSymlinkPattern.matcher(linkTarget).matches()) { return true; } //Need canonical paths to check all other possibilities try { java.io.File parentFile = parentStore.toLocalFile(EFS.NONE, null); //If this store cannot be represented as a local file, there is nothing we can do //In the future, we could try to resolve the link target //against the remote file system to do more checks. if (parentFile == null) return false; //get canonical path for both child and parent java.io.File childFile = new java.io.File(parentFile, localInfo.getName()); String parentPath = parentFile.getCanonicalPath() + '/'; String childPath = childFile.getCanonicalPath() + '/'; //get or instantiate the prefix and root path histories. //Might be done earlier - for now, do it on demand. initLinkHistoriesIfNeeded(); //insert the parent for checking loops pathPrefixHistory.insertLonger(parentPath); if (pathPrefixHistory.containsAsPrefix(childPath)) { //found a potential loop: is it spanning up a new tree? if (!rootPathHistory.insertShorter(childPath)) { //not spanning up a new tree, so it is a real loop. return true; } } else if (rootPathHistory.hasPrefixOf(childPath)) { //child points into a different portion of the tree that we visited already before, or will certainly visit. //This does not introduce a loop yet, but introduces duplicate resources. //TODO Ideally, such duplicates should be modelled as linked resources. See bug 105534 return false; } else { //child neither introduces a loop nor points to a known tree. //It probably spans up a new tree of potential prefixes. rootPathHistory.insertShorter(childPath); } } catch (IOException e) { //ignore } catch (CoreException e) { //ignore } return false; } protected boolean isValidLevel(int currentLevel, int depth) { switch (depth) { case IResource.DEPTH_INFINITE : return true; case IResource.DEPTH_ONE : return currentLevel <= 1; case IResource.DEPTH_ZERO : return currentLevel == 0; default : return currentLevel + 1000 <= depth; } } /** * Sorts the given array of strings in place. This is * not using the sorting framework to avoid casting overhead. */ protected void quickSort(IFileInfo[] infos, int left, int right) { int originalLeft = left; int originalRight = right; IFileInfo mid = infos[(left + right) / 2]; do { while (mid.compareTo(infos[left]) > 0) left++; while (infos[right].compareTo(mid) > 0) right--; if (left <= right) { IFileInfo tmp = infos[left]; infos[left] = infos[right]; infos[right] = tmp; left++; right--; } } while (left <= right); if (originalLeft < right) quickSort(infos, originalLeft, right); if (left < originalRight) quickSort(infos, left, originalRight); return; } /** * Remove from the last element of the queue to the first child of the * given node. */ protected void removeNodeChildrenFromQueue(UnifiedTreeNode node) { UnifiedTreeNode first = node.getFirstChild(); if (first == null) return; while (true) { if (first.equals(queue.removeTail())) break; } node.setFirstChild(null); } /** * Increases the current tree level by one. Returns true if the new * level is still valid for the given depth */ protected boolean setLevel(int newLevel, int depth) { level = newLevel; childLevelValid = isValidLevel(level + 1, depth); return isValidLevel(level, depth); } private void setRoot(IResource root) { this.root = root; } }
true
true
protected void addChildren(UnifiedTreeNode node) { Resource parent = (Resource) node.getResource(); // is there a possibility to have children? int parentType = parent.getType(); if (parentType == IResource.FILE && !node.isFolder()) return; //don't refresh resources in closed or non-existent projects if (!parent.getProject().isAccessible()) return; // get the list of resources in the file system // don't ask for local children if we know it doesn't exist locally IFileInfo[] list = node.existsInFileSystem() ? getLocalList(node) : NO_CHILDREN; int localIndex = 0; // See if the children of this resource have been computed before ResourceInfo resourceInfo = parent.getResourceInfo(false, false); int flags = parent.getFlags(resourceInfo); boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN); // get the list of resources in the workspace if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) { IResource target = null; UnifiedTreeNode child = null; IResource[] members; try { members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS | IContainer.INCLUDE_HIDDEN); } catch (CoreException e) { members = NO_RESOURCES; } int workspaceIndex = 0; //iterate simultaneously over file system and workspace members while (workspaceIndex < members.length) { target = members[workspaceIndex]; String name = target.getName(); IFileInfo localInfo = localIndex < list.length ? list[localIndex] : null; int comp = localInfo != null ? name.compareTo(localInfo.getName()) : -1; //special handling for linked resources if (target.isLinked()) { //child will be null if location is undefined child = createChildForLinkedResource(target); workspaceIndex++; //if there is a matching local file, skip it - it will be blocked by the linked resource if (comp == 0) localIndex++; } else if (comp == 0) { // resource exists in workspace and file system --> localInfo is non-null //create workspace-only node for symbolic link that creates a cycle if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) child = createNode(target, null, null, true); else child = createNode(target, null, localInfo, true); localIndex++; workspaceIndex++; } else if (comp > 0) { // resource exists only in file system //don't create a node for symbolic links that create a cycle if (!localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) || !localInfo.isDirectory() || !isRecursiveLink(node.getStore(), localInfo)) child = createChildNodeFromFileSystem(node, localInfo); localIndex++; } else { // resource exists only in the workspace child = createNode(target, null, null, true); workspaceIndex++; } if (child != null) addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, list, localIndex); /* Mark the children as now known */ if (unknown) { // Don't open the info - we might not be inside a workspace-modifying operation resourceInfo = parent.getResourceInfo(false, false); if (resourceInfo != null) resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN); } /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); }
protected void addChildren(UnifiedTreeNode node) { Resource parent = (Resource) node.getResource(); // is there a possibility to have children? int parentType = parent.getType(); if (parentType == IResource.FILE && !node.isFolder()) return; //don't refresh resources in closed or non-existent projects if (!parent.getProject().isAccessible()) return; // get the list of resources in the file system // don't ask for local children if we know it doesn't exist locally IFileInfo[] list = node.existsInFileSystem() ? getLocalList(node) : NO_CHILDREN; int localIndex = 0; // See if the children of this resource have been computed before ResourceInfo resourceInfo = parent.getResourceInfo(false, false); int flags = parent.getFlags(resourceInfo); boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN); // get the list of resources in the workspace if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) { IResource target = null; UnifiedTreeNode child = null; IResource[] members; try { members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS | IContainer.INCLUDE_HIDDEN); } catch (CoreException e) { members = NO_RESOURCES; } int workspaceIndex = 0; //iterate simultaneously over file system and workspace members while (workspaceIndex < members.length) { target = members[workspaceIndex]; String name = target.getName(); IFileInfo localInfo = localIndex < list.length ? list[localIndex] : null; int comp = localInfo != null ? name.compareTo(localInfo.getName()) : -1; //special handling for linked resources if (target.isLinked()) { //child will be null if location is undefined child = createChildForLinkedResource(target); workspaceIndex++; //if there is a matching local file, skip it - it will be blocked by the linked resource if (comp == 0) localIndex++; } else if (comp == 0) { // resource exists in workspace and file system --> localInfo is non-null //create workspace-only node for symbolic link that creates a cycle if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) child = createNode(target, null, null, true); else child = createNode(target, null, localInfo, true); localIndex++; workspaceIndex++; } else if (comp > 0) { // resource exists only in file system //don't create a node for symbolic links that create a cycle if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) child = null; else child = createChildNodeFromFileSystem(node, localInfo); localIndex++; } else { // resource exists only in the workspace child = createNode(target, null, null, true); workspaceIndex++; } if (child != null) addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, list, localIndex); /* Mark the children as now known */ if (unknown) { // Don't open the info - we might not be inside a workspace-modifying operation resourceInfo = parent.getResourceInfo(false, false); if (resourceInfo != null) resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN); } /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); }
diff --git a/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/actions/ReconnectMarketDataFeedJob.java b/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/actions/ReconnectMarketDataFeedJob.java index e532c65b9..b92968472 100644 --- a/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/actions/ReconnectMarketDataFeedJob.java +++ b/source/trunk/plugins/org.marketcetera.photon/src/main/java/org/marketcetera/photon/actions/ReconnectMarketDataFeedJob.java @@ -1,170 +1,170 @@ package org.marketcetera.photon.actions; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.log4j.Logger; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.preferences.ScopedPreferenceStore; import org.marketcetera.marketdata.IMarketDataFeed; import org.marketcetera.marketdata.IMarketDataFeedFactory; import org.marketcetera.photon.PhotonPlugin; import org.marketcetera.photon.marketdata.IMarketDataConstants; import org.marketcetera.photon.marketdata.MarketDataFeedService; import org.marketcetera.photon.marketdata.MarketDataFeedTracker; import org.marketcetera.quickfix.ConnectionConstants; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; public class ReconnectMarketDataFeedJob extends Job { private static AtomicBoolean reconnectInProgress = new AtomicBoolean(false); private BundleContext bundleContext; MarketDataFeedTracker marketDataFeedTracker; public ReconnectMarketDataFeedJob(String name) { super(name); bundleContext = PhotonPlugin.getDefault().getBundleContext(); marketDataFeedTracker = new MarketDataFeedTracker(bundleContext); marketDataFeedTracker.open(); } @Override protected IStatus run(IProgressMonitor monitor) { Logger logger = PhotonPlugin.getMainConsoleLogger(); if (reconnectInProgress.getAndSet(true)){ return Status.CANCEL_STATUS; } boolean succeeded = false; try { disconnect(marketDataFeedTracker); } catch (Throwable th) { PhotonPlugin.getMainConsoleLogger().warn("Could not disconnect from quote feed"); } try { IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry(); IExtensionPoint extensionPoint = extensionRegistry.getExtensionPoint(IMarketDataConstants.EXTENSION_POINT_ID); IExtension[] extensions = extensionPoint.getExtensions(); Set<String> startupFeeds = getStartupFeeds(); if (extensions != null && extensions.length > 0) { for (IExtension anExtension : extensions) { String pluginName = anExtension.getContributor().getName(); if (startupFeeds.contains(pluginName)) { IConfigurationElement[] configurationElements = anExtension.getConfigurationElements(); IConfigurationElement feedElement = configurationElements[0]; String factoryClass = feedElement.getAttribute(IMarketDataConstants.FEED_FACTORY_CLASS_ATTRIBUTE); Class<IMarketDataFeedFactory> clazz = (Class<IMarketDataFeedFactory>) Class.forName(factoryClass); Constructor<IMarketDataFeedFactory> constructor = clazz.getConstructor( new Class[0] ); IMarketDataFeedFactory factory = constructor.newInstance(new Object[0]); ScopedPreferenceStore store = PhotonPlugin.getDefault().getPreferenceStore(); String url = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_URL_SUFFIX); String user = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_USER_SUFFIX); String password = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_PASSWORD_SUFFIX); Map<String, Object> parameters = getParameters(factory, store, pluginName); IMarketDataFeed targetQuoteFeed = factory.getInstance(url, user, password, parameters); MarketDataFeedService marketDataFeedService = new MarketDataFeedService(targetQuoteFeed); ServiceRegistration registration = bundleContext.registerService(MarketDataFeedService.class.getName(), marketDataFeedService, null); marketDataFeedService.setServiceRegistration(registration); marketDataFeedService.afterPropertiesSet(); targetQuoteFeed.start(); succeeded = true; break; } } } } catch (Exception e) { - logger.error("Exception connecting to quote feed", e); + logger.error("Exception connecting to market data feed: "+e.getMessage(), e); return Status.CANCEL_STATUS; } finally { reconnectInProgress.set(false); if (!succeeded){ - logger.error("Error connecting to quote feed"); + logger.error("Error connecting to market data feed"); return Status.CANCEL_STATUS; } } return Status.OK_STATUS; } private Map<String, Object> getParameters(IMarketDataFeedFactory factory, ScopedPreferenceStore store, String pluginName) { String[] keys = factory.getAllowedPropertyKeys(); Map<String, Object> map = new HashMap<String, Object>(); for (String key : keys) { String fqKey = constructKey(pluginName, key); if (store.contains(fqKey)){ map.put(key, store.getString(fqKey)); } } return map; } private String getPreference(ScopedPreferenceStore store, String ... pieces) { return store.getString(constructKey(pieces)); } private String constructKey(String... pieces) { StringBuilder builder = new StringBuilder(ConnectionConstants.MARKETDATA_KEY_BASE); builder.append('.'); int i; for (i = 0; i < pieces.length-1; i++) { builder.append(pieces[i]); builder.append('.'); } builder.append(pieces[i]); return builder.toString(); } private Set<String> getStartupFeeds() { String startupString = PhotonPlugin.getDefault().getPreferenceStore().getString(ConnectionConstants.MARKETDATA_STARTUP_KEY); startupString.split("[\\s,]+"); return new HashSet<String>(Arrays.asList(startupString.split("[\\s,]+"))); } public static void disconnect(MarketDataFeedTracker marketDataFeedTracker) { MarketDataFeedService service = (MarketDataFeedService) marketDataFeedTracker.getMarketDataFeedService(); if (service != null){ ServiceRegistration serviceRegistration = service.getServiceRegistration(); if (serviceRegistration != null){ serviceRegistration.unregister(); } } RuntimeException caughtException = null; if (service != null){ try { service.stop(); } catch (RuntimeException e) { caughtException = e; } } if (caughtException != null){ throw caughtException; } } }
false
true
protected IStatus run(IProgressMonitor monitor) { Logger logger = PhotonPlugin.getMainConsoleLogger(); if (reconnectInProgress.getAndSet(true)){ return Status.CANCEL_STATUS; } boolean succeeded = false; try { disconnect(marketDataFeedTracker); } catch (Throwable th) { PhotonPlugin.getMainConsoleLogger().warn("Could not disconnect from quote feed"); } try { IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry(); IExtensionPoint extensionPoint = extensionRegistry.getExtensionPoint(IMarketDataConstants.EXTENSION_POINT_ID); IExtension[] extensions = extensionPoint.getExtensions(); Set<String> startupFeeds = getStartupFeeds(); if (extensions != null && extensions.length > 0) { for (IExtension anExtension : extensions) { String pluginName = anExtension.getContributor().getName(); if (startupFeeds.contains(pluginName)) { IConfigurationElement[] configurationElements = anExtension.getConfigurationElements(); IConfigurationElement feedElement = configurationElements[0]; String factoryClass = feedElement.getAttribute(IMarketDataConstants.FEED_FACTORY_CLASS_ATTRIBUTE); Class<IMarketDataFeedFactory> clazz = (Class<IMarketDataFeedFactory>) Class.forName(factoryClass); Constructor<IMarketDataFeedFactory> constructor = clazz.getConstructor( new Class[0] ); IMarketDataFeedFactory factory = constructor.newInstance(new Object[0]); ScopedPreferenceStore store = PhotonPlugin.getDefault().getPreferenceStore(); String url = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_URL_SUFFIX); String user = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_USER_SUFFIX); String password = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_PASSWORD_SUFFIX); Map<String, Object> parameters = getParameters(factory, store, pluginName); IMarketDataFeed targetQuoteFeed = factory.getInstance(url, user, password, parameters); MarketDataFeedService marketDataFeedService = new MarketDataFeedService(targetQuoteFeed); ServiceRegistration registration = bundleContext.registerService(MarketDataFeedService.class.getName(), marketDataFeedService, null); marketDataFeedService.setServiceRegistration(registration); marketDataFeedService.afterPropertiesSet(); targetQuoteFeed.start(); succeeded = true; break; } } } } catch (Exception e) { logger.error("Exception connecting to quote feed", e); return Status.CANCEL_STATUS; } finally { reconnectInProgress.set(false); if (!succeeded){ logger.error("Error connecting to quote feed"); return Status.CANCEL_STATUS; } } return Status.OK_STATUS; }
protected IStatus run(IProgressMonitor monitor) { Logger logger = PhotonPlugin.getMainConsoleLogger(); if (reconnectInProgress.getAndSet(true)){ return Status.CANCEL_STATUS; } boolean succeeded = false; try { disconnect(marketDataFeedTracker); } catch (Throwable th) { PhotonPlugin.getMainConsoleLogger().warn("Could not disconnect from quote feed"); } try { IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry(); IExtensionPoint extensionPoint = extensionRegistry.getExtensionPoint(IMarketDataConstants.EXTENSION_POINT_ID); IExtension[] extensions = extensionPoint.getExtensions(); Set<String> startupFeeds = getStartupFeeds(); if (extensions != null && extensions.length > 0) { for (IExtension anExtension : extensions) { String pluginName = anExtension.getContributor().getName(); if (startupFeeds.contains(pluginName)) { IConfigurationElement[] configurationElements = anExtension.getConfigurationElements(); IConfigurationElement feedElement = configurationElements[0]; String factoryClass = feedElement.getAttribute(IMarketDataConstants.FEED_FACTORY_CLASS_ATTRIBUTE); Class<IMarketDataFeedFactory> clazz = (Class<IMarketDataFeedFactory>) Class.forName(factoryClass); Constructor<IMarketDataFeedFactory> constructor = clazz.getConstructor( new Class[0] ); IMarketDataFeedFactory factory = constructor.newInstance(new Object[0]); ScopedPreferenceStore store = PhotonPlugin.getDefault().getPreferenceStore(); String url = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_URL_SUFFIX); String user = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_USER_SUFFIX); String password = getPreference(store, pluginName, ConnectionConstants.MARKETDATA_PASSWORD_SUFFIX); Map<String, Object> parameters = getParameters(factory, store, pluginName); IMarketDataFeed targetQuoteFeed = factory.getInstance(url, user, password, parameters); MarketDataFeedService marketDataFeedService = new MarketDataFeedService(targetQuoteFeed); ServiceRegistration registration = bundleContext.registerService(MarketDataFeedService.class.getName(), marketDataFeedService, null); marketDataFeedService.setServiceRegistration(registration); marketDataFeedService.afterPropertiesSet(); targetQuoteFeed.start(); succeeded = true; break; } } } } catch (Exception e) { logger.error("Exception connecting to market data feed: "+e.getMessage(), e); return Status.CANCEL_STATUS; } finally { reconnectInProgress.set(false); if (!succeeded){ logger.error("Error connecting to market data feed"); return Status.CANCEL_STATUS; } } return Status.OK_STATUS; }
diff --git a/src/com/jmex/angelfont/BitmapFontLoader.java b/src/com/jmex/angelfont/BitmapFontLoader.java index f77da740a..2fd9588ca 100644 --- a/src/com/jmex/angelfont/BitmapFontLoader.java +++ b/src/com/jmex/angelfont/BitmapFontLoader.java @@ -1,176 +1,176 @@ /* * Copyright (c) 2003-2009 jMonkeyEngine * 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 'jMonkeyEngine' 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 com.jmex.angelfont; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import com.jme.image.Texture.MagnificationFilter; import com.jme.image.Texture.MinificationFilter; import com.jme.util.TextureManager; /** * * A Loader class for {@link BitmapFont} objects. * * @author dhdd, Andreas Grabner * @author Momoko_Fan (enhancements) */ public class BitmapFontLoader { /** * * Loads the jme default {@link BitmapFont} * * @return the BitmapFont that is the jme default */ public static BitmapFont loadDefaultFont() { URL fontFile = BitmapFontLoader.class.getClassLoader().getResource("com/jmex/angelfont/angelFont.fnt"); URL textureFile = BitmapFontLoader.class.getClassLoader().getResource("com/jmex/angelfont/angelFont.png"); try { return load(fontFile, textureFile); } catch (IOException e) { return null; } // catch } // loadDefaultFont /** * * loads the {@link BitmapFont} defined by the two provided URLs * * @param fontFile the URL to the .fnt file of the {@link BitmapFont} * @param textureFile the URL to the texture file of the {@link BitmapFont} * @return the BitmapFont defined by the two provided {@link URL}s * @throws IOException if one of the provided {@link URL}s is null */ public static BitmapFont load(URL fontFile, URL textureFile) throws IOException { try { BitmapCharacterSet charSet = new BitmapCharacterSet(); BitmapFont font = new BitmapFont(); if (fontFile == null) { throw new IOException("The given URL to the requested font file is null!"); } // if - if (fontFile == null) { + if (textureFile == null) { throw new IOException("The given URL to the requested font texture file is null!"); } // if font.setFontTexture(TextureManager.loadTexture(textureFile, true)); font.getFontTexture().setMinificationFilter(MinificationFilter.Trilinear); font.getFontTexture().setMagnificationFilter(MagnificationFilter.Bilinear); BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.openStream())); String regex = "[\\s=]+"; font.setCharSet(charSet); while (reader.ready()) { String line = reader.readLine(); String[] tokens = line.split(regex); if (tokens[0].equals("info")) { // Get rendered size for (int i = 1; i < tokens.length; i++) { if (tokens[i].equals("size")) { charSet.setRenderedSize(Math.abs(Integer.parseInt(tokens[i + 1]))); } } } else if (tokens[0].equals("common")) { // Fill out BitmapCharacterSet fields for (int i = 1; i < tokens.length; i++) { String token = tokens[i]; if (token.equals("lineHeight")) { charSet.setLineHeight(Integer.parseInt(tokens[i + 1])); } else if (token.equals("base")) { charSet.setBase(Integer.parseInt(tokens[i + 1])); } else if (token.equals("scaleW")) { charSet.setWidth(Integer.parseInt(tokens[i + 1])); } else if (token.equals("scaleH")) { charSet.setHeight(Integer.parseInt(tokens[i + 1])); } // else if } } else if (tokens[0].equals("char")) { // New BitmapCharacter BitmapCharacter ch = null; for (int i = 1; i < tokens.length; i++) { String token = tokens[i]; if (token.equals("id")) { int index = Integer.parseInt(tokens[i + 1]); ch = new BitmapCharacter(); charSet.addCharacter(index, ch); } else if (token.equals("x")) { ch.setX(Integer.parseInt(tokens[i + 1])); } else if (token.equals("y")) { ch.setY(Integer.parseInt(tokens[i + 1])); } else if (token.equals("width")) { ch.setWidth(Integer.parseInt(tokens[i + 1])); } else if (token.equals("height")) { ch.setHeight(Integer.parseInt(tokens[i + 1])); } else if (token.equals("xoffset")) { ch.setXOffset(Integer.parseInt(tokens[i + 1])); } else if (token.equals("yoffset")) { ch.setYOffset(Integer.parseInt(tokens[i + 1])); } else if (token.equals("xadvance")) { ch.setXAdvance(Integer.parseInt(tokens[i + 1])); } } } else if (tokens[0].equals("kerning")) { // Build kerning list int index = 0; Kerning k = new Kerning(); for (int i = 1; i < tokens.length; i++) { if (tokens[i].equals("first")) { index = Integer.parseInt(tokens[i + 1]); } else if (tokens[i].equals("second")) { k.setSecond(Integer.parseInt(tokens[i + 1])); } else if (tokens[i].equals("amount")) { k.setAmount(Integer.parseInt(tokens[i + 1])); } } BitmapCharacter ch = charSet.getCharacter(index); ch.getKerningList().add(k); } } reader.close(); return font; } catch (Exception ex) { ex.printStackTrace(); } return null; } // load }
true
true
public static BitmapFont load(URL fontFile, URL textureFile) throws IOException { try { BitmapCharacterSet charSet = new BitmapCharacterSet(); BitmapFont font = new BitmapFont(); if (fontFile == null) { throw new IOException("The given URL to the requested font file is null!"); } // if if (fontFile == null) { throw new IOException("The given URL to the requested font texture file is null!"); } // if font.setFontTexture(TextureManager.loadTexture(textureFile, true)); font.getFontTexture().setMinificationFilter(MinificationFilter.Trilinear); font.getFontTexture().setMagnificationFilter(MagnificationFilter.Bilinear); BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.openStream())); String regex = "[\\s=]+"; font.setCharSet(charSet); while (reader.ready()) { String line = reader.readLine(); String[] tokens = line.split(regex); if (tokens[0].equals("info")) { // Get rendered size for (int i = 1; i < tokens.length; i++) { if (tokens[i].equals("size")) { charSet.setRenderedSize(Math.abs(Integer.parseInt(tokens[i + 1]))); } } } else if (tokens[0].equals("common")) { // Fill out BitmapCharacterSet fields for (int i = 1; i < tokens.length; i++) { String token = tokens[i]; if (token.equals("lineHeight")) { charSet.setLineHeight(Integer.parseInt(tokens[i + 1])); } else if (token.equals("base")) { charSet.setBase(Integer.parseInt(tokens[i + 1])); } else if (token.equals("scaleW")) { charSet.setWidth(Integer.parseInt(tokens[i + 1])); } else if (token.equals("scaleH")) { charSet.setHeight(Integer.parseInt(tokens[i + 1])); } // else if } } else if (tokens[0].equals("char")) { // New BitmapCharacter BitmapCharacter ch = null; for (int i = 1; i < tokens.length; i++) { String token = tokens[i]; if (token.equals("id")) { int index = Integer.parseInt(tokens[i + 1]); ch = new BitmapCharacter(); charSet.addCharacter(index, ch); } else if (token.equals("x")) { ch.setX(Integer.parseInt(tokens[i + 1])); } else if (token.equals("y")) { ch.setY(Integer.parseInt(tokens[i + 1])); } else if (token.equals("width")) { ch.setWidth(Integer.parseInt(tokens[i + 1])); } else if (token.equals("height")) { ch.setHeight(Integer.parseInt(tokens[i + 1])); } else if (token.equals("xoffset")) { ch.setXOffset(Integer.parseInt(tokens[i + 1])); } else if (token.equals("yoffset")) { ch.setYOffset(Integer.parseInt(tokens[i + 1])); } else if (token.equals("xadvance")) { ch.setXAdvance(Integer.parseInt(tokens[i + 1])); } } } else if (tokens[0].equals("kerning")) { // Build kerning list int index = 0; Kerning k = new Kerning(); for (int i = 1; i < tokens.length; i++) { if (tokens[i].equals("first")) { index = Integer.parseInt(tokens[i + 1]); } else if (tokens[i].equals("second")) { k.setSecond(Integer.parseInt(tokens[i + 1])); } else if (tokens[i].equals("amount")) { k.setAmount(Integer.parseInt(tokens[i + 1])); } } BitmapCharacter ch = charSet.getCharacter(index); ch.getKerningList().add(k); } } reader.close(); return font; } catch (Exception ex) { ex.printStackTrace(); } return null; } // load
public static BitmapFont load(URL fontFile, URL textureFile) throws IOException { try { BitmapCharacterSet charSet = new BitmapCharacterSet(); BitmapFont font = new BitmapFont(); if (fontFile == null) { throw new IOException("The given URL to the requested font file is null!"); } // if if (textureFile == null) { throw new IOException("The given URL to the requested font texture file is null!"); } // if font.setFontTexture(TextureManager.loadTexture(textureFile, true)); font.getFontTexture().setMinificationFilter(MinificationFilter.Trilinear); font.getFontTexture().setMagnificationFilter(MagnificationFilter.Bilinear); BufferedReader reader = new BufferedReader(new InputStreamReader(fontFile.openStream())); String regex = "[\\s=]+"; font.setCharSet(charSet); while (reader.ready()) { String line = reader.readLine(); String[] tokens = line.split(regex); if (tokens[0].equals("info")) { // Get rendered size for (int i = 1; i < tokens.length; i++) { if (tokens[i].equals("size")) { charSet.setRenderedSize(Math.abs(Integer.parseInt(tokens[i + 1]))); } } } else if (tokens[0].equals("common")) { // Fill out BitmapCharacterSet fields for (int i = 1; i < tokens.length; i++) { String token = tokens[i]; if (token.equals("lineHeight")) { charSet.setLineHeight(Integer.parseInt(tokens[i + 1])); } else if (token.equals("base")) { charSet.setBase(Integer.parseInt(tokens[i + 1])); } else if (token.equals("scaleW")) { charSet.setWidth(Integer.parseInt(tokens[i + 1])); } else if (token.equals("scaleH")) { charSet.setHeight(Integer.parseInt(tokens[i + 1])); } // else if } } else if (tokens[0].equals("char")) { // New BitmapCharacter BitmapCharacter ch = null; for (int i = 1; i < tokens.length; i++) { String token = tokens[i]; if (token.equals("id")) { int index = Integer.parseInt(tokens[i + 1]); ch = new BitmapCharacter(); charSet.addCharacter(index, ch); } else if (token.equals("x")) { ch.setX(Integer.parseInt(tokens[i + 1])); } else if (token.equals("y")) { ch.setY(Integer.parseInt(tokens[i + 1])); } else if (token.equals("width")) { ch.setWidth(Integer.parseInt(tokens[i + 1])); } else if (token.equals("height")) { ch.setHeight(Integer.parseInt(tokens[i + 1])); } else if (token.equals("xoffset")) { ch.setXOffset(Integer.parseInt(tokens[i + 1])); } else if (token.equals("yoffset")) { ch.setYOffset(Integer.parseInt(tokens[i + 1])); } else if (token.equals("xadvance")) { ch.setXAdvance(Integer.parseInt(tokens[i + 1])); } } } else if (tokens[0].equals("kerning")) { // Build kerning list int index = 0; Kerning k = new Kerning(); for (int i = 1; i < tokens.length; i++) { if (tokens[i].equals("first")) { index = Integer.parseInt(tokens[i + 1]); } else if (tokens[i].equals("second")) { k.setSecond(Integer.parseInt(tokens[i + 1])); } else if (tokens[i].equals("amount")) { k.setAmount(Integer.parseInt(tokens[i + 1])); } } BitmapCharacter ch = charSet.getCharacter(index); ch.getKerningList().add(k); } } reader.close(); return font; } catch (Exception ex) { ex.printStackTrace(); } return null; } // load
diff --git a/steps/searchandreplace/src/main/java/net/sf/okapi/steps/searchandreplace/SearchAndReplaceStep.java b/steps/searchandreplace/src/main/java/net/sf/okapi/steps/searchandreplace/SearchAndReplaceStep.java index a037a3c23..ddfc63905 100644 --- a/steps/searchandreplace/src/main/java/net/sf/okapi/steps/searchandreplace/SearchAndReplaceStep.java +++ b/steps/searchandreplace/src/main/java/net/sf/okapi/steps/searchandreplace/SearchAndReplaceStep.java @@ -1,305 +1,305 @@ /*=========================================================================== Copyright (C) 2009 by the Okapi Framework contributors ----------------------------------------------------------------------------- This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html ===========================================================================*/ package net.sf.okapi.steps.searchandreplace; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URI; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.sf.okapi.common.BOMNewlineEncodingDetector; import net.sf.okapi.common.Event; import net.sf.okapi.common.IParameters; import net.sf.okapi.common.IResource; import net.sf.okapi.common.UsingParameters; import net.sf.okapi.common.Util; import net.sf.okapi.common.exceptions.OkapiIOException; import net.sf.okapi.common.LocaleId; import net.sf.okapi.common.pipeline.BasePipelineStep; import net.sf.okapi.common.pipeline.annotations.StepParameterMapping; import net.sf.okapi.common.pipeline.annotations.StepParameterType; import net.sf.okapi.common.resource.RawDocument; import net.sf.okapi.common.resource.TextContainer; import net.sf.okapi.common.resource.TextUnit; @UsingParameters(Parameters.class) public class SearchAndReplaceStep extends BasePipelineStep { private final Logger logger = Logger.getLogger(getClass().getName()); private Parameters params; private boolean isDone; private Matcher matcher; private Pattern patterns[]; private URI outputURI; private LocaleId targetLocale; public enum ProcType { UNSPECIFIED, PLAINTEXT, FILTER; } private boolean firstEventDone = false; private ProcType procType = ProcType.UNSPECIFIED; @Override public void destroy () { // Nothing to do } public SearchAndReplaceStep() { params = new Parameters(); } @StepParameterMapping(parameterType = StepParameterType.OUTPUT_URI) public void setOutputURI (URI outputURI) { this.outputURI = outputURI; } @StepParameterMapping(parameterType = StepParameterType.TARGET_LOCALE) public void setTargetLocale (LocaleId targetLocale) { this.targetLocale = targetLocale; } public String getDescription () { return "Performs search and replace on the entire file or the text units. " + "Expects raw document or filter events. Sends back: raw document or filter events."; } public String getName () { return "Search and Replace"; } @Override public boolean isDone () { if ( procType == ProcType.UNSPECIFIED ){ return false; }else if ( procType == ProcType.PLAINTEXT ) { // Expects RawDocument return isDone; } else { return true; } } @Override public IParameters getParameters () { return params; } @Override public void setParameters (IParameters params) { this.params = (Parameters)params; } @Override protected Event handleStartBatch (Event event) { if ( params.regEx ){ int flags = 0; patterns = new Pattern[params.rules.size()]; //--initialize patterns-- if ( params.dotAll ) flags |= Pattern.DOTALL; if ( params.ignoreCase ) flags |= Pattern.CASE_INSENSITIVE; if ( params.multiLine ) flags |= Pattern.MULTILINE; for(int i=0; i<params.rules.size();i++){ String s[] = params.rules.get(i); if ( params.regEx ){ patterns[i]= Pattern.compile(s[1], flags); } } } return event; } @Override protected Event handleStartBatchItem (Event event) { isDone = false; return event; } @Override protected Event handleRawDocument (Event event) { //--first event determines processing type-- if (!firstEventDone) { procType = ProcType.PLAINTEXT; firstEventDone=true; } RawDocument rawDoc; String encoding = null; BufferedReader reader = null; BufferedWriter writer = null; String result = null; StringBuilder assembled = new StringBuilder(); try { rawDoc = (RawDocument)event.getResource(); // Detect the BOM (and the encoding) if possible BOMNewlineEncodingDetector detector = new BOMNewlineEncodingDetector(rawDoc.getStream(), rawDoc.getEncoding()); detector.detectAndRemoveBom(); encoding = detector.getEncoding(); // Create the reader from the BOM-aware stream, with the possibly new encoding reader = new BufferedReader(new InputStreamReader(detector.getInputStream(), encoding)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ assembled.append(buf, 0, numRead); } reader.close(); result = assembled.toString(); assembled = null; // Open the output File outFile; if ( isLastOutputStep() ) { outFile = new File(outputURI); Util.createDirectories(outFile.getAbsolutePath()); } else { try { outFile = File.createTempFile("okp-snr_", ".tmp"); } catch ( Throwable e ) { throw new OkapiIOException("Cannot create temporary output.", e); } outFile.deleteOnExit(); } if ( params.regEx ){ for(int i=0; i<params.rules.size();i++){ String s[] = params.rules.get(i); if ( s[0].equals("true") ) { matcher = patterns[i].matcher(result); result = matcher.replaceAll(s[2]); } } }else{ for ( String[] s : params.rules ) { if ( s[0].equals("true") ) { - result = result.replace(s[1],s[2]); + result = result.replace(s[1],s[2]); } } } writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), encoding)); Util.writeBOMIfNeeded(writer, detector.hasUtf8Bom(), encoding); writer.write(result); writer.close(); event.setResource(new RawDocument(outFile.toURI(), encoding, rawDoc.getSourceLocale(), rawDoc.getTargetLocale())); } catch ( FileNotFoundException e ) { throw new RuntimeException(e); } catch ( IOException e ) { throw new RuntimeException(e); } finally { isDone = true; try { if ( writer != null ) { writer.close(); writer = null; } if ( reader != null ) { reader.close(); reader = null; } } catch ( IOException e) { throw new RuntimeException(e); } } return event; } @Override protected Event handleTextUnit (Event event) { //--first event determines processing type-- if (!firstEventDone) { procType = ProcType.FILTER; firstEventDone=true; } TextUnit tu = (TextUnit)event.getResource(); // Skip non-translatable if ( !tu.isTranslatable() ) return event; String tmp = null; try { // Else: do the requested modifications // Make sure we have a target where to set data tu.createTarget(targetLocale, false, IResource.COPY_ALL); String result = tu.getTargetContent(targetLocale).getCodedText(); if ( params.regEx ){ for(int i=0; i<params.rules.size();i++){ String s[] = params.rules.get(i); if ( s[0].equals("true") ) { matcher = patterns[i].matcher(result); result = matcher.replaceAll(s[2]); } } } else { for ( String[] s : params.rules ) { if ( s[0].equals("true") ) { result = result.replace(s[1],s[2]); } } } TextContainer cnt = tu.getTarget(targetLocale); cnt.setCodedText(result); } catch ( Exception e ) { logger.log(Level.WARNING, String.format("Error when updating content: '%s'.", tmp), e); } return event; } }
true
true
protected Event handleRawDocument (Event event) { //--first event determines processing type-- if (!firstEventDone) { procType = ProcType.PLAINTEXT; firstEventDone=true; } RawDocument rawDoc; String encoding = null; BufferedReader reader = null; BufferedWriter writer = null; String result = null; StringBuilder assembled = new StringBuilder(); try { rawDoc = (RawDocument)event.getResource(); // Detect the BOM (and the encoding) if possible BOMNewlineEncodingDetector detector = new BOMNewlineEncodingDetector(rawDoc.getStream(), rawDoc.getEncoding()); detector.detectAndRemoveBom(); encoding = detector.getEncoding(); // Create the reader from the BOM-aware stream, with the possibly new encoding reader = new BufferedReader(new InputStreamReader(detector.getInputStream(), encoding)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ assembled.append(buf, 0, numRead); } reader.close(); result = assembled.toString(); assembled = null; // Open the output File outFile; if ( isLastOutputStep() ) { outFile = new File(outputURI); Util.createDirectories(outFile.getAbsolutePath()); } else { try { outFile = File.createTempFile("okp-snr_", ".tmp"); } catch ( Throwable e ) { throw new OkapiIOException("Cannot create temporary output.", e); } outFile.deleteOnExit(); } if ( params.regEx ){ for(int i=0; i<params.rules.size();i++){ String s[] = params.rules.get(i); if ( s[0].equals("true") ) { matcher = patterns[i].matcher(result); result = matcher.replaceAll(s[2]); } } }else{ for ( String[] s : params.rules ) { if ( s[0].equals("true") ) { result = result.replace(s[1],s[2]); } } } writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), encoding)); Util.writeBOMIfNeeded(writer, detector.hasUtf8Bom(), encoding); writer.write(result); writer.close(); event.setResource(new RawDocument(outFile.toURI(), encoding, rawDoc.getSourceLocale(), rawDoc.getTargetLocale())); } catch ( FileNotFoundException e ) { throw new RuntimeException(e); } catch ( IOException e ) { throw new RuntimeException(e); } finally { isDone = true; try { if ( writer != null ) { writer.close(); writer = null; } if ( reader != null ) { reader.close(); reader = null; } } catch ( IOException e) { throw new RuntimeException(e); } } return event; }
protected Event handleRawDocument (Event event) { //--first event determines processing type-- if (!firstEventDone) { procType = ProcType.PLAINTEXT; firstEventDone=true; } RawDocument rawDoc; String encoding = null; BufferedReader reader = null; BufferedWriter writer = null; String result = null; StringBuilder assembled = new StringBuilder(); try { rawDoc = (RawDocument)event.getResource(); // Detect the BOM (and the encoding) if possible BOMNewlineEncodingDetector detector = new BOMNewlineEncodingDetector(rawDoc.getStream(), rawDoc.getEncoding()); detector.detectAndRemoveBom(); encoding = detector.getEncoding(); // Create the reader from the BOM-aware stream, with the possibly new encoding reader = new BufferedReader(new InputStreamReader(detector.getInputStream(), encoding)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ assembled.append(buf, 0, numRead); } reader.close(); result = assembled.toString(); assembled = null; // Open the output File outFile; if ( isLastOutputStep() ) { outFile = new File(outputURI); Util.createDirectories(outFile.getAbsolutePath()); } else { try { outFile = File.createTempFile("okp-snr_", ".tmp"); } catch ( Throwable e ) { throw new OkapiIOException("Cannot create temporary output.", e); } outFile.deleteOnExit(); } if ( params.regEx ){ for(int i=0; i<params.rules.size();i++){ String s[] = params.rules.get(i); if ( s[0].equals("true") ) { matcher = patterns[i].matcher(result); result = matcher.replaceAll(s[2]); } } }else{ for ( String[] s : params.rules ) { if ( s[0].equals("true") ) { result = result.replace(s[1],s[2]); } } } writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), encoding)); Util.writeBOMIfNeeded(writer, detector.hasUtf8Bom(), encoding); writer.write(result); writer.close(); event.setResource(new RawDocument(outFile.toURI(), encoding, rawDoc.getSourceLocale(), rawDoc.getTargetLocale())); } catch ( FileNotFoundException e ) { throw new RuntimeException(e); } catch ( IOException e ) { throw new RuntimeException(e); } finally { isDone = true; try { if ( writer != null ) { writer.close(); writer = null; } if ( reader != null ) { reader.close(); reader = null; } } catch ( IOException e) { throw new RuntimeException(e); } } return event; }
diff --git a/core/src/main/java/hudson/MarkupText.java b/core/src/main/java/hudson/MarkupText.java index 478b4bb31..619e2a4a8 100644 --- a/core/src/main/java/hudson/MarkupText.java +++ b/core/src/main/java/hudson/MarkupText.java @@ -1,254 +1,259 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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 hudson; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Mutable representation of string with HTML mark up. * * <p> * This class is used to put mark up on plain text. * See <a href="https://hudson.dev.java.net/source/browse/hudson/hudson/main/core/src/test/java/hudson/MarkupTextTest.java?view=markup"> * the test code</a> for a typical usage and its result. * * @author Kohsuke Kawaguchi * @since 1.70 */ public class MarkupText extends AbstractMarkupText { private final String text; /** * Added mark up tags. */ private final List<Tag> tags = new ArrayList<Tag>(); /** * Represents one mark up inserted into text. */ private static final class Tag implements Comparable<Tag> { private final int pos; private final String markup; public Tag(int pos, String markup) { this.pos = pos; this.markup = markup; } public int compareTo(Tag that) { return this.pos-that.pos; } } /** * Represents a substring of a {@link MarkupText}. */ public final class SubText extends AbstractMarkupText { private final int start,end; private final int[] groups; public SubText(Matcher m, int textOffset) { start = m.start() + textOffset; end = m.end() + textOffset; int cnt = m.groupCount(); groups = new int[cnt*2]; for( int i=0; i<cnt; i++ ) { groups[i*2 ] = m.start(i+1) + textOffset; groups[i*2+1] = m.end(i+1) + textOffset; } } @Override public String getText() { return text.substring(start,end); } @Override public void addMarkup(int startPos, int endPos, String startTag, String endTag) { MarkupText.this.addMarkup(startPos+start, endPos+start, startTag, endTag); } /** * Surrounds this subtext with the specified start tag and the end tag. * * <p> * Start/end tag text can contain special tokens "$0", "$1", ... * and they will be replaced by their {@link #group(int) group match}. * "\$" can be used to escape characters. */ public void surroundWith(String startTag, String endTag) { addMarkup(0,length(),replace(startTag),replace(endTag)); } /** * Works like {@link #surroundWith(String, String)} except * that the token replacement is not performed on parameters. */ public void surroundWithLiteral(String startTag, String endTag) { addMarkup(0,length(),startTag,endTag); } /** * Gets the start index of the captured group within {@link MarkupText#getText()}. * * @param groupIndex * 0 means the start of the whole subtext. 1, 2, ... are * groups captured by '(...)' in the regexp. */ public int start(int groupIndex) { if(groupIndex==0) return start; return groups[groupIndex*2-2]; } /** * Gets the start index of this subtext within {@link MarkupText#getText()}. */ public int start() { return start; } /** * Gets the end index of the captured group within {@link MarkupText#getText()}. */ public int end(int groupIndex) { if(groupIndex==0) return end; return groups[groupIndex*2-1]; } /** * Gets the end index of this subtext within {@link MarkupText#getText()}. */ public int end() { return end; } /** * Gets the text that represents the captured group. */ public String group(int groupIndex) { if(start(groupIndex)==-1) return null; return text.substring(start(groupIndex),end(groupIndex)); } /** * Replaces the group tokens like "$0", "$1", and etc with their actual matches. */ public String replace(String s) { StringBuffer buf = new StringBuffer(); for( int i=0; i<s.length(); i++) { char ch = s.charAt(i); if (ch == '\\') {// escape char i++; buf.append(s.charAt(i)); } else if (ch == '$') {// replace by group i++; + ch = s.charAt(i); // get the group number - int groupId = s.charAt(i) - '0'; + int groupId = ch - '0'; + if (groupId < 0 || groupId > 9) { + buf.append('$').append(ch); + } else { + // add the group text + String group = group(groupId); + if (group != null) + buf.append(group); + } - // add the group text - String group = group(groupId); - if (group != null) - buf.append(group); } else { // other chars buf.append(ch); } } return buf.toString(); } @Override protected SubText createSubText(Matcher m) { return new SubText(m,start); } } public MarkupText(String text) { this.text = text; } @Override public String getText() { return text; } @Override public void addMarkup( int startPos, int endPos, String startTag, String endTag ) { rangeCheck(startPos); rangeCheck(endPos); if(startPos>endPos) throw new IndexOutOfBoundsException(); // when multiple tags are added to the same range, we want them to show up like // <b><i>abc</i></b>, not <b><i>abc</b></i>. Do this by inserting them to different // places. tags.add(0,new Tag(startPos, startTag)); tags.add(new Tag(endPos,endTag)); } private void rangeCheck(int pos) { if(pos<0 || pos>text.length()) throw new IndexOutOfBoundsException(); } /** * Returns the fully marked-up text. */ public String toString() { if(tags.isEmpty()) return text; // the most common case // somewhat inefficient implementation, if there are a lot of mark up and text is large. Collections.sort(tags); StringBuilder buf = new StringBuilder(); buf.append(text); int offset = 0; // remember the # of chars inserted. for (Tag tag : tags) { buf.insert(tag.pos+offset,tag.markup); offset += tag.markup.length(); } return buf.toString(); } // perhaps this method doesn't need to be here to remain binary compatible with past versions, // but having this seems to be safer. @Override public List<SubText> findTokens(Pattern pattern) { return super.findTokens(pattern); } @Override protected SubText createSubText(Matcher m) { return new SubText(m,0); } }
false
true
public String replace(String s) { StringBuffer buf = new StringBuffer(); for( int i=0; i<s.length(); i++) { char ch = s.charAt(i); if (ch == '\\') {// escape char i++; buf.append(s.charAt(i)); } else if (ch == '$') {// replace by group i++; // get the group number int groupId = s.charAt(i) - '0'; // add the group text String group = group(groupId); if (group != null) buf.append(group); } else { // other chars buf.append(ch); } } return buf.toString(); }
public String replace(String s) { StringBuffer buf = new StringBuffer(); for( int i=0; i<s.length(); i++) { char ch = s.charAt(i); if (ch == '\\') {// escape char i++; buf.append(s.charAt(i)); } else if (ch == '$') {// replace by group i++; ch = s.charAt(i); // get the group number int groupId = ch - '0'; if (groupId < 0 || groupId > 9) { buf.append('$').append(ch); } else { // add the group text String group = group(groupId); if (group != null) buf.append(group); } } else { // other chars buf.append(ch); } } return buf.toString(); }
diff --git a/src/main/java/Sirius/server/search/StaticSearchTools.java b/src/main/java/Sirius/server/search/StaticSearchTools.java index e68757be..35a503d4 100644 --- a/src/main/java/Sirius/server/search/StaticSearchTools.java +++ b/src/main/java/Sirius/server/search/StaticSearchTools.java @@ -1,65 +1,65 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * Copyright (C) 2010 thorsten * * 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 Sirius.server.search; import Sirius.server.middleware.types.MetaClass; import java.util.ArrayList; /** * DOCUMENT ME! * * @author thorsten * @version $Revision$, $Date$ */ public class StaticSearchTools { //~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @param classes DOCUMENT ME! * * @return DOCUMENT ME! * * @throws IllegalArgumentException DOCUMENT ME! */ public static String getMetaClassIdsForInStatement(final ArrayList<MetaClass> classes) throws IllegalArgumentException { String s = ""; if ((classes == null) || (classes.size() == 0)) { throw new IllegalArgumentException("ArrayList of MetaClasses must neither be null nor empty"); } final String domainCheck = classes.get(0).getDomain(); for (final MetaClass mc : classes) { s += mc.getID() + ","; if (!mc.getDomain().equals(domainCheck)) { throw new IllegalArgumentException("ArrayList of MetaClasses must be from the same domain"); } } - s = s.substring(0, s.length() - 2); + s = s.trim().substring(0, s.length() - 1); return "(" + s + ")"; } }
true
true
public static String getMetaClassIdsForInStatement(final ArrayList<MetaClass> classes) throws IllegalArgumentException { String s = ""; if ((classes == null) || (classes.size() == 0)) { throw new IllegalArgumentException("ArrayList of MetaClasses must neither be null nor empty"); } final String domainCheck = classes.get(0).getDomain(); for (final MetaClass mc : classes) { s += mc.getID() + ","; if (!mc.getDomain().equals(domainCheck)) { throw new IllegalArgumentException("ArrayList of MetaClasses must be from the same domain"); } } s = s.substring(0, s.length() - 2); return "(" + s + ")"; }
public static String getMetaClassIdsForInStatement(final ArrayList<MetaClass> classes) throws IllegalArgumentException { String s = ""; if ((classes == null) || (classes.size() == 0)) { throw new IllegalArgumentException("ArrayList of MetaClasses must neither be null nor empty"); } final String domainCheck = classes.get(0).getDomain(); for (final MetaClass mc : classes) { s += mc.getID() + ","; if (!mc.getDomain().equals(domainCheck)) { throw new IllegalArgumentException("ArrayList of MetaClasses must be from the same domain"); } } s = s.trim().substring(0, s.length() - 1); return "(" + s + ")"; }
diff --git a/src/gamepatcher/Downloader.java b/src/gamepatcher/Downloader.java index ca19fb1..1e78a5a 100644 --- a/src/gamepatcher/Downloader.java +++ b/src/gamepatcher/Downloader.java @@ -1,265 +1,265 @@ package gamepatcher; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.file.AccessDeniedException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Calendar; import java.util.Scanner; import java.util.TimeZone; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; public class Downloader extends Patcher { private String filePath; private String datePath; private String fileSite; private String dateSite; private long chunkSize; private float progress; private boolean downloaded = false; // this boolean allows you to deny new updates public Downloader(String fileName, String dateName, String fileSite, String dateSite, long chunkSize){ constructor(fileName, dateName, fileSite, dateSite); // sets chunkSize, which is the amount of data downloaded per round this.chunkSize = chunkSize; } public Downloader(String fileName, String dateName, String fileSite, String dateSite){ constructor(fileName, dateName, fileSite, dateSite); chunkSize = 1000; } public void constructor(String fileName, String dateName, String fileSite, String dateSite){ setUserDir(); filePath = System.getProperty("user.dir") + File.separatorChar + fileName; datePath = System.getProperty("user.dir") + File.separatorChar + dateName; this.fileSite = fileSite; this.dateSite = dateSite; scanAndDeleteOldFiles("tempDate", getSuffix(datePath)); scanAndDeleteOldFiles("tempFile", getSuffix(filePath)); } public boolean isUpdateNecessary(){ if(new File(filePath).exists() && new File(datePath).exists()){ // the date of update on the website copy will be compared to the local copy to see if an update should happen System.out.println("Checking date of update..."); ReadableByteChannel rbc = null; FileOutputStream fos = null; File tempDate = null; try { URL date = new URL(dateSite); URLConnection dateConnection = date.openConnection(); long size = dateConnection.getContentLength(); rbc = Channels.newChannel(date.openStream()); tempDate = File.createTempFile("tempDate", ".txt"); tempDate.deleteOnExit(); fos = new FileOutputStream(tempDate); fos.getChannel().transferFrom(rbc, 0, size); } catch (MalformedURLException e) { ErrorLogger.logError(e); return false; } catch (FileNotFoundException e) { ErrorLogger.logError(e); return false; } catch (UnknownHostException e) { System.out.println("No internet found"); return false; } catch (IOException e) { ErrorLogger.logError(e); return false; } finally { if(rbc != null) try { rbc.close(); } catch (IOException e) { ErrorLogger.logError(e); return false; } if(fos != null) try { fos.close(); } catch (IOException e) { ErrorLogger.logError(e); return false; } } Calendar timeOfUpdate = fileToCalendar(tempDate.getAbsolutePath()); Calendar timeOnFile = fileToCalendar(datePath); if(timeOnFile.compareTo(timeOfUpdate) > 0){ System.out.println("No download necessary"); return false; } else return true; } else return true; } public void autoUpdate(){ if(isUpdateNecessary()) downloadFiles(); } private Calendar fileToCalendar(String path){ // converts a file in the date format used in this program (line 1-year, line 2-month, line 3-day, line 4-hour, line 5-minute, line 6-second) Scanner scanner = null; int[] values = new int[6]; try { scanner = new Scanner(new File(path)); for(int i = 0; i < values.length; i++) values[i] = Integer.parseInt(scanner.nextLine()); } catch (FileNotFoundException e) { ErrorLogger.logError(e); return null; } finally { if(scanner != null) scanner.close(); } Calendar calendar = Calendar.getInstance(); calendar.set(values[0], values[1] - 1, values[2], values[3], values[4], values[5]); return calendar; } private String getSuffix(String fileName){ return fileName.contains(".") ? fileName.substring(fileName.lastIndexOf('.'), fileName.length()) : ""; } private void scanAndDeleteOldFiles(String name, String suffix){ // if the download is aborted, a temporary file will be left behind. this method deletes all temporary files left behind in the past DirectoryStream<Path> ds = null; try { ds = Files.newDirectoryStream(Paths.get(System.getProperty("java.io.tmpdir")), name + '*' + suffix); for(Path file : ds){ if(file.toFile().delete()) System.out.println("Old file " + file.toFile().getAbsolutePath() + " deleted successfully."); else System.out.println("Old file " + file.toFile().getAbsolutePath() + " denied being deleted. That evil file!"); } } catch (IOException e) { ErrorLogger.logError(e); return; } finally { try { ds.close(); } catch (IOException e) { ErrorLogger.logError(e); return; } } } public void downloadFiles(){ System.out.println("Download necessary"); System.out.println("Downloading..."); ReadableByteChannel rbc = null; FileOutputStream fos = null; try { // creates file in temporary directory to be downloaded to, so that the main file isn't lost if the download is aborted - File temp = File.createTempFile("tempFile", filePath.substring(filePath.lastIndexOf('.'), filePath.length())); + File temp = File.createTempFile("tempFile", getSuffix(filePath)); // the file will be deleted upon exit unless the download is aborted mid-way temp.deleteOnExit(); URL file = new URL(fileSite); URLConnection urlconnection = file.openConnection(); urlconnection.setReadTimeout(5000); long size = urlconnection.getContentLength(); rbc = Channels.newChannel(file.openStream()); fos = new FileOutputStream(temp); long position = 0; while(position < size){ position += fos.getChannel().transferFrom(rbc, position, chunkSize); // sets progress to the nearest tenth of the amount of bytes downloaded out of the total progress = Math.round((float)(100 * (float)position / (float)size) * (float)10) / (float)10; System.out.println(progress + "% done"); } File actual = new File(filePath); if(actual.exists()) if(!actual.delete()) return; Path temporary = temp.toPath(); Path desired = actual.toPath(); Files.copy(temporary, desired, REPLACE_EXISTING); } catch (AccessDeniedException e) { System.out.println("Access is denied to copy the file to the desired folder. Please change the path in gamepatchersettings.txt to a folder in which you have write access."); ErrorLogger.logError(e); return; } catch (MalformedURLException e) { ErrorLogger.logError(e); return; } catch (IOException e) { ErrorLogger.logError(e); return; } finally { if(rbc != null) try { rbc.close(); } catch (IOException e) { ErrorLogger.logError(e); return; } if(fos != null) try { fos.close(); } catch (IOException e) { ErrorLogger.logError(e); return; } } System.out.println("Success"); System.out.println("Making datestamp..."); // a datestamp of when the update took place will be made File dateFile = new File(datePath); try { dateFile.createNewFile(); } catch (IOException e) { ErrorLogger.logError(e); return; } if(dateFile.exists()){ Calendar calendar = Calendar.getInstance(); TimeZone utc = TimeZone.getTimeZone("UTC"); // all time is converted to UTC so that time zones don't screw up updating calendar.setTimeZone(utc); String[] values = new String[6]; values[0] = String.valueOf(calendar.get(Calendar.YEAR)); values[1] = String.valueOf(calendar.get(Calendar.MONTH) + 1); values[2] = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); values[3] = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)); values[4] = String.valueOf(calendar.get(Calendar.MINUTE)); values[5] = String.valueOf(calendar.get(Calendar.SECOND)); BufferedWriter bw = null; try { FileWriter dateWriter = new FileWriter(dateFile); bw = new BufferedWriter(dateWriter); for(int i = 0; i < values.length; i++){ bw.write(values[i]); bw.newLine(); } } catch (IOException e) { ErrorLogger.logError(e); return; } finally { if(bw != null) try { bw.close(); } catch (IOException e) { ErrorLogger.logError(e); } } System.out.println("Datestamp success"); downloaded = true; } } public float getProgress(){ return progress; } public boolean getDownloaded(){ return downloaded; } }
true
true
public void downloadFiles(){ System.out.println("Download necessary"); System.out.println("Downloading..."); ReadableByteChannel rbc = null; FileOutputStream fos = null; try { // creates file in temporary directory to be downloaded to, so that the main file isn't lost if the download is aborted File temp = File.createTempFile("tempFile", filePath.substring(filePath.lastIndexOf('.'), filePath.length())); // the file will be deleted upon exit unless the download is aborted mid-way temp.deleteOnExit(); URL file = new URL(fileSite); URLConnection urlconnection = file.openConnection(); urlconnection.setReadTimeout(5000); long size = urlconnection.getContentLength(); rbc = Channels.newChannel(file.openStream()); fos = new FileOutputStream(temp); long position = 0; while(position < size){ position += fos.getChannel().transferFrom(rbc, position, chunkSize); // sets progress to the nearest tenth of the amount of bytes downloaded out of the total progress = Math.round((float)(100 * (float)position / (float)size) * (float)10) / (float)10; System.out.println(progress + "% done"); } File actual = new File(filePath); if(actual.exists()) if(!actual.delete()) return; Path temporary = temp.toPath(); Path desired = actual.toPath(); Files.copy(temporary, desired, REPLACE_EXISTING); } catch (AccessDeniedException e) { System.out.println("Access is denied to copy the file to the desired folder. Please change the path in gamepatchersettings.txt to a folder in which you have write access."); ErrorLogger.logError(e); return; } catch (MalformedURLException e) { ErrorLogger.logError(e); return; } catch (IOException e) { ErrorLogger.logError(e); return; } finally { if(rbc != null) try { rbc.close(); } catch (IOException e) { ErrorLogger.logError(e); return; } if(fos != null) try { fos.close(); } catch (IOException e) { ErrorLogger.logError(e); return; } } System.out.println("Success"); System.out.println("Making datestamp..."); // a datestamp of when the update took place will be made File dateFile = new File(datePath); try { dateFile.createNewFile(); } catch (IOException e) { ErrorLogger.logError(e); return; } if(dateFile.exists()){ Calendar calendar = Calendar.getInstance(); TimeZone utc = TimeZone.getTimeZone("UTC"); // all time is converted to UTC so that time zones don't screw up updating calendar.setTimeZone(utc); String[] values = new String[6]; values[0] = String.valueOf(calendar.get(Calendar.YEAR)); values[1] = String.valueOf(calendar.get(Calendar.MONTH) + 1); values[2] = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); values[3] = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)); values[4] = String.valueOf(calendar.get(Calendar.MINUTE)); values[5] = String.valueOf(calendar.get(Calendar.SECOND)); BufferedWriter bw = null; try { FileWriter dateWriter = new FileWriter(dateFile); bw = new BufferedWriter(dateWriter); for(int i = 0; i < values.length; i++){ bw.write(values[i]); bw.newLine(); } } catch (IOException e) { ErrorLogger.logError(e); return; } finally { if(bw != null) try { bw.close(); } catch (IOException e) { ErrorLogger.logError(e); } } System.out.println("Datestamp success"); downloaded = true; } }
public void downloadFiles(){ System.out.println("Download necessary"); System.out.println("Downloading..."); ReadableByteChannel rbc = null; FileOutputStream fos = null; try { // creates file in temporary directory to be downloaded to, so that the main file isn't lost if the download is aborted File temp = File.createTempFile("tempFile", getSuffix(filePath)); // the file will be deleted upon exit unless the download is aborted mid-way temp.deleteOnExit(); URL file = new URL(fileSite); URLConnection urlconnection = file.openConnection(); urlconnection.setReadTimeout(5000); long size = urlconnection.getContentLength(); rbc = Channels.newChannel(file.openStream()); fos = new FileOutputStream(temp); long position = 0; while(position < size){ position += fos.getChannel().transferFrom(rbc, position, chunkSize); // sets progress to the nearest tenth of the amount of bytes downloaded out of the total progress = Math.round((float)(100 * (float)position / (float)size) * (float)10) / (float)10; System.out.println(progress + "% done"); } File actual = new File(filePath); if(actual.exists()) if(!actual.delete()) return; Path temporary = temp.toPath(); Path desired = actual.toPath(); Files.copy(temporary, desired, REPLACE_EXISTING); } catch (AccessDeniedException e) { System.out.println("Access is denied to copy the file to the desired folder. Please change the path in gamepatchersettings.txt to a folder in which you have write access."); ErrorLogger.logError(e); return; } catch (MalformedURLException e) { ErrorLogger.logError(e); return; } catch (IOException e) { ErrorLogger.logError(e); return; } finally { if(rbc != null) try { rbc.close(); } catch (IOException e) { ErrorLogger.logError(e); return; } if(fos != null) try { fos.close(); } catch (IOException e) { ErrorLogger.logError(e); return; } } System.out.println("Success"); System.out.println("Making datestamp..."); // a datestamp of when the update took place will be made File dateFile = new File(datePath); try { dateFile.createNewFile(); } catch (IOException e) { ErrorLogger.logError(e); return; } if(dateFile.exists()){ Calendar calendar = Calendar.getInstance(); TimeZone utc = TimeZone.getTimeZone("UTC"); // all time is converted to UTC so that time zones don't screw up updating calendar.setTimeZone(utc); String[] values = new String[6]; values[0] = String.valueOf(calendar.get(Calendar.YEAR)); values[1] = String.valueOf(calendar.get(Calendar.MONTH) + 1); values[2] = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); values[3] = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)); values[4] = String.valueOf(calendar.get(Calendar.MINUTE)); values[5] = String.valueOf(calendar.get(Calendar.SECOND)); BufferedWriter bw = null; try { FileWriter dateWriter = new FileWriter(dateFile); bw = new BufferedWriter(dateWriter); for(int i = 0; i < values.length; i++){ bw.write(values[i]); bw.newLine(); } } catch (IOException e) { ErrorLogger.logError(e); return; } finally { if(bw != null) try { bw.close(); } catch (IOException e) { ErrorLogger.logError(e); } } System.out.println("Datestamp success"); downloaded = true; } }
diff --git a/SSHD_log_vis/src/request_handlers/GetEntries.java b/SSHD_log_vis/src/request_handlers/GetEntries.java index 900f201..8ad1a90 100644 --- a/SSHD_log_vis/src/request_handlers/GetEntries.java +++ b/SSHD_log_vis/src/request_handlers/GetEntries.java @@ -1,223 +1,226 @@ package request_handlers; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import JSONtypes.Connect; import JSONtypes.Entry; import JSONtypes.Invalid; import JSONtypes.Line; import JSONtypes.Other; import data_source_interface.DataSourceException; import data_source_interface.Mysql_Datasource; import data_source_interface.LogDataSource; import enums.Status; /** * Servlet implementation class GetEntries Implements fetching of timebinned log * entries for sshd_log_vis tool. Requests must provide startTime, endTime, * maxBins and binLength. maxBins indicates the maximum number of timebins the * server should produce. where the natural number of bins * ((endTime-startTime)/binLength) would exceed maxBins, it is clamped to * maxBins for displayability reasons. */ public class GetEntries extends HttpServlet { private static final long serialVersionUID = 1L; private static final String JSONMimeType = "application/json"; private LogDataSource datasource; /** * @see HttpServlet#HttpServlet() */ public GetEntries() { super(); this.datasource = new Mysql_Datasource(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Line> lines = new ArrayList<Line>(); List<Entry> entries = new ArrayList<Entry>(); if (request.getParameter("startTime") == null || request.getParameter("endTime") == null || request.getParameter("maxBins") == null || request.getParameter("binLength") == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } try { lines = this.datasource.getEntriesFromDataSource( request.getParameter("serverName"), request.getParameter("startTime"), request.getParameter("endTime")); } catch (DataSourceException e2) { this.getServletContext().log(e2.getMessage(), e2.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (lines.isEmpty()) { response.sendError(HttpServletResponse.SC_NO_CONTENT); return; } PrintWriter w; w = response.getWriter(); long binLength; long requestLength; long bins; long maxBins; long startTime; long endTime; try { binLength = Long.parseLong(request.getParameter("binLength")); endTime = Long.parseLong(request.getParameter("endTime")); startTime = Long.parseLong(request.getParameter("startTime")); maxBins = Long.parseLong(request.getParameter("maxBins")); requestLength = endTime - startTime; } catch (NumberFormatException e1) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (requestLength < 0) { // start time must be before end time. response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } /** * compute bin widths and maximum possible bin count. if number of bins * based on request length and bin length exceeds max Bins set number of * bins to max bins, and recompute bin length based on the length of * request and maxbins */ bins = (int) (Math.ceil(requestLength / (double) binLength)); bins = (bins < maxBins) ? bins : maxBins; binLength = (bins == maxBins) ? (long) Math.ceil((requestLength/1000) //convert to seconds / bins) * 1000 //convert back from seconds : binLength; response.setContentType(GetEntries.JSONMimeType); //TODO refactor this, it's too hard to understand and maintain. Entry e = new Entry(lines.get(0).getId(), null); e.setStart(startTime); e.setEnd(startTime + binLength); - while (e.getEnd() < lines.get(0).getTime()){ + while (e.getEnd() <= lines.get(0).getTime()){ e.setStart(e.getEnd()); e.setEnd(e.getEnd() + binLength); } if (e.getStart() <= lines.get(0).getTime() && lines.get(0).getTime() < e.getEnd()) { entries.add(e); } if (lines.size() == 1){ e.setElem(lines.get(0)); } Line l; for (int i = 0; i < lines.size(); i++) { l = lines.get(i); // this element is inside the current bin if (l.getTime() < e.getEnd()) { setFlags(l, e); // we're right on the edge of a bin } /*else if (l.getTime() == e.getEnd()) { //setFlags(l, e); // if lines.size == count, this is the last iteration anyway, so don't bother setting up a new element. if (lines.size() > (i + 1) // lookahead, if the next elem exist and is in a new bin, make it. && lines.get(i + 1).getTime() > (l.getTime())) { if (e.getSubElemCount() == 1) { e.setElem(l); } e = new Entry(l.getId(), null); entries.add(e); e.setStart(l.getTime()); e.setEnd(startTime + binLength); } } */ else { // this element is past the end of the current bin // it may be more than one binLength past while (l.getTime() >= startTime + binLength) { startTime += binLength;// increment startTime in binLength increments, skipping N bins. } if (e.getSubElemCount() == 1) { e.setElem(lines.get(i-1)); //the previous element must have been it. } e = new Entry(l.getId(), null); entries.add(e); e.setStart(startTime); setFlags(l, e); e.setEnd(startTime + binLength); + if ((lines.size() == i +1 || lines.get(i+1).getTime() >= e.getEnd()) && e.getSubElemCount() == 1){ + e.setElem(l); + } } } //END REFACTOR BLOCK StringBuilder json = new StringBuilder("["); for (Entry es : entries) { json.append(es.toJSONString()); json.append(","); } json.deleteCharAt(json.length() - 1); // clunky, but should strip out trailing , json.append("]"); w.write(json.toString()); w.flush(); response.flushBuffer(); } private void setFlags(Line l, Entry e) { Connect con; Other other; e.incSubElemCount(); if (l.getClass().equals(Connect.class)) { con = (Connect) l; if (con.getStatus() == Status.ACCEPTED) { e.incAcceptedConn(); } else { e.incFailedConn(); if (con.getUser().equals("root")) { e.addFlag("R"); } } if (con.getFreqLoc() == 0) { // jdbc turns nulls to 0's e.addFlag("L"); } if (con.getFreqTime() == 0) { // jdbc turns nulls to 0's e.addFlag("T"); } } else if (l.getClass().equals(Invalid.class)) { e.incInvalid(); } else if (l.getClass().equals(Other.class)) { other = (Other) l; if (other.getMessage().toLowerCase().trim().startsWith("error")) { e.addFlag("E"); } } } }
false
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Line> lines = new ArrayList<Line>(); List<Entry> entries = new ArrayList<Entry>(); if (request.getParameter("startTime") == null || request.getParameter("endTime") == null || request.getParameter("maxBins") == null || request.getParameter("binLength") == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } try { lines = this.datasource.getEntriesFromDataSource( request.getParameter("serverName"), request.getParameter("startTime"), request.getParameter("endTime")); } catch (DataSourceException e2) { this.getServletContext().log(e2.getMessage(), e2.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (lines.isEmpty()) { response.sendError(HttpServletResponse.SC_NO_CONTENT); return; } PrintWriter w; w = response.getWriter(); long binLength; long requestLength; long bins; long maxBins; long startTime; long endTime; try { binLength = Long.parseLong(request.getParameter("binLength")); endTime = Long.parseLong(request.getParameter("endTime")); startTime = Long.parseLong(request.getParameter("startTime")); maxBins = Long.parseLong(request.getParameter("maxBins")); requestLength = endTime - startTime; } catch (NumberFormatException e1) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (requestLength < 0) { // start time must be before end time. response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } /** * compute bin widths and maximum possible bin count. if number of bins * based on request length and bin length exceeds max Bins set number of * bins to max bins, and recompute bin length based on the length of * request and maxbins */ bins = (int) (Math.ceil(requestLength / (double) binLength)); bins = (bins < maxBins) ? bins : maxBins; binLength = (bins == maxBins) ? (long) Math.ceil((requestLength/1000) //convert to seconds / bins) * 1000 //convert back from seconds : binLength; response.setContentType(GetEntries.JSONMimeType); //TODO refactor this, it's too hard to understand and maintain. Entry e = new Entry(lines.get(0).getId(), null); e.setStart(startTime); e.setEnd(startTime + binLength); while (e.getEnd() < lines.get(0).getTime()){ e.setStart(e.getEnd()); e.setEnd(e.getEnd() + binLength); } if (e.getStart() <= lines.get(0).getTime() && lines.get(0).getTime() < e.getEnd()) { entries.add(e); } if (lines.size() == 1){ e.setElem(lines.get(0)); } Line l; for (int i = 0; i < lines.size(); i++) { l = lines.get(i); // this element is inside the current bin if (l.getTime() < e.getEnd()) { setFlags(l, e); // we're right on the edge of a bin } /*else if (l.getTime() == e.getEnd()) { //setFlags(l, e); // if lines.size == count, this is the last iteration anyway, so don't bother setting up a new element. if (lines.size() > (i + 1) // lookahead, if the next elem exist and is in a new bin, make it. && lines.get(i + 1).getTime() > (l.getTime())) { if (e.getSubElemCount() == 1) { e.setElem(l); } e = new Entry(l.getId(), null); entries.add(e); e.setStart(l.getTime()); e.setEnd(startTime + binLength); } } */ else { // this element is past the end of the current bin // it may be more than one binLength past while (l.getTime() >= startTime + binLength) { startTime += binLength;// increment startTime in binLength increments, skipping N bins. } if (e.getSubElemCount() == 1) { e.setElem(lines.get(i-1)); //the previous element must have been it. } e = new Entry(l.getId(), null); entries.add(e); e.setStart(startTime); setFlags(l, e); e.setEnd(startTime + binLength); } } //END REFACTOR BLOCK StringBuilder json = new StringBuilder("["); for (Entry es : entries) { json.append(es.toJSONString()); json.append(","); } json.deleteCharAt(json.length() - 1); // clunky, but should strip out trailing , json.append("]"); w.write(json.toString()); w.flush(); response.flushBuffer(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Line> lines = new ArrayList<Line>(); List<Entry> entries = new ArrayList<Entry>(); if (request.getParameter("startTime") == null || request.getParameter("endTime") == null || request.getParameter("maxBins") == null || request.getParameter("binLength") == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } try { lines = this.datasource.getEntriesFromDataSource( request.getParameter("serverName"), request.getParameter("startTime"), request.getParameter("endTime")); } catch (DataSourceException e2) { this.getServletContext().log(e2.getMessage(), e2.getCause()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (lines.isEmpty()) { response.sendError(HttpServletResponse.SC_NO_CONTENT); return; } PrintWriter w; w = response.getWriter(); long binLength; long requestLength; long bins; long maxBins; long startTime; long endTime; try { binLength = Long.parseLong(request.getParameter("binLength")); endTime = Long.parseLong(request.getParameter("endTime")); startTime = Long.parseLong(request.getParameter("startTime")); maxBins = Long.parseLong(request.getParameter("maxBins")); requestLength = endTime - startTime; } catch (NumberFormatException e1) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (requestLength < 0) { // start time must be before end time. response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } /** * compute bin widths and maximum possible bin count. if number of bins * based on request length and bin length exceeds max Bins set number of * bins to max bins, and recompute bin length based on the length of * request and maxbins */ bins = (int) (Math.ceil(requestLength / (double) binLength)); bins = (bins < maxBins) ? bins : maxBins; binLength = (bins == maxBins) ? (long) Math.ceil((requestLength/1000) //convert to seconds / bins) * 1000 //convert back from seconds : binLength; response.setContentType(GetEntries.JSONMimeType); //TODO refactor this, it's too hard to understand and maintain. Entry e = new Entry(lines.get(0).getId(), null); e.setStart(startTime); e.setEnd(startTime + binLength); while (e.getEnd() <= lines.get(0).getTime()){ e.setStart(e.getEnd()); e.setEnd(e.getEnd() + binLength); } if (e.getStart() <= lines.get(0).getTime() && lines.get(0).getTime() < e.getEnd()) { entries.add(e); } if (lines.size() == 1){ e.setElem(lines.get(0)); } Line l; for (int i = 0; i < lines.size(); i++) { l = lines.get(i); // this element is inside the current bin if (l.getTime() < e.getEnd()) { setFlags(l, e); // we're right on the edge of a bin } /*else if (l.getTime() == e.getEnd()) { //setFlags(l, e); // if lines.size == count, this is the last iteration anyway, so don't bother setting up a new element. if (lines.size() > (i + 1) // lookahead, if the next elem exist and is in a new bin, make it. && lines.get(i + 1).getTime() > (l.getTime())) { if (e.getSubElemCount() == 1) { e.setElem(l); } e = new Entry(l.getId(), null); entries.add(e); e.setStart(l.getTime()); e.setEnd(startTime + binLength); } } */ else { // this element is past the end of the current bin // it may be more than one binLength past while (l.getTime() >= startTime + binLength) { startTime += binLength;// increment startTime in binLength increments, skipping N bins. } if (e.getSubElemCount() == 1) { e.setElem(lines.get(i-1)); //the previous element must have been it. } e = new Entry(l.getId(), null); entries.add(e); e.setStart(startTime); setFlags(l, e); e.setEnd(startTime + binLength); if ((lines.size() == i +1 || lines.get(i+1).getTime() >= e.getEnd()) && e.getSubElemCount() == 1){ e.setElem(l); } } } //END REFACTOR BLOCK StringBuilder json = new StringBuilder("["); for (Entry es : entries) { json.append(es.toJSONString()); json.append(","); } json.deleteCharAt(json.length() - 1); // clunky, but should strip out trailing , json.append("]"); w.write(json.toString()); w.flush(); response.flushBuffer(); }
diff --git a/src/org/protege/editor/owl/ui/view/OWLIndividualListViewComponent.java b/src/org/protege/editor/owl/ui/view/OWLIndividualListViewComponent.java index 6eae381a..1c0941e7 100644 --- a/src/org/protege/editor/owl/ui/view/OWLIndividualListViewComponent.java +++ b/src/org/protege/editor/owl/ui/view/OWLIndividualListViewComponent.java @@ -1,222 +1,223 @@ package org.protege.editor.owl.ui.view; import org.protege.editor.core.ui.view.DisposableAction; import org.protege.editor.owl.model.entity.OWLEntityCreationSet; import org.protege.editor.owl.ui.OWLIcons; import org.protege.editor.owl.ui.list.OWLObjectList; import org.semanticweb.owl.model.*; import org.semanticweb.owl.util.OWLEntityRemover; import org.semanticweb.owl.util.OWLEntitySetProvider; import javax.swing.*; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Matthew Horridge<br> * The University Of Manchester<br> * Bio-Health Informatics Group<br> * Date: 29-Jan-2007<br><br> * <p/> * This definitely needs a rethink - it is a totally inefficient hack! */ public class OWLIndividualListViewComponent extends AbstractOWLIndividualViewComponent implements Findable<OWLIndividual>, Deleteable, CreateNewTarget { private OWLObjectList list; private OWLOntologyChangeListener listener; private ChangeListenerMediator changeListenerMediator; public void initialiseIndividualsView() throws Exception { list = new OWLObjectList(getOWLEditorKit()); setLayout(new BorderLayout()); add(new JScrollPane(list)); list.setFixedCellHeight(20); + list.setFixedCellWidth(500); reset(); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (list.getSelectedValue() != null) { setSelectedEntity((OWLIndividual) list.getSelectedValue()); } changeListenerMediator.fireStateChanged(OWLIndividualListViewComponent.this); } } }); list.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { setSelectedEntity((OWLIndividual) list.getSelectedValue()); } }); listener = new OWLOntologyChangeListener() { public void ontologiesChanged(List<? extends OWLOntologyChange> changes) { processChanges(changes); } }; getOWLModelManager().addOntologyChangeListener(listener); addAction(new AddIndividualAction(), "A", "A"); addAction(new DeleteIndividualAction(getOWLEditorKit(), new OWLEntitySetProvider<OWLIndividual>() { public Set<OWLIndividual> getEntities() { return getSelectedIndividuals(); } }), "B", "A"); changeListenerMediator = new ChangeListenerMediator(); } private void reset() { Set<OWLIndividual> inds = new HashSet<OWLIndividual>(); for (OWLOntology ont : getOWLModelManager().getActiveOntologies()) { inds.addAll(ont.getReferencedIndividuals()); } list.setListData(inds.toArray()); } protected OWLIndividual updateView(OWLIndividual selelectedIndividual) { list.setSelectedValue(selelectedIndividual, true); return selelectedIndividual; } public void disposeView() { getOWLModelManager().removeOntologyChangeListener(listener); } public OWLIndividual getSelectedIndividual() { return (OWLIndividual) list.getSelectedValue(); } public Set<OWLIndividual> getSelectedIndividuals() { Set<OWLIndividual> inds = new HashSet<OWLIndividual>(); for (Object obj : list.getSelectedValues()) { inds.add((OWLIndividual) obj); } return inds; } private void processChanges(List<? extends OWLOntologyChange> changes) { for (OWLOntologyChange change : changes) { for (OWLEntity ent : ((OWLAxiomChange) change).getEntities()) { if (ent instanceof OWLIndividual) { reset(); break; } } } } private void addIndividual() { OWLEntityCreationSet<OWLIndividual> set = getOWLWorkspace().createOWLIndividual(); if (set == null) { return; } List<OWLOntologyChange> changes = new ArrayList<OWLOntologyChange>(); changes.addAll(set.getOntologyChanges()); getOWLModelManager().applyChanges(changes); OWLIndividual ind = set.getOWLEntity(); if (ind != null) { getOWLWorkspace().getOWLSelectionModel().setSelectedEntity(ind); } } public List<OWLIndividual> find(String match) { return getOWLModelManager().getMatchingOWLIndividuals(match); } public void show(OWLIndividual owlEntity) { list.setSelectedValue(owlEntity, true); } private class AddIndividualAction extends DisposableAction { public AddIndividualAction() { super("Add individual", OWLIcons.getIcon("individual.add.png")); } public void actionPerformed(ActionEvent e) { addIndividual(); } public void dispose() { } } public void addChangeListener(ChangeListener listener) { changeListenerMediator.addChangeListener(listener); } public void removeChangeListener(ChangeListener listener) { changeListenerMediator.removeChangeListener(listener); } public void handleDelete() { OWLEntityRemover entityRemover = new OWLEntityRemover(getOWLModelManager().getOWLOntologyManager(), getOWLModelManager().getOntologies()); for (OWLIndividual ind : getSelectedIndividuals()) { ind.accept(entityRemover); } getOWLModelManager().applyChanges(entityRemover.getChanges()); } public boolean canDelete() { return !getSelectedIndividuals().isEmpty(); } public boolean canCreateNew() { return true; } public void createNewObject() { addIndividual(); } }
true
true
public void initialiseIndividualsView() throws Exception { list = new OWLObjectList(getOWLEditorKit()); setLayout(new BorderLayout()); add(new JScrollPane(list)); list.setFixedCellHeight(20); reset(); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (list.getSelectedValue() != null) { setSelectedEntity((OWLIndividual) list.getSelectedValue()); } changeListenerMediator.fireStateChanged(OWLIndividualListViewComponent.this); } } }); list.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { setSelectedEntity((OWLIndividual) list.getSelectedValue()); } }); listener = new OWLOntologyChangeListener() { public void ontologiesChanged(List<? extends OWLOntologyChange> changes) { processChanges(changes); } }; getOWLModelManager().addOntologyChangeListener(listener); addAction(new AddIndividualAction(), "A", "A"); addAction(new DeleteIndividualAction(getOWLEditorKit(), new OWLEntitySetProvider<OWLIndividual>() { public Set<OWLIndividual> getEntities() { return getSelectedIndividuals(); } }), "B", "A"); changeListenerMediator = new ChangeListenerMediator(); }
public void initialiseIndividualsView() throws Exception { list = new OWLObjectList(getOWLEditorKit()); setLayout(new BorderLayout()); add(new JScrollPane(list)); list.setFixedCellHeight(20); list.setFixedCellWidth(500); reset(); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (list.getSelectedValue() != null) { setSelectedEntity((OWLIndividual) list.getSelectedValue()); } changeListenerMediator.fireStateChanged(OWLIndividualListViewComponent.this); } } }); list.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { setSelectedEntity((OWLIndividual) list.getSelectedValue()); } }); listener = new OWLOntologyChangeListener() { public void ontologiesChanged(List<? extends OWLOntologyChange> changes) { processChanges(changes); } }; getOWLModelManager().addOntologyChangeListener(listener); addAction(new AddIndividualAction(), "A", "A"); addAction(new DeleteIndividualAction(getOWLEditorKit(), new OWLEntitySetProvider<OWLIndividual>() { public Set<OWLIndividual> getEntities() { return getSelectedIndividuals(); } }), "B", "A"); changeListenerMediator = new ChangeListenerMediator(); }
diff --git a/server/cluster-mgmt/src/main/java/com/vmware/bdd/utils/SSHUtil.java b/server/cluster-mgmt/src/main/java/com/vmware/bdd/utils/SSHUtil.java index 4ffdec92..1eb2fff3 100644 --- a/server/cluster-mgmt/src/main/java/com/vmware/bdd/utils/SSHUtil.java +++ b/server/cluster-mgmt/src/main/java/com/vmware/bdd/utils/SSHUtil.java @@ -1,112 +1,111 @@ package com.vmware.bdd.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import org.apache.log4j.Logger; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class SSHUtil { private JSch jsch; private Session session; private final Logger logger = Logger.getLogger(SSHUtil.class); private void connect(String user, String privateKeyFile, String hostIP, int sshPort) { jsch = new JSch(); try { session = jsch.getSession(user, hostIP, sshPort); jsch.addIdentity(privateKeyFile); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setTimeout(Constants.SSH_SESSION_TIMEOUT); session.connect(); logger.debug("SSH session is connected!"); } catch (JSchException e) { e.printStackTrace(); } } public boolean execCmd(String user, String privateKeyFile, String hostIP, int sshPort, String command, InputStream in, OutputStream out) { AuAssert.check(command != null); connect(user, privateKeyFile, hostIP, sshPort); ChannelExec channel = null; - BufferedReader in = null; logger.info("going to exec command"); BufferedReader bufferedReader = null; try { channel = (ChannelExec) session.openChannel("exec"); if (channel != null) { logger.debug("SSH channel is opened!"); channel.setPty(true); // to enable sudo channel.setCommand(command); channel.setInputStream(in); channel.setOutputStream(out); bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream())); channel.connect(); if (!channel.isConnected()) { logger.error("Cannot setup SSH channel connection."); } StringBuilder buff = new StringBuilder(); while (true) { String line = bufferedReader.readLine(); buff.append(line); if (channel.isClosed()) { int exitStatus = channel.getExitStatus(); logger.debug("Exit status from exec is: " + exitStatus); logger.debug("command result: " + buff.toString()); if (exitStatus == 0) { return true; } return false; } //to avoid CPU busy try { Thread.sleep(200); } catch (InterruptedException e) { } } } else { logger.error("Cannot open SSH channel to " + hostIP + "."); return false; } } catch (IOException e) { e.printStackTrace(); } catch (JSchException e) { e.printStackTrace(); } finally { if (channel != null && channel.isConnected()) { channel.disconnect(); } if (session != null && channel.isConnected()) { session.disconnect(); } try { bufferedReader.close(); } catch (IOException e) { logger.error("bufferedReader close failed: " + e.getMessage()); } } return false; } }
true
true
public boolean execCmd(String user, String privateKeyFile, String hostIP, int sshPort, String command, InputStream in, OutputStream out) { AuAssert.check(command != null); connect(user, privateKeyFile, hostIP, sshPort); ChannelExec channel = null; BufferedReader in = null; logger.info("going to exec command"); BufferedReader bufferedReader = null; try { channel = (ChannelExec) session.openChannel("exec"); if (channel != null) { logger.debug("SSH channel is opened!"); channel.setPty(true); // to enable sudo channel.setCommand(command); channel.setInputStream(in); channel.setOutputStream(out); bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream())); channel.connect(); if (!channel.isConnected()) { logger.error("Cannot setup SSH channel connection."); } StringBuilder buff = new StringBuilder(); while (true) { String line = bufferedReader.readLine(); buff.append(line); if (channel.isClosed()) { int exitStatus = channel.getExitStatus(); logger.debug("Exit status from exec is: " + exitStatus); logger.debug("command result: " + buff.toString()); if (exitStatus == 0) { return true; } return false; } //to avoid CPU busy try { Thread.sleep(200); } catch (InterruptedException e) { } } } else { logger.error("Cannot open SSH channel to " + hostIP + "."); return false; } } catch (IOException e) { e.printStackTrace(); } catch (JSchException e) { e.printStackTrace(); } finally { if (channel != null && channel.isConnected()) { channel.disconnect(); } if (session != null && channel.isConnected()) { session.disconnect(); } try { bufferedReader.close(); } catch (IOException e) { logger.error("bufferedReader close failed: " + e.getMessage()); } } return false; }
public boolean execCmd(String user, String privateKeyFile, String hostIP, int sshPort, String command, InputStream in, OutputStream out) { AuAssert.check(command != null); connect(user, privateKeyFile, hostIP, sshPort); ChannelExec channel = null; logger.info("going to exec command"); BufferedReader bufferedReader = null; try { channel = (ChannelExec) session.openChannel("exec"); if (channel != null) { logger.debug("SSH channel is opened!"); channel.setPty(true); // to enable sudo channel.setCommand(command); channel.setInputStream(in); channel.setOutputStream(out); bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream())); channel.connect(); if (!channel.isConnected()) { logger.error("Cannot setup SSH channel connection."); } StringBuilder buff = new StringBuilder(); while (true) { String line = bufferedReader.readLine(); buff.append(line); if (channel.isClosed()) { int exitStatus = channel.getExitStatus(); logger.debug("Exit status from exec is: " + exitStatus); logger.debug("command result: " + buff.toString()); if (exitStatus == 0) { return true; } return false; } //to avoid CPU busy try { Thread.sleep(200); } catch (InterruptedException e) { } } } else { logger.error("Cannot open SSH channel to " + hostIP + "."); return false; } } catch (IOException e) { e.printStackTrace(); } catch (JSchException e) { e.printStackTrace(); } finally { if (channel != null && channel.isConnected()) { channel.disconnect(); } if (session != null && channel.isConnected()) { session.disconnect(); } try { bufferedReader.close(); } catch (IOException e) { logger.error("bufferedReader close failed: " + e.getMessage()); } } return false; }
diff --git a/SecondOpinionProject/src/main/java/com/secondopinion/common/service/PatientService.java b/SecondOpinionProject/src/main/java/com/secondopinion/common/service/PatientService.java index e72e22d..18dc4b2 100644 --- a/SecondOpinionProject/src/main/java/com/secondopinion/common/service/PatientService.java +++ b/SecondOpinionProject/src/main/java/com/secondopinion/common/service/PatientService.java @@ -1,104 +1,105 @@ package com.secondopinion.common.service; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.secondopinion.common.dao.PatientDao; import com.secondopinion.common.dao.UserDao; import com.secondopinion.common.model.FileUpload; import com.secondopinion.common.model.Patient; import com.secondopinion.common.model.PatientFile; import com.secondopinion.common.model.PatientMedication; import com.secondopinion.common.model.User; @Component public class PatientService { private static final String BUCKET_NAME = "secondopinion"; private static final int KEY_LENGTH = 10; @Autowired private PatientDao patientDao; @Autowired private UserDao userDao; public void createPatient(User user, Patient patient) { patientDao.insert(user, patient); } public Patient findPatient(User user) { return patientDao.findByUserId(user.getUserId()); } public Patient findPatient(int patientId) { return patientDao.findByPatientId(patientId); } public Patient getCurrentPatient() { org.springframework.security.core.userdetails.User loggedInUser = (org.springframework.security.core.userdetails.User) SecurityContextHolder .getContext().getAuthentication().getPrincipal(); String name = loggedInUser.getUsername(); User user = userDao.findByUserName(name); return findPatient(user); } public void updatePatient(Patient patient) { patientDao.updatePatient(patient); } public List<PatientMedication> getPatientMedations(Patient patient) { return patientDao.fetchPatientMedications(patient.getPatientId()); } public void addPatientMedation(Patient patient, PatientMedication patientMedication) { patientDao.insertPatientMedication(patient, patientMedication); } public void addPatientFile(Patient patient, FileUpload fileUpload) throws IOException { String keyName = "patient-documents/" + RandomStringUtils.randomAlphanumeric(KEY_LENGTH); + keyName += "/" + fileUpload.fileName; AWSCredentials credentials = new PropertiesCredentials( PatientService.class .getResourceAsStream("/AwsCredentials.properties")); System.out.println(credentials); AmazonS3 s3client = new AmazonS3Client(credentials); try { if (fileUpload.file.getSize() > 0) { InputStream in = fileUpload.file.getInputStream(); Long contentLength = Long.valueOf(fileUpload.file.getSize()); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(contentLength); s3client.putObject(new PutObjectRequest(BUCKET_NAME, keyName, in, metadata)); System.out.println("File Uploaded to S3"); String url = "https://s3-us-west-2.amazonaws.com/secondopinion/patient-documents/" + keyName + "/" + fileUpload.fileName; PatientFile patientFile = new PatientFile( patient.getPatientId(), fileUpload.fileName, fileUpload.fileDescription, url); patientDao.insertPatientFile(patient, patientFile); } } catch (Exception e) { System.err.println("S3 Upload Error" + e.getMessage()); } } public void removePatientMedication(int medicationId) { patientDao.deletePatientMedication(medicationId); } }
true
true
public void addPatientFile(Patient patient, FileUpload fileUpload) throws IOException { String keyName = "patient-documents/" + RandomStringUtils.randomAlphanumeric(KEY_LENGTH); AWSCredentials credentials = new PropertiesCredentials( PatientService.class .getResourceAsStream("/AwsCredentials.properties")); System.out.println(credentials); AmazonS3 s3client = new AmazonS3Client(credentials); try { if (fileUpload.file.getSize() > 0) { InputStream in = fileUpload.file.getInputStream(); Long contentLength = Long.valueOf(fileUpload.file.getSize()); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(contentLength); s3client.putObject(new PutObjectRequest(BUCKET_NAME, keyName, in, metadata)); System.out.println("File Uploaded to S3"); String url = "https://s3-us-west-2.amazonaws.com/secondopinion/patient-documents/" + keyName + "/" + fileUpload.fileName; PatientFile patientFile = new PatientFile( patient.getPatientId(), fileUpload.fileName, fileUpload.fileDescription, url); patientDao.insertPatientFile(patient, patientFile); } } catch (Exception e) { System.err.println("S3 Upload Error" + e.getMessage()); } }
public void addPatientFile(Patient patient, FileUpload fileUpload) throws IOException { String keyName = "patient-documents/" + RandomStringUtils.randomAlphanumeric(KEY_LENGTH); keyName += "/" + fileUpload.fileName; AWSCredentials credentials = new PropertiesCredentials( PatientService.class .getResourceAsStream("/AwsCredentials.properties")); System.out.println(credentials); AmazonS3 s3client = new AmazonS3Client(credentials); try { if (fileUpload.file.getSize() > 0) { InputStream in = fileUpload.file.getInputStream(); Long contentLength = Long.valueOf(fileUpload.file.getSize()); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(contentLength); s3client.putObject(new PutObjectRequest(BUCKET_NAME, keyName, in, metadata)); System.out.println("File Uploaded to S3"); String url = "https://s3-us-west-2.amazonaws.com/secondopinion/patient-documents/" + keyName + "/" + fileUpload.fileName; PatientFile patientFile = new PatientFile( patient.getPatientId(), fileUpload.fileName, fileUpload.fileDescription, url); patientDao.insertPatientFile(patient, patientFile); } } catch (Exception e) { System.err.println("S3 Upload Error" + e.getMessage()); } }
diff --git a/src/main/java/org/jboss/aerogear/unifiedpush/SenderClient.java b/src/main/java/org/jboss/aerogear/unifiedpush/SenderClient.java index 3a6321c..568a1d9 100644 --- a/src/main/java/org/jboss/aerogear/unifiedpush/SenderClient.java +++ b/src/main/java/org/jboss/aerogear/unifiedpush/SenderClient.java @@ -1,222 +1,222 @@ /** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aerogear.unifiedpush; import net.iharder.Base64; import org.codehaus.jackson.map.ObjectMapper; import org.jboss.aerogear.unifiedpush.message.UnifiedMessage; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Logger; public class SenderClient implements JavaSender { private static final Logger logger = Logger.getLogger(SenderClient.class.getName()); private static final Charset UTF_8 = Charset.forName("UTF-8"); private String serverURL; public SenderClient(String rootServerURL) { if (rootServerURL == null) { throw new IllegalStateException("server can not be null"); } this.setServerURL(rootServerURL); } public SenderClient() { } /** * Construct the URL fired against the Unified Push Server * * @param type a String defining the sending method, could be "broadcast" or "selected" * @return a StringBuilder containing the constructed URL */ protected StringBuilder buildUrl(String type) { if (serverURL == null) { throw new IllegalStateException("server can not be null"); } // build the broadcast URL: StringBuilder sb = new StringBuilder(); sb.append(serverURL) .append("rest/sender/") .append(type); return sb; } @Override public void broadcast(UnifiedMessage unifiedMessage) { StringBuilder sb = buildUrl("broadcast"); // transform JSON: String payload = transformJSON(unifiedMessage.getAttributes()); // fire! submitPayload(sb.toString(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret()); } @Override public void sendTo(UnifiedMessage unifiedMessage) { StringBuilder sb = buildUrl("selected"); // build the URL: final Map<String, Object> selectedPayloadObject = new LinkedHashMap<String, Object>(); // add the "clientIdentifiers" to the "alias" field if (unifiedMessage.getAliases() != null && !unifiedMessage.getAliases().isEmpty()) { selectedPayloadObject.put("alias", unifiedMessage.getAliases()); } if(unifiedMessage.getCategory() != null) { - selectedPayloadObject.put("category", unifiedMessage.getAliases()); + selectedPayloadObject.put("category", unifiedMessage.getCategory()); } if(unifiedMessage.getDeviceType() != null && !unifiedMessage.getDeviceType().isEmpty()) { selectedPayloadObject.put("deviceType", unifiedMessage.getDeviceType()); } if(unifiedMessage.getVariants() != null && !unifiedMessage.getVariants().isEmpty()) { selectedPayloadObject.put("variants", unifiedMessage.getVariants()); } if(unifiedMessage.getSimplePushMap()!= null && !unifiedMessage.getSimplePushMap().isEmpty()) { selectedPayloadObject.put("simple-push", unifiedMessage.getSimplePushMap()); } selectedPayloadObject.put("message", unifiedMessage.getAttributes()); // transform to JSONString: String payload = transformJSON(selectedPayloadObject); // fire! submitPayload(sb.toString(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret()); } private void submitPayload(String url, String jsonPayloadObject, String pushApplicationId, String masterSecret) { String credentials = pushApplicationId + ":" + masterSecret; HttpURLConnection httpURLConnection = null; try { String encoded = Base64.encodeBytes(credentials.getBytes(UTF_8)); // POST the payload to the UnifiedPush Server httpURLConnection = post(url, encoded, jsonPayloadObject); int statusCode = httpURLConnection.getResponseCode(); logger.info(String.format("HTTP Response code form UnifiedPush Server: %s", statusCode)); // if we got a redirect, let's extract the 'Location' header from the response // and submit the payload again if (isRedirect(statusCode)) { String redirectURL = httpURLConnection.getHeaderField("Location"); logger.info(String.format("Performing redirect to '%s'", redirectURL)); // execute the 'redirect' this.submitPayload(redirectURL, jsonPayloadObject, pushApplicationId, masterSecret); } } catch (MalformedURLException e) { logger.severe("Invalid Server URL"); } catch (IOException e) { logger.severe("IO Exception"); } finally { // tear down if (httpURLConnection != null) { httpURLConnection.disconnect(); } } } /** * Returns HttpURLConnection that 'posts' the given JSON to the given UnifiedPush Server URL. */ private HttpURLConnection post(String url, String encodedCredentials, String jsonPayloadObject) throws IOException { if (url == null || encodedCredentials == null || jsonPayloadObject == null) { throw new IllegalArgumentException("arguments cannot be null"); } byte[] bytes = jsonPayloadObject.getBytes(UTF_8); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestProperty("Authorization", "Basic " + encodedCredentials); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestMethod("POST"); OutputStream out = null; try { out = conn.getOutputStream(); out.write(bytes); } finally { // in case something blows up, while writing // the payload, we wanna close the stream: if (out != null) { out.close(); } } return conn; } /** * Convenience method to open/establish a HttpURLConnection. */ private HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * checks if the given status code is a redirect (301, 302 or 303 response status code) */ private boolean isRedirect(int statusCode) { if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { return true; } return false; } private String transformJSON(Object value) { ObjectMapper om = new ObjectMapper(); String stringPayload = null; try { stringPayload = om.writeValueAsString(value); } catch (Exception e) { throw new IllegalStateException("Failed to encode JSON payload"); } return stringPayload; } public String getServerURL() { return serverURL; } public void setServerURL(String serverURL) { if (!serverURL.endsWith("/")) { serverURL = serverURL.concat("/"); } this.serverURL = serverURL; } }
true
true
public void sendTo(UnifiedMessage unifiedMessage) { StringBuilder sb = buildUrl("selected"); // build the URL: final Map<String, Object> selectedPayloadObject = new LinkedHashMap<String, Object>(); // add the "clientIdentifiers" to the "alias" field if (unifiedMessage.getAliases() != null && !unifiedMessage.getAliases().isEmpty()) { selectedPayloadObject.put("alias", unifiedMessage.getAliases()); } if(unifiedMessage.getCategory() != null) { selectedPayloadObject.put("category", unifiedMessage.getAliases()); } if(unifiedMessage.getDeviceType() != null && !unifiedMessage.getDeviceType().isEmpty()) { selectedPayloadObject.put("deviceType", unifiedMessage.getDeviceType()); } if(unifiedMessage.getVariants() != null && !unifiedMessage.getVariants().isEmpty()) { selectedPayloadObject.put("variants", unifiedMessage.getVariants()); } if(unifiedMessage.getSimplePushMap()!= null && !unifiedMessage.getSimplePushMap().isEmpty()) { selectedPayloadObject.put("simple-push", unifiedMessage.getSimplePushMap()); } selectedPayloadObject.put("message", unifiedMessage.getAttributes()); // transform to JSONString: String payload = transformJSON(selectedPayloadObject); // fire! submitPayload(sb.toString(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret()); }
public void sendTo(UnifiedMessage unifiedMessage) { StringBuilder sb = buildUrl("selected"); // build the URL: final Map<String, Object> selectedPayloadObject = new LinkedHashMap<String, Object>(); // add the "clientIdentifiers" to the "alias" field if (unifiedMessage.getAliases() != null && !unifiedMessage.getAliases().isEmpty()) { selectedPayloadObject.put("alias", unifiedMessage.getAliases()); } if(unifiedMessage.getCategory() != null) { selectedPayloadObject.put("category", unifiedMessage.getCategory()); } if(unifiedMessage.getDeviceType() != null && !unifiedMessage.getDeviceType().isEmpty()) { selectedPayloadObject.put("deviceType", unifiedMessage.getDeviceType()); } if(unifiedMessage.getVariants() != null && !unifiedMessage.getVariants().isEmpty()) { selectedPayloadObject.put("variants", unifiedMessage.getVariants()); } if(unifiedMessage.getSimplePushMap()!= null && !unifiedMessage.getSimplePushMap().isEmpty()) { selectedPayloadObject.put("simple-push", unifiedMessage.getSimplePushMap()); } selectedPayloadObject.put("message", unifiedMessage.getAttributes()); // transform to JSONString: String payload = transformJSON(selectedPayloadObject); // fire! submitPayload(sb.toString(), payload, unifiedMessage.getPushApplicationId(), unifiedMessage.getMasterSecret()); }
diff --git a/project-set/components/header-translation/src/main/java/com/rackspace/papi/components/header/translation/HeaderTranslationFilter.java b/project-set/components/header-translation/src/main/java/com/rackspace/papi/components/header/translation/HeaderTranslationFilter.java index cbba960d9e..eebe3681fc 100644 --- a/project-set/components/header-translation/src/main/java/com/rackspace/papi/components/header/translation/HeaderTranslationFilter.java +++ b/project-set/components/header-translation/src/main/java/com/rackspace/papi/components/header/translation/HeaderTranslationFilter.java @@ -1,51 +1,51 @@ package com.rackspace.papi.components.header.translation; import com.rackspace.papi.components.header.translation.config.Header; import com.rackspace.papi.filter.FilterConfigHelper; import com.rackspace.papi.filter.logic.impl.FilterLogicHandlerDelegate; import com.rackspace.papi.service.config.ConfigurationService; import com.rackspace.papi.service.context.ServletContextHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; import java.net.URL; public class HeaderTranslationFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(HeaderTranslationFilter.class); private static final String DEFAULT_CONFIG = "header-translation.cfg.xml"; private String config; private HeaderTranslationHandlerFactory headerTranslationHandlerFactory; private ConfigurationService configurationService; @Override public void init(FilterConfig filterConfig) throws ServletException { config = new FilterConfigHelper(filterConfig).getFilterConfig(DEFAULT_CONFIG); LOG.info("Initializing filter using config " + config); configurationService = ServletContextHelper.getInstance(filterConfig.getServletContext()).getPowerApiContext().configurationService(); headerTranslationHandlerFactory = new HeaderTranslationHandlerFactory(); - URL xsdURL = getClass().getResource("/META-INF/schema/config/header-identity-configuration.xsd"); + URL xsdURL = getClass().getResource("/META-INF/schema/config/header-translation.xsd"); configurationService.subscribeTo(filterConfig.getFilterName(), config, xsdURL, headerTranslationHandlerFactory, Header.class); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { new FilterLogicHandlerDelegate(servletRequest, servletResponse, filterChain).doFilter( headerTranslationHandlerFactory.newHandler()); } @Override public void destroy() { configurationService.unsubscribeFrom(config, headerTranslationHandlerFactory); } }
true
true
public void init(FilterConfig filterConfig) throws ServletException { config = new FilterConfigHelper(filterConfig).getFilterConfig(DEFAULT_CONFIG); LOG.info("Initializing filter using config " + config); configurationService = ServletContextHelper.getInstance(filterConfig.getServletContext()).getPowerApiContext().configurationService(); headerTranslationHandlerFactory = new HeaderTranslationHandlerFactory(); URL xsdURL = getClass().getResource("/META-INF/schema/config/header-identity-configuration.xsd"); configurationService.subscribeTo(filterConfig.getFilterName(), config, xsdURL, headerTranslationHandlerFactory, Header.class); }
public void init(FilterConfig filterConfig) throws ServletException { config = new FilterConfigHelper(filterConfig).getFilterConfig(DEFAULT_CONFIG); LOG.info("Initializing filter using config " + config); configurationService = ServletContextHelper.getInstance(filterConfig.getServletContext()).getPowerApiContext().configurationService(); headerTranslationHandlerFactory = new HeaderTranslationHandlerFactory(); URL xsdURL = getClass().getResource("/META-INF/schema/config/header-translation.xsd"); configurationService.subscribeTo(filterConfig.getFilterName(), config, xsdURL, headerTranslationHandlerFactory, Header.class); }
diff --git a/core/src/visad/trunk/collab/DisplaySyncImpl.java b/core/src/visad/trunk/collab/DisplaySyncImpl.java index dc4501585..0631a67b2 100644 --- a/core/src/visad/trunk/collab/DisplaySyncImpl.java +++ b/core/src/visad/trunk/collab/DisplaySyncImpl.java @@ -1,363 +1,367 @@ /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 2000 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library 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 visad.collab; import java.rmi.RemoteException; import java.util.Iterator; import java.util.ListIterator; import java.util.Vector; import visad.ConstantMap; import visad.Control; import visad.DataRenderer; import visad.DisplayImpl; import visad.RemoteDataReference; import visad.RemoteDisplayImpl; import visad.RemoteReferenceLink; import visad.RemoteVisADException; import visad.ScalarMap; import visad.VisADException; public class DisplaySyncImpl extends EventListener implements DisplaySync { private DisplayMonitor monitor; private DisplayImpl myDisplay; private Object mapClearSync = new Object(); private int mapClearCount = 0; public DisplaySyncImpl(DisplayImpl dpy) throws RemoteException { super(dpy.getName() + ":Sync"); myDisplay = dpy; monitor = dpy.getDisplayMonitor(); monitor.setDisplaySync(this); } /** * Adds the specified data reference to this <TT>Display</TT>. * * @param link The link to the remote data reference. * * @exception VisADException If a link could not be made for the * remote data reference. */ private void addLink(RemoteReferenceLink link) throws VisADException { // build array of ConstantMap values ConstantMap[] cm = null; try { Vector v = link.getConstantMapVector(); int len = v.size(); if (len > 0) { cm = new ConstantMap[len]; for (int i = 0; i < len; i++) { ConstantMap tmp = (ConstantMap )v.elementAt(i); cm[i] = (ConstantMap )tmp.clone(); } } } catch (Exception e) { throw new VisADException("Couldn't copy ConstantMaps" + " for remote DataReference"); } // get reference to Data object RemoteDataReference ref; try { ref = link.getReference(); } catch (Exception e) { throw new VisADException("Couldn't copy remote DataReference"); } if (ref != null) { DataRenderer dr = myDisplay.getDisplayRenderer().makeDefaultRenderer(); String defaultClass = dr.getClass().getName(); // get proper DataRenderer DataRenderer renderer; try { String newClass = link.getRendererClassName(); if (newClass == defaultClass) { renderer = null; } else { Object obj = Class.forName(newClass).newInstance(); renderer = (DataRenderer )obj; } } catch (Exception e) { throw new VisADException("Couldn't copy remote DataRenderer " + "name; using " + defaultClass); } // build RemoteDisplayImpl to which reference is attached try { RemoteDisplayImpl rd = new RemoteDisplayImpl(myDisplay); // if this reference uses the default renderer... if (renderer == null) { rd.addReference(ref, cm); } else { rd.addReferences(renderer, ref, cm); } } catch (Exception e) { e.printStackTrace(); throw new VisADException("Couldn't add remote DataReference " + ref + ": " + e.getClass().getName() + ": " + e.getMessage()); } } } /** * Finds the first map associated with this <TT>Display</TT> * which matches the specified <TT>ScalarMap</TT>. * * @param map The <TT>ScalarMap</TT> to find. */ private ScalarMap findMap(ScalarMap map) { ScalarMap found = null; boolean isConstMap; Vector v; if (map instanceof ConstantMap) { v = myDisplay.getConstantMapVector(); isConstMap = true; } else { v = myDisplay.getMapVector(); isConstMap = false; } ListIterator iter = v.listIterator(); while (iter.hasNext()) { ScalarMap sm = (ScalarMap )iter.next(); if (sm.equals(map)) { found = sm; break; } } return found; } /** * Attempt to deliver the queued events. * * @exception RemoteException If a connection could not be made to the * remote listener. */ void deliverEventTable(EventTable tbl) throws RemoteException { MonitorEventTable mTable = (MonitorEventTable )tbl; // deliver events Iterator iter = mTable.keyIterator(); while (iter.hasNext()) { Object key = iter.next(); MonitorEvent evt = (MonitorEvent )mTable.remove(key); if (evt == null) { System.err.println("Skipping null event for key " + key); continue; } try { deliverOneEvent(evt); } catch (RemoteException re) { // restore failed event to table mTable.restore(key, evt); // let caller handle RemoteExceptions throw re; } catch (Throwable t) { // whine loudly about all other Exceptions t.printStackTrace(); } } } private void deliverOneEvent(MonitorEvent evt) throws RemoteException, RemoteVisADException { Control lclCtl, rmtCtl; ScalarMap lclMap, rmtMap; switch (evt.getType()) { case MonitorEvent.MAP_ADDED: rmtMap = ((MapMonitorEvent )evt).getMap(); // if we haven't already added this map... if (findMap(rmtMap) == null) { if (!myDisplay.getRendererVector().isEmpty()) { System.err.println("Late addMap: " + rmtMap); } else { // forward to any listeners monitor.notifyListeners(evt); try { myDisplay.addMap(rmtMap); } catch (VisADException ve) { ve.printStackTrace(); throw new RemoteVisADException("Map " + rmtMap + " not added: " + ve); } } } break; case MonitorEvent.MAP_CHANGED: // forward to any listeners monitor.notifyListeners(evt); rmtMap = ((MapMonitorEvent )evt).getMap(); lclMap = findMap(rmtMap); if (lclMap == null) { throw new RemoteVisADException("ScalarMap " + rmtMap + " not found"); } + // CTR 2 June 2000 - do not set map range if already set (avoid loops) double[] rng = rmtMap.getRange(); - try { - lclMap.setRange(rng[0], rng[1]); - } catch (VisADException ve) { - throw new RemoteVisADException("Map not changed: " + ve); + double[] lclRng = lclMap.getRange(); + if (rng[0] != lclRng[0] || rng[1] != lclRng[1]) { + try { + lclMap.setRange(rng[0], rng[1]); + } catch (VisADException ve) { + throw new RemoteVisADException("Map not changed: " + ve); + } } break; case MonitorEvent.MAPS_CLEARED: // forward to any listeners monitor.notifyListeners(evt); try { myDisplay.removeAllReferences(); myDisplay.clearMaps(); } catch (VisADException ve) { throw new RemoteVisADException("Maps not cleared: " + ve); } catch (NullPointerException npe) { npe.printStackTrace(); throw new RemoteVisADException("Maps not cleared"); } break; case MonitorEvent.REFERENCE_ADDED: // forward to any listeners monitor.notifyListeners(evt); RemoteReferenceLink ref = ((ReferenceMonitorEvent )evt).getLink(); try { addLink(ref); } catch (VisADException ve) { throw new RemoteVisADException("DataReference " + ref + " not found by " + Name + ": " + ve.getMessage()); } break; case MonitorEvent.CONTROL_INIT_REQUESTED: // !!! DON'T FORWARD INIT EVENTS TO LISTENERS !!! rmtCtl = ((ControlMonitorEvent )evt).getControl(); lclCtl = myDisplay.getControl(rmtCtl.getClass(), rmtCtl.getInstanceNumber()); if (lclCtl == null) { // didn't find control ... maybe it doesn't exist yet? break; } try { ControlMonitorEvent cme; cme = new ControlMonitorEvent(MonitorEvent.CONTROL_CHANGED, (Control )lclCtl.clone()); monitor.notifyListeners(cme); } catch (VisADException ve) { throw new RemoteVisADException("Control " + rmtCtl + " not changed by " + Name + ": " + ve); } break; case MonitorEvent.CONTROL_CHANGED: rmtCtl = ((ControlMonitorEvent )evt).getControl(); lclCtl = myDisplay.getControl(rmtCtl.getClass(), rmtCtl.getInstanceNumber()); // skip this if we have change events to deliver for this control if (!monitor.hasEventQueued(evt.getOriginator(), lclCtl)) { if (lclCtl != null) { try { lclCtl.syncControl(rmtCtl); } catch (VisADException ve) { throw new RemoteVisADException("Control " + lclCtl + " not changed by " + Name + ": " + ve.getMessage()); } // forward to any listeners monitor.notifyListeners(evt); } } break; default: throw new RemoteVisADException("Event " + evt + " not handled"); } } EventTable getNewEventTable() { return new MonitorEventTable(Name); } public boolean isLocalClear() { boolean result = true; synchronized (mapClearSync) { if (mapClearCount > 0) { mapClearCount--; result = false; } } return result; } public void stateChanged(MonitorEvent evt) throws RemoteException, RemoteVisADException { switch (evt.getType()) { case MonitorEvent.MAPS_CLEARED: synchronized (mapClearSync) { mapClearCount++; } break; case MonitorEvent.CONTROL_CHANGED: if (monitor.hasEventQueued(evt.getOriginator(), ((ControlMonitorEvent )evt).getControl())) { // drop this event since we're about to override it return; } break; } addEvent(evt); } }
false
true
private void deliverOneEvent(MonitorEvent evt) throws RemoteException, RemoteVisADException { Control lclCtl, rmtCtl; ScalarMap lclMap, rmtMap; switch (evt.getType()) { case MonitorEvent.MAP_ADDED: rmtMap = ((MapMonitorEvent )evt).getMap(); // if we haven't already added this map... if (findMap(rmtMap) == null) { if (!myDisplay.getRendererVector().isEmpty()) { System.err.println("Late addMap: " + rmtMap); } else { // forward to any listeners monitor.notifyListeners(evt); try { myDisplay.addMap(rmtMap); } catch (VisADException ve) { ve.printStackTrace(); throw new RemoteVisADException("Map " + rmtMap + " not added: " + ve); } } } break; case MonitorEvent.MAP_CHANGED: // forward to any listeners monitor.notifyListeners(evt); rmtMap = ((MapMonitorEvent )evt).getMap(); lclMap = findMap(rmtMap); if (lclMap == null) { throw new RemoteVisADException("ScalarMap " + rmtMap + " not found"); } double[] rng = rmtMap.getRange(); try { lclMap.setRange(rng[0], rng[1]); } catch (VisADException ve) { throw new RemoteVisADException("Map not changed: " + ve); } break; case MonitorEvent.MAPS_CLEARED: // forward to any listeners monitor.notifyListeners(evt); try { myDisplay.removeAllReferences(); myDisplay.clearMaps(); } catch (VisADException ve) { throw new RemoteVisADException("Maps not cleared: " + ve); } catch (NullPointerException npe) { npe.printStackTrace(); throw new RemoteVisADException("Maps not cleared"); } break; case MonitorEvent.REFERENCE_ADDED: // forward to any listeners monitor.notifyListeners(evt); RemoteReferenceLink ref = ((ReferenceMonitorEvent )evt).getLink(); try { addLink(ref); } catch (VisADException ve) { throw new RemoteVisADException("DataReference " + ref + " not found by " + Name + ": " + ve.getMessage()); } break; case MonitorEvent.CONTROL_INIT_REQUESTED: // !!! DON'T FORWARD INIT EVENTS TO LISTENERS !!! rmtCtl = ((ControlMonitorEvent )evt).getControl(); lclCtl = myDisplay.getControl(rmtCtl.getClass(), rmtCtl.getInstanceNumber()); if (lclCtl == null) { // didn't find control ... maybe it doesn't exist yet? break; } try { ControlMonitorEvent cme; cme = new ControlMonitorEvent(MonitorEvent.CONTROL_CHANGED, (Control )lclCtl.clone()); monitor.notifyListeners(cme); } catch (VisADException ve) { throw new RemoteVisADException("Control " + rmtCtl + " not changed by " + Name + ": " + ve); } break; case MonitorEvent.CONTROL_CHANGED: rmtCtl = ((ControlMonitorEvent )evt).getControl(); lclCtl = myDisplay.getControl(rmtCtl.getClass(), rmtCtl.getInstanceNumber()); // skip this if we have change events to deliver for this control if (!monitor.hasEventQueued(evt.getOriginator(), lclCtl)) { if (lclCtl != null) { try { lclCtl.syncControl(rmtCtl); } catch (VisADException ve) { throw new RemoteVisADException("Control " + lclCtl + " not changed by " + Name + ": " + ve.getMessage()); } // forward to any listeners monitor.notifyListeners(evt); } } break; default: throw new RemoteVisADException("Event " + evt + " not handled"); } }
private void deliverOneEvent(MonitorEvent evt) throws RemoteException, RemoteVisADException { Control lclCtl, rmtCtl; ScalarMap lclMap, rmtMap; switch (evt.getType()) { case MonitorEvent.MAP_ADDED: rmtMap = ((MapMonitorEvent )evt).getMap(); // if we haven't already added this map... if (findMap(rmtMap) == null) { if (!myDisplay.getRendererVector().isEmpty()) { System.err.println("Late addMap: " + rmtMap); } else { // forward to any listeners monitor.notifyListeners(evt); try { myDisplay.addMap(rmtMap); } catch (VisADException ve) { ve.printStackTrace(); throw new RemoteVisADException("Map " + rmtMap + " not added: " + ve); } } } break; case MonitorEvent.MAP_CHANGED: // forward to any listeners monitor.notifyListeners(evt); rmtMap = ((MapMonitorEvent )evt).getMap(); lclMap = findMap(rmtMap); if (lclMap == null) { throw new RemoteVisADException("ScalarMap " + rmtMap + " not found"); } // CTR 2 June 2000 - do not set map range if already set (avoid loops) double[] rng = rmtMap.getRange(); double[] lclRng = lclMap.getRange(); if (rng[0] != lclRng[0] || rng[1] != lclRng[1]) { try { lclMap.setRange(rng[0], rng[1]); } catch (VisADException ve) { throw new RemoteVisADException("Map not changed: " + ve); } } break; case MonitorEvent.MAPS_CLEARED: // forward to any listeners monitor.notifyListeners(evt); try { myDisplay.removeAllReferences(); myDisplay.clearMaps(); } catch (VisADException ve) { throw new RemoteVisADException("Maps not cleared: " + ve); } catch (NullPointerException npe) { npe.printStackTrace(); throw new RemoteVisADException("Maps not cleared"); } break; case MonitorEvent.REFERENCE_ADDED: // forward to any listeners monitor.notifyListeners(evt); RemoteReferenceLink ref = ((ReferenceMonitorEvent )evt).getLink(); try { addLink(ref); } catch (VisADException ve) { throw new RemoteVisADException("DataReference " + ref + " not found by " + Name + ": " + ve.getMessage()); } break; case MonitorEvent.CONTROL_INIT_REQUESTED: // !!! DON'T FORWARD INIT EVENTS TO LISTENERS !!! rmtCtl = ((ControlMonitorEvent )evt).getControl(); lclCtl = myDisplay.getControl(rmtCtl.getClass(), rmtCtl.getInstanceNumber()); if (lclCtl == null) { // didn't find control ... maybe it doesn't exist yet? break; } try { ControlMonitorEvent cme; cme = new ControlMonitorEvent(MonitorEvent.CONTROL_CHANGED, (Control )lclCtl.clone()); monitor.notifyListeners(cme); } catch (VisADException ve) { throw new RemoteVisADException("Control " + rmtCtl + " not changed by " + Name + ": " + ve); } break; case MonitorEvent.CONTROL_CHANGED: rmtCtl = ((ControlMonitorEvent )evt).getControl(); lclCtl = myDisplay.getControl(rmtCtl.getClass(), rmtCtl.getInstanceNumber()); // skip this if we have change events to deliver for this control if (!monitor.hasEventQueued(evt.getOriginator(), lclCtl)) { if (lclCtl != null) { try { lclCtl.syncControl(rmtCtl); } catch (VisADException ve) { throw new RemoteVisADException("Control " + lclCtl + " not changed by " + Name + ": " + ve.getMessage()); } // forward to any listeners monitor.notifyListeners(evt); } } break; default: throw new RemoteVisADException("Event " + evt + " not handled"); } }
diff --git a/app/rules/RuleUtils.java b/app/rules/RuleUtils.java index 668890e..de74894 100644 --- a/app/rules/RuleUtils.java +++ b/app/rules/RuleUtils.java @@ -1,207 +1,206 @@ package rules; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import models.FileMove; import models.Rule; import models.User; import play.Logger; import com.google.appengine.repackaged.com.google.common.base.Pair; import com.google.common.collect.Lists; import dropbox.Dropbox; import dropbox.client.DropboxClient; import dropbox.client.DropboxClientFactory; import dropbox.client.FileMoveCollisionException; import dropbox.client.InvalidTokenException; public class RuleUtils { private static final int MAX_TRIES = 10; /** * Return a regex pattern that will match the given glob pattern. * * Only ? and * are supported. * TODO use a memoizer to cache compiled patterns. * TODO Collapse consecutive *'s. */ public static Pattern getGlobPattern(String glob) { if (glob == null) { return Pattern.compile(""); } StringBuilder out = new StringBuilder(); for(int i = 0; i < glob.length(); ++i) { final char c = glob.charAt(i); switch(c) { case '*': out.append(".*"); break; case '?': out.append("."); break; case '.': out.append("\\."); break; case '\\': out.append("\\\\"); break; default: out.append(c); } } return Pattern.compile(out.toString(), Pattern.CASE_INSENSITIVE); } public static String getExt(String fileName) { return splitName(fileName).second; } /** * Split given fileName into name and extension. * * If the file name starts with a period but does not contain any other * periods we say that it doesn't have an extension. * * Otherwise all text after the last period in the filename is taken to be * the extension even if it contains spaces. * * Examples: * ".bashrc" has no extension * ".foo.pdf" has the extension pdf * "file.ext ension" has extension "ext ension" * * @return a {@link Pair} where first is file name and second is extension. * Extension may be null * Extension does not contain the leading period (.) */ public static Pair<String, String> splitName(String fileName) { if (fileName == null) { return new Pair<String, String>(null, null); } int extBegin = fileName.lastIndexOf("."); if (extBegin <= 0) { return new Pair<String, String>(fileName, null); } String name = fileName.substring(0, extBegin); String ext = fileName.substring(extBegin + 1); if (ext.isEmpty()) { ext = null; } return new Pair<String, String>(name, ext); } /** * Process all rules for the current user and move files to new location * as approriate. * * @return list of file moves performed */ public static List<FileMove> runRules(User user) { user.updateLastSyncDate(); List<FileMove> fileMoves = Lists.newArrayList(); DropboxClient client = DropboxClientFactory.create(user); try { Set<String> files = client.listDir(Dropbox.getSortboxPath()); if (files.isEmpty()) { Logger.info("Ran rules for %s, no files to process.", user); return fileMoves; } List<Rule> rules = Rule.findByUserId(user.id); Logger.info("Running rules for %s", user); for (String file : files) { String base = basename(file); for (Rule r : rules) { if (r.matches(base)) { Logger.info("Moving file '%s' to '%s'. Rule id: %s", file, r.dest, r.id); boolean success = true; String resolvedName = null; int tries = 0; while (tries < MAX_TRIES) { try { String suffix = null; if (!success) { suffix = " conflict" + (tries > 1 ? " " + tries : ""); } resolvedName = insertIntoName(base, suffix); String dest = r.dest + (r.dest.endsWith("/") ? "" : "/") + resolvedName; client.move(file, dest); break; } catch (FileMoveCollisionException e) { success = false; } tries++; } if (success) { // If we moved the file to the correct destination - // on first try - // resolved name is same as original name so leave - // it as null. + // on first try resolved name is same as original + // name so leave it as null. resolvedName = null; } else if (tries >= MAX_TRIES) { // If we failed to move the file to any location // leave this field // as null to indicate complete failure. resolvedName = null; Logger.error( "Cannot move file '%s' to '%s' after %d tries. Skipping.", file, r.dest, MAX_TRIES); } fileMoves.add(new FileMove(user.id, base, r.dest, success, resolvedName)); break; } } } Logger.info("Done running rules for %s. %d moves performed", user, fileMoves.size()); if (!fileMoves.isEmpty()) { user.incrementFileMoves(fileMoves.size()); FileMove.save(fileMoves); } return fileMoves; } catch (InvalidTokenException e) { Logger.error(e, "Disabling periodic sort, invalid OAuth token for user: %s", user); user.periodicSort = false; user.save(); } return Collections.emptyList(); } public static String insertIntoName(String fileName, String suffix) { assert ! fileName.contains("/") : "Cannot process paths, can only process basenames."; Pair<String, String> fileAndExt = splitName(fileName); return fileAndExt.first + (suffix == null ? "" : suffix) + (fileAndExt.second == null ? "" : "." + fileAndExt.second); } public static String basename(String path) { return path == null ? null : new File(path).getName(); } private RuleUtils() {} }
true
true
public static List<FileMove> runRules(User user) { user.updateLastSyncDate(); List<FileMove> fileMoves = Lists.newArrayList(); DropboxClient client = DropboxClientFactory.create(user); try { Set<String> files = client.listDir(Dropbox.getSortboxPath()); if (files.isEmpty()) { Logger.info("Ran rules for %s, no files to process.", user); return fileMoves; } List<Rule> rules = Rule.findByUserId(user.id); Logger.info("Running rules for %s", user); for (String file : files) { String base = basename(file); for (Rule r : rules) { if (r.matches(base)) { Logger.info("Moving file '%s' to '%s'. Rule id: %s", file, r.dest, r.id); boolean success = true; String resolvedName = null; int tries = 0; while (tries < MAX_TRIES) { try { String suffix = null; if (!success) { suffix = " conflict" + (tries > 1 ? " " + tries : ""); } resolvedName = insertIntoName(base, suffix); String dest = r.dest + (r.dest.endsWith("/") ? "" : "/") + resolvedName; client.move(file, dest); break; } catch (FileMoveCollisionException e) { success = false; } tries++; } if (success) { // If we moved the file to the correct destination // on first try // resolved name is same as original name so leave // it as null. resolvedName = null; } else if (tries >= MAX_TRIES) { // If we failed to move the file to any location // leave this field // as null to indicate complete failure. resolvedName = null; Logger.error( "Cannot move file '%s' to '%s' after %d tries. Skipping.", file, r.dest, MAX_TRIES); } fileMoves.add(new FileMove(user.id, base, r.dest, success, resolvedName)); break; } } } Logger.info("Done running rules for %s. %d moves performed", user, fileMoves.size()); if (!fileMoves.isEmpty()) { user.incrementFileMoves(fileMoves.size()); FileMove.save(fileMoves); } return fileMoves; } catch (InvalidTokenException e) { Logger.error(e, "Disabling periodic sort, invalid OAuth token for user: %s", user); user.periodicSort = false; user.save(); } return Collections.emptyList(); }
public static List<FileMove> runRules(User user) { user.updateLastSyncDate(); List<FileMove> fileMoves = Lists.newArrayList(); DropboxClient client = DropboxClientFactory.create(user); try { Set<String> files = client.listDir(Dropbox.getSortboxPath()); if (files.isEmpty()) { Logger.info("Ran rules for %s, no files to process.", user); return fileMoves; } List<Rule> rules = Rule.findByUserId(user.id); Logger.info("Running rules for %s", user); for (String file : files) { String base = basename(file); for (Rule r : rules) { if (r.matches(base)) { Logger.info("Moving file '%s' to '%s'. Rule id: %s", file, r.dest, r.id); boolean success = true; String resolvedName = null; int tries = 0; while (tries < MAX_TRIES) { try { String suffix = null; if (!success) { suffix = " conflict" + (tries > 1 ? " " + tries : ""); } resolvedName = insertIntoName(base, suffix); String dest = r.dest + (r.dest.endsWith("/") ? "" : "/") + resolvedName; client.move(file, dest); break; } catch (FileMoveCollisionException e) { success = false; } tries++; } if (success) { // If we moved the file to the correct destination // on first try resolved name is same as original // name so leave it as null. resolvedName = null; } else if (tries >= MAX_TRIES) { // If we failed to move the file to any location // leave this field // as null to indicate complete failure. resolvedName = null; Logger.error( "Cannot move file '%s' to '%s' after %d tries. Skipping.", file, r.dest, MAX_TRIES); } fileMoves.add(new FileMove(user.id, base, r.dest, success, resolvedName)); break; } } } Logger.info("Done running rules for %s. %d moves performed", user, fileMoves.size()); if (!fileMoves.isEmpty()) { user.incrementFileMoves(fileMoves.size()); FileMove.save(fileMoves); } return fileMoves; } catch (InvalidTokenException e) { Logger.error(e, "Disabling periodic sort, invalid OAuth token for user: %s", user); user.periodicSort = false; user.save(); } return Collections.emptyList(); }
diff --git a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/DataPropertyAssertion.java b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/DataPropertyAssertion.java index 2ed9d4d85..68b73eb15 100644 --- a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/DataPropertyAssertion.java +++ b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/viewpoint/DataPropertyAssertion.java @@ -1,96 +1,98 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo 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. * * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.foundation.viewpoint; import org.openflexo.antar.binding.BindingDefinition; import org.openflexo.antar.binding.BindingDefinition.BindingDefinitionType; import org.openflexo.antar.binding.BindingModel; import org.openflexo.foundation.Inspectors; import org.openflexo.foundation.ontology.OntologyDataProperty; import org.openflexo.foundation.ontology.OntologyProperty; import org.openflexo.foundation.view.action.EditionSchemeAction; import org.openflexo.foundation.viewpoint.EditionAction.EditionActionBindingAttribute; import org.openflexo.foundation.viewpoint.binding.ViewPointDataBinding; public class DataPropertyAssertion extends AbstractAssertion { private String dataPropertyURI; public String _getDataPropertyURI() { return dataPropertyURI; } public void _setDataPropertyURI(String dataPropertyURI) { this.dataPropertyURI = dataPropertyURI; } @Override public String getInspectorName() { return Inspectors.VPM.DATA_PROPERTY_ASSERTION_INSPECTOR; } public OntologyProperty getOntologyProperty() { return getOntologyLibrary().getProperty(_getDataPropertyURI()); } public void setOntologyProperty(OntologyProperty p) { _setDataPropertyURI(p != null ? p.getURI() : null); } public Object getValue(EditionSchemeAction action) { return getValue().getBindingValue(action); } @Override public BindingModel getBindingModel() { return getEditionScheme().getBindingModel(); } private ViewPointDataBinding value; private BindingDefinition VALUE = new BindingDefinition("value", Object.class, BindingDefinitionType.GET, false) { @Override public java.lang.reflect.Type getType() { if (getOntologyProperty() instanceof OntologyDataProperty) { - return ((OntologyDataProperty) getOntologyProperty()).getDataType().getAccessedType(); + if (((OntologyDataProperty) getOntologyProperty()).getDataType() != null) { + return ((OntologyDataProperty) getOntologyProperty()).getDataType().getAccessedType(); + } } return Object.class; }; }; public BindingDefinition getValueBindingDefinition() { return VALUE; } public ViewPointDataBinding getValue() { if (value == null) { value = new ViewPointDataBinding(this, EditionActionBindingAttribute.value, getValueBindingDefinition()); } return value; } public void setValue(ViewPointDataBinding value) { value.setOwner(this); value.setBindingAttribute(EditionActionBindingAttribute.value); value.setBindingDefinition(getValueBindingDefinition()); this.value = value; } }
true
true
public java.lang.reflect.Type getType() { if (getOntologyProperty() instanceof OntologyDataProperty) { return ((OntologyDataProperty) getOntologyProperty()).getDataType().getAccessedType(); } return Object.class; };
public java.lang.reflect.Type getType() { if (getOntologyProperty() instanceof OntologyDataProperty) { if (((OntologyDataProperty) getOntologyProperty()).getDataType() != null) { return ((OntologyDataProperty) getOntologyProperty()).getDataType().getAccessedType(); } } return Object.class; };
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/performance/PerfSteppingTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/performance/PerfSteppingTests.java index d64e224c6..1ae8db498 100644 --- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/performance/PerfSteppingTests.java +++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/performance/PerfSteppingTests.java @@ -1,124 +1,124 @@ /******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.debug.tests.performance; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventFilter; import org.eclipse.jdt.debug.core.IJavaLineBreakpoint; import org.eclipse.jdt.debug.core.IJavaStackFrame; import org.eclipse.jdt.debug.core.IJavaThread; import org.eclipse.jdt.debug.tests.AbstractDebugPerformanceTest; import org.eclipse.test.performance.Dimension; /** * Tests performance of stepping. */ public class PerfSteppingTests extends AbstractDebugPerformanceTest { public PerfSteppingTests(String name) { super(name); } class MyFilter implements IDebugEventFilter { private IJavaThread fThread = null; private Object fLock; private DebugEvent[] EMPTY = new DebugEvent[0]; public MyFilter(IJavaThread thread, Object lock) { fThread = thread; fLock = lock; } public DebugEvent[] filterDebugEvents(DebugEvent[] events) { for (int i = 0; i < events.length; i++) { DebugEvent event = events[i]; if (event.getSource() == fThread) { if (event.getKind() == DebugEvent.SUSPEND && event.getDetail() == DebugEvent.STEP_END) { synchronized (fLock) { fLock.notifyAll(); } } return EMPTY; } } return events; } public void step() { synchronized (fLock) { try { fThread.stepOver(); } catch (DebugException e) { assertTrue(e.getMessage(), false); } try { fLock.wait(); } catch (InterruptedException e) { assertTrue(e.getMessage(), false); } } } } /** * Tests stepping over without taking into account event processing in the UI. * * @throws Exception */ public void testBareStepOver() throws Exception { - tagAsSummary("Rapid Stepping", Dimension.CPU_TIME); + tagAsSummary("Bare Step Over", Dimension.CPU_TIME); String typeName = "PerfLoop"; IJavaLineBreakpoint bp = createLineBreakpoint(20, typeName); IJavaThread thread= null; try { thread= launchToBreakpoint(typeName, false); // warm up Object lock = new Object(); MyFilter filter = new MyFilter(thread, lock); DebugPlugin.getDefault().addDebugEventFilter(filter); IJavaStackFrame frame = (IJavaStackFrame)thread.getTopStackFrame(); for (int n= 0; n < 10; n++) { for (int i = 0; i < 100; i++) { filter.step(); } } DebugPlugin.getDefault().removeDebugEventFilter(filter); // real test lock = new Object(); filter = new MyFilter(thread, lock); DebugPlugin.getDefault().addDebugEventFilter(filter); frame = (IJavaStackFrame)thread.getTopStackFrame(); for (int n= 0; n < 10; n++) { startMeasuring(); for (int i = 0; i < 100; i++) { filter.step(); } stopMeasuring(); } commitMeasurements(); assertPerformance(); DebugPlugin.getDefault().removeDebugEventFilter(filter); } finally { terminateAndRemove(thread); removeAllBreakpoints(); } } }
true
true
public void testBareStepOver() throws Exception { tagAsSummary("Rapid Stepping", Dimension.CPU_TIME); String typeName = "PerfLoop"; IJavaLineBreakpoint bp = createLineBreakpoint(20, typeName); IJavaThread thread= null; try { thread= launchToBreakpoint(typeName, false); // warm up Object lock = new Object(); MyFilter filter = new MyFilter(thread, lock); DebugPlugin.getDefault().addDebugEventFilter(filter); IJavaStackFrame frame = (IJavaStackFrame)thread.getTopStackFrame(); for (int n= 0; n < 10; n++) { for (int i = 0; i < 100; i++) { filter.step(); } } DebugPlugin.getDefault().removeDebugEventFilter(filter); // real test lock = new Object(); filter = new MyFilter(thread, lock); DebugPlugin.getDefault().addDebugEventFilter(filter); frame = (IJavaStackFrame)thread.getTopStackFrame(); for (int n= 0; n < 10; n++) { startMeasuring(); for (int i = 0; i < 100; i++) { filter.step(); } stopMeasuring(); } commitMeasurements(); assertPerformance(); DebugPlugin.getDefault().removeDebugEventFilter(filter); } finally { terminateAndRemove(thread); removeAllBreakpoints(); } }
public void testBareStepOver() throws Exception { tagAsSummary("Bare Step Over", Dimension.CPU_TIME); String typeName = "PerfLoop"; IJavaLineBreakpoint bp = createLineBreakpoint(20, typeName); IJavaThread thread= null; try { thread= launchToBreakpoint(typeName, false); // warm up Object lock = new Object(); MyFilter filter = new MyFilter(thread, lock); DebugPlugin.getDefault().addDebugEventFilter(filter); IJavaStackFrame frame = (IJavaStackFrame)thread.getTopStackFrame(); for (int n= 0; n < 10; n++) { for (int i = 0; i < 100; i++) { filter.step(); } } DebugPlugin.getDefault().removeDebugEventFilter(filter); // real test lock = new Object(); filter = new MyFilter(thread, lock); DebugPlugin.getDefault().addDebugEventFilter(filter); frame = (IJavaStackFrame)thread.getTopStackFrame(); for (int n= 0; n < 10; n++) { startMeasuring(); for (int i = 0; i < 100; i++) { filter.step(); } stopMeasuring(); } commitMeasurements(); assertPerformance(); DebugPlugin.getDefault().removeDebugEventFilter(filter); } finally { terminateAndRemove(thread); removeAllBreakpoints(); } }
diff --git a/core/vdmj/src/main/java/org/overturetool/vdmj/values/OperationValue.java b/core/vdmj/src/main/java/org/overturetool/vdmj/values/OperationValue.java index ac151dd493..0830ea1fc6 100644 --- a/core/vdmj/src/main/java/org/overturetool/vdmj/values/OperationValue.java +++ b/core/vdmj/src/main/java/org/overturetool/vdmj/values/OperationValue.java @@ -1,682 +1,682 @@ /******************************************************************************* * * Copyright (C) 2008 Fujitsu Services Ltd. * * Author: Nick Battle * * This file is part of VDMJ. * * VDMJ 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. * * VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ package org.overturetool.vdmj.values; import java.util.Iterator; import java.util.ListIterator; import org.overturetool.vdmj.Settings; import org.overturetool.vdmj.config.Properties; import org.overturetool.vdmj.definitions.ClassDefinition; import org.overturetool.vdmj.definitions.ExplicitOperationDefinition; import org.overturetool.vdmj.definitions.ImplicitOperationDefinition; import org.overturetool.vdmj.definitions.StateDefinition; import org.overturetool.vdmj.definitions.SystemDefinition; import org.overturetool.vdmj.expressions.AndExpression; import org.overturetool.vdmj.expressions.Expression; import org.overturetool.vdmj.lex.Dialect; import org.overturetool.vdmj.lex.LexKeywordToken; import org.overturetool.vdmj.lex.LexLocation; import org.overturetool.vdmj.lex.LexNameToken; import org.overturetool.vdmj.lex.Token; import org.overturetool.vdmj.messages.rtlog.RTExtendedTextMessage; import org.overturetool.vdmj.messages.rtlog.RTLogger; import org.overturetool.vdmj.messages.rtlog.RTOperationMessage; import org.overturetool.vdmj.messages.rtlog.RTMessage.MessageType; import org.overturetool.vdmj.patterns.Pattern; import org.overturetool.vdmj.patterns.PatternList; import org.overturetool.vdmj.runtime.ClassContext; import org.overturetool.vdmj.runtime.Context; import org.overturetool.vdmj.runtime.ObjectContext; import org.overturetool.vdmj.runtime.PatternMatchException; import org.overturetool.vdmj.runtime.RootContext; import org.overturetool.vdmj.runtime.StateContext; import org.overturetool.vdmj.runtime.ValueException; import org.overturetool.vdmj.scheduler.AsyncThread; import org.overturetool.vdmj.scheduler.BasicSchedulableThread; import org.overturetool.vdmj.scheduler.CPUResource; import org.overturetool.vdmj.scheduler.Holder; import org.overturetool.vdmj.scheduler.ISchedulableThread; import org.overturetool.vdmj.scheduler.InitThread; import org.overturetool.vdmj.scheduler.MessageRequest; import org.overturetool.vdmj.scheduler.MessageResponse; import org.overturetool.vdmj.scheduler.ResourceScheduler; import org.overturetool.vdmj.statements.Statement; import org.overturetool.vdmj.types.OperationType; import org.overturetool.vdmj.types.PatternListTypePair; import org.overturetool.vdmj.types.Type; import org.overturetool.vdmj.util.Utils; public class OperationValue extends Value { private static final long serialVersionUID = 1L; public final ExplicitOperationDefinition expldef; public final ImplicitOperationDefinition impldef; public final LexNameToken name; public final OperationType type; public final PatternList paramPatterns; public final Statement body; public final FunctionValue precondition; public final FunctionValue postcondition; public final StateDefinition state; public final ClassDefinition classdef; private LexNameToken stateName = null; private Context stateContext = null; private ObjectValue self = null; public boolean isConstructor = false; public boolean isStatic = false; public boolean isAsync = false; private Expression guard = null; public int hashAct = 0; // Number of activations public int hashFin = 0; // Number of finishes public int hashReq = 0; // Number of requests private long priority = 0; private boolean traceRT = true; public OperationValue(ExplicitOperationDefinition def, FunctionValue precondition, FunctionValue postcondition, StateDefinition state) { this.expldef = def; this.impldef = null; this.name = def.name; this.type = (OperationType)def.getType(); this.paramPatterns = def.parameterPatterns; this.body = def.body; this.precondition = precondition; this.postcondition = postcondition; this.state = state; this.classdef = def.classDefinition; this.isAsync = def.accessSpecifier.isAsync; traceRT = Settings.dialect == Dialect.VDM_RT && classdef != null && !(classdef instanceof SystemDefinition) && !classdef.name.name.equals("CPU") && !classdef.name.name.equals("BUS") && !name.name.equals("thread") && !name.name.startsWith("inv_"); } public OperationValue(ImplicitOperationDefinition def, FunctionValue precondition, FunctionValue postcondition, StateDefinition state) { this.impldef = def; this.expldef = null; this.name = def.name; this.type = (OperationType)def.getType(); this.paramPatterns = new PatternList(); for (PatternListTypePair ptp : def.parameterPatterns) { paramPatterns.addAll(ptp.patterns); } this.body = def.body; this.precondition = precondition; this.postcondition = postcondition; this.state = state; this.classdef = def.classDefinition; this.isAsync = def.accessSpecifier.isAsync; traceRT = Settings.dialect == Dialect.VDM_RT && classdef != null && !(classdef instanceof SystemDefinition) && !classdef.name.name.equals("CPU") && !classdef.name.name.equals("BUS") && !name.name.equals("thread"); } @Override public String toString() { return type.toString(); } public void setSelf(ObjectValue self) { if (!isStatic) { this.self = self; } } public ObjectValue getSelf() { return self; } public void setGuard(Expression add) { if (guard == null) { guard = add; } else { // Create "old and new" expression guard = new AndExpression(guard, new LexKeywordToken(Token.AND, guard.location), add); } } public void prepareGuard(ObjectContext ctxt) { if (guard != null) { ValueListener vl = new GuardValueListener(self); for (Value v: guard.getValues(ctxt)) { UpdatableValue uv = (UpdatableValue)v; uv.addListener(vl); } } } public Value eval(LexLocation from, ValueList argValues, Context ctxt) throws ValueException { if (Settings.dialect == Dialect.VDM_RT) { if (!isStatic && (ctxt.threadState.CPU != self.getCPU() || isAsync)) { return asyncEval(argValues, ctxt); } else { return localEval(from, argValues, ctxt, true); } } else { return localEval(from, argValues, ctxt, true); } } public Value localEval( LexLocation from, ValueList argValues, Context ctxt, boolean logreq) throws ValueException { if (body == null) { abort(4066, "Cannot call implicit operation: " + name, ctxt); } if (state != null && stateName == null) { stateName = state.name; stateContext = state.getStateContext(); } RootContext argContext = newContext(from, toTitle(), ctxt); req(logreq); notifySelf(); if (guard != null) { guard(argContext); } else { act(); // Still activated, even if no guard } notifySelf(); if (argValues.size() != paramPatterns.size()) { abort(4068, "Wrong number of arguments passed to " + name.name, ctxt); } ListIterator<Value> valIter = argValues.listIterator(); Iterator<Type> typeIter = type.parameters.iterator(); NameValuePairMap args = new NameValuePairMap(); for (Pattern p : paramPatterns) { try { // Note args cannot be Updateable, so we deref them here Value pv = valIter.next().deref().convertValueTo(typeIter.next(), ctxt); for (NameValuePair nvp : p.getNamedValues(pv, ctxt)) { Value v = args.get(nvp.name); if (v == null) { args.put(nvp); } else // Names match, so values must also { if (!v.equals(nvp.value)) { abort(4069, "Parameter patterns do not match arguments", ctxt); } } } } catch (PatternMatchException e) { abort(e.number, e, ctxt); } } if (self != null) { argContext.put(name.getSelfName(), self); } // Note: arg name/values hide member values argContext.putAll(args); Value originalSigma = null; ObjectValue originalSelf = null; - if (precondition != null || postcondition != null) + if (postcondition != null) { if (stateName != null) { Value sigma = argContext.lookup(stateName); originalSigma = (Value)sigma.clone(); } if (self != null) { originalSelf = self.shallowCopy(); // self.deepCopy(); } } // Make sure the #fin is updated with ErrorExceptions, using the // finally clause... Value rv = null; try { if (precondition != null && Settings.prechecks) { ValueList preArgs = new ValueList(argValues); if (stateName != null) { - preArgs.add(originalSigma); + preArgs.add(argContext.lookup(stateName)); } else if (self != null) { preArgs.add(self); } ctxt.setPrepost(4071, "Precondition failure: "); precondition.eval(from, preArgs, ctxt); ctxt.setPrepost(0, null); } rv = body.eval(argContext); if (isConstructor) { rv = self; } else { rv = rv.convertValueTo(type.result, argContext); } if (postcondition != null && Settings.postchecks) { ValueList postArgs = new ValueList(argValues); if (!(rv instanceof VoidValue)) { postArgs.add(rv); } if (stateName != null) { postArgs.add(originalSigma); Value sigma = argContext.lookup(stateName); postArgs.add(sigma); } else if (self != null) { postArgs.add(originalSelf); postArgs.add(self); } ctxt.setPrepost(4072, "Postcondition failure: "); postcondition.eval(from, postArgs, ctxt); ctxt.setPrepost(0, null); } } finally { fin(); notifySelf(); } return rv; } private RootContext newContext(LexLocation from, String title, Context ctxt) { RootContext argContext; if (self != null) { argContext = new ObjectContext(from, title, ctxt, self); } else if (classdef != null) { argContext = new ClassContext(from, title, ctxt, classdef); } else { argContext = new StateContext(from, title, ctxt, stateContext); } return argContext; } private void guard(Context ctxt) throws ValueException { ISchedulableThread th = BasicSchedulableThread.getThread(Thread.currentThread()); if (th == null || th instanceof InitThread ) { return; // Probably during initialization. } self.guardLock.lock(ctxt, guard.location); while (true) { synchronized (self) // So that test and act() are atomic { // We have to suspend thread swapping round the guard, // else we will reschedule another CPU thread while // having self locked, and that locks up everything! debug("guard TEST"); ctxt.threadState.setAtomic(true); boolean ok = guard.eval(ctxt).boolValue(ctxt); ctxt.threadState.setAtomic(false); if (ok) { debug("guard OK"); act(); break; // Out of while loop } } // The guardLock list is signalled by the GuardValueListener // and by notifySelf when something changes. debug("guard WAIT"); self.guardLock.block(ctxt, guard.location); debug("guard WAKE"); } self.guardLock.unlock(); } private void notifySelf() { if (self != null && self.guardLock != null) { debug("Signal guard"); self.guardLock.signal(); } } private Value asyncEval(ValueList argValues, Context ctxt) throws ValueException { // Spawn a thread, send a message, wait for a reply... CPUValue from = ctxt.threadState.CPU; CPUValue to = self.getCPU(); boolean stepping = ctxt.threadState.isStepping(); long threadId = BasicSchedulableThread.getThread(Thread.currentThread()).getId(); // Async calls have the OpRequest made by the caller using the // "from" CPU, whereas the OpActivate and OpComplete are made // by the called object, using self's CPU (see trace(msg)). RTLogger.log(new RTOperationMessage(MessageType.Request, this, from.resource, threadId)); if (from != to) // Remote CPU call { BUSValue bus = BUSValue.lookupBUS(from, to); if (bus == null) { abort(4140, "No BUS between CPUs " + from.getName() + " and " + to.getName(), ctxt); } if (isAsync) // Don't wait { MessageRequest request = new MessageRequest(ctxt.threadState.dbgp, bus, from, to, self, this, argValues, null, stepping); bus.transmit(request); return new VoidValue(); } else { Holder<MessageResponse> result = new Holder<MessageResponse>(); MessageRequest request = new MessageRequest(ctxt.threadState.dbgp, bus, from, to, self, this, argValues, result, stepping); bus.transmit(request); MessageResponse reply = result.get(ctxt, name.location); return reply.getValue(); // Can throw a returned exception } } else // local, must be async so don't wait { MessageRequest request = new MessageRequest(ctxt.threadState.dbgp, null, from, to, self, this, argValues, null, stepping); new AsyncThread(request).start(); return new VoidValue(); } } @Override public boolean equals(Object other) { if (other instanceof Value) { Value val = ((Value)other).deref(); if (val instanceof OperationValue) { OperationValue ov = (OperationValue)val; return ov.type.equals(type); } } return false; } @Override public int hashCode() { return type.hashCode(); } @Override public String kind() { return "operation"; } @Override public Value convertValueTo(Type to, Context ctxt) throws ValueException { if (to.isType(OperationType.class)) { return this; } else { return super.convertValueTo(to, ctxt); } } @Override public OperationValue operationValue(Context ctxt) { return this; } @Override public Object clone() { if (expldef != null) { return new OperationValue(expldef, precondition, postcondition, state); } else { return new OperationValue(impldef, precondition, postcondition, state); } } private synchronized void req(boolean logreq) { hashReq++; if (logreq) // Async OpRequests are made in asyncEval { trace(MessageType.Request); } debug("#req = " + hashReq); } private synchronized void act() { hashAct++; if (!ResourceScheduler.isStopping()) { trace(MessageType.Activate); debug("#act = " + hashAct); } } private synchronized void fin() { hashFin++; if (!ResourceScheduler.isStopping()) { trace(MessageType.Completed); debug("#fin = " + hashFin); } } private void trace(MessageType kind) { if (traceRT) { ISchedulableThread ct = BasicSchedulableThread.getThread(Thread.currentThread()); if (isStatic) { CPUResource cpu = null; if (ct instanceof InitThread) { cpu = CPUValue.vCPU.resource; // Initialization on vCPU } else { cpu = ct.getCPUResource(); } RTLogger.log(new RTOperationMessage(kind, this, cpu, ct.getId())); } else { RTLogger.log(new RTOperationMessage(kind, this, self.getCPU().resource, ct.getId())); } } } /** * @param string */ private void debug(String string) { if (Properties.diags_guards) { if (Settings.dialect == Dialect.VDM_PP) { System.err.println(String.format("%s %s %s", BasicSchedulableThread.getThread(Thread.currentThread()), name, string)); } else { RTLogger.log(new RTExtendedTextMessage(String.format("-- %s %s %s", BasicSchedulableThread.getThread(Thread.currentThread()), name, string))); } } } public synchronized void setPriority(long priority) { this.priority = priority; } public synchronized long getPriority() { return priority; } public synchronized CPUValue getCPU() { return self == null ? CPUValue.vCPU : self.getCPU(); } public String toTitle() { return name.name + Utils.listToString("(", paramPatterns, ", ", ")"); } }
false
true
public Value localEval( LexLocation from, ValueList argValues, Context ctxt, boolean logreq) throws ValueException { if (body == null) { abort(4066, "Cannot call implicit operation: " + name, ctxt); } if (state != null && stateName == null) { stateName = state.name; stateContext = state.getStateContext(); } RootContext argContext = newContext(from, toTitle(), ctxt); req(logreq); notifySelf(); if (guard != null) { guard(argContext); } else { act(); // Still activated, even if no guard } notifySelf(); if (argValues.size() != paramPatterns.size()) { abort(4068, "Wrong number of arguments passed to " + name.name, ctxt); } ListIterator<Value> valIter = argValues.listIterator(); Iterator<Type> typeIter = type.parameters.iterator(); NameValuePairMap args = new NameValuePairMap(); for (Pattern p : paramPatterns) { try { // Note args cannot be Updateable, so we deref them here Value pv = valIter.next().deref().convertValueTo(typeIter.next(), ctxt); for (NameValuePair nvp : p.getNamedValues(pv, ctxt)) { Value v = args.get(nvp.name); if (v == null) { args.put(nvp); } else // Names match, so values must also { if (!v.equals(nvp.value)) { abort(4069, "Parameter patterns do not match arguments", ctxt); } } } } catch (PatternMatchException e) { abort(e.number, e, ctxt); } } if (self != null) { argContext.put(name.getSelfName(), self); } // Note: arg name/values hide member values argContext.putAll(args); Value originalSigma = null; ObjectValue originalSelf = null; if (precondition != null || postcondition != null) { if (stateName != null) { Value sigma = argContext.lookup(stateName); originalSigma = (Value)sigma.clone(); } if (self != null) { originalSelf = self.shallowCopy(); // self.deepCopy(); } } // Make sure the #fin is updated with ErrorExceptions, using the // finally clause... Value rv = null; try { if (precondition != null && Settings.prechecks) { ValueList preArgs = new ValueList(argValues); if (stateName != null) { preArgs.add(originalSigma); } else if (self != null) { preArgs.add(self); } ctxt.setPrepost(4071, "Precondition failure: "); precondition.eval(from, preArgs, ctxt); ctxt.setPrepost(0, null); } rv = body.eval(argContext); if (isConstructor) { rv = self; } else { rv = rv.convertValueTo(type.result, argContext); } if (postcondition != null && Settings.postchecks) { ValueList postArgs = new ValueList(argValues); if (!(rv instanceof VoidValue)) { postArgs.add(rv); } if (stateName != null) { postArgs.add(originalSigma); Value sigma = argContext.lookup(stateName); postArgs.add(sigma); } else if (self != null) { postArgs.add(originalSelf); postArgs.add(self); } ctxt.setPrepost(4072, "Postcondition failure: "); postcondition.eval(from, postArgs, ctxt); ctxt.setPrepost(0, null); } } finally { fin(); notifySelf(); } return rv; }
public Value localEval( LexLocation from, ValueList argValues, Context ctxt, boolean logreq) throws ValueException { if (body == null) { abort(4066, "Cannot call implicit operation: " + name, ctxt); } if (state != null && stateName == null) { stateName = state.name; stateContext = state.getStateContext(); } RootContext argContext = newContext(from, toTitle(), ctxt); req(logreq); notifySelf(); if (guard != null) { guard(argContext); } else { act(); // Still activated, even if no guard } notifySelf(); if (argValues.size() != paramPatterns.size()) { abort(4068, "Wrong number of arguments passed to " + name.name, ctxt); } ListIterator<Value> valIter = argValues.listIterator(); Iterator<Type> typeIter = type.parameters.iterator(); NameValuePairMap args = new NameValuePairMap(); for (Pattern p : paramPatterns) { try { // Note args cannot be Updateable, so we deref them here Value pv = valIter.next().deref().convertValueTo(typeIter.next(), ctxt); for (NameValuePair nvp : p.getNamedValues(pv, ctxt)) { Value v = args.get(nvp.name); if (v == null) { args.put(nvp); } else // Names match, so values must also { if (!v.equals(nvp.value)) { abort(4069, "Parameter patterns do not match arguments", ctxt); } } } } catch (PatternMatchException e) { abort(e.number, e, ctxt); } } if (self != null) { argContext.put(name.getSelfName(), self); } // Note: arg name/values hide member values argContext.putAll(args); Value originalSigma = null; ObjectValue originalSelf = null; if (postcondition != null) { if (stateName != null) { Value sigma = argContext.lookup(stateName); originalSigma = (Value)sigma.clone(); } if (self != null) { originalSelf = self.shallowCopy(); // self.deepCopy(); } } // Make sure the #fin is updated with ErrorExceptions, using the // finally clause... Value rv = null; try { if (precondition != null && Settings.prechecks) { ValueList preArgs = new ValueList(argValues); if (stateName != null) { preArgs.add(argContext.lookup(stateName)); } else if (self != null) { preArgs.add(self); } ctxt.setPrepost(4071, "Precondition failure: "); precondition.eval(from, preArgs, ctxt); ctxt.setPrepost(0, null); } rv = body.eval(argContext); if (isConstructor) { rv = self; } else { rv = rv.convertValueTo(type.result, argContext); } if (postcondition != null && Settings.postchecks) { ValueList postArgs = new ValueList(argValues); if (!(rv instanceof VoidValue)) { postArgs.add(rv); } if (stateName != null) { postArgs.add(originalSigma); Value sigma = argContext.lookup(stateName); postArgs.add(sigma); } else if (self != null) { postArgs.add(originalSelf); postArgs.add(self); } ctxt.setPrepost(4072, "Postcondition failure: "); postcondition.eval(from, postArgs, ctxt); ctxt.setPrepost(0, null); } } finally { fin(); notifySelf(); } return rv; }
diff --git a/src/simpleserver/events/RunningEvent.java b/src/simpleserver/events/RunningEvent.java index 4f1b05e..ea1419e 100644 --- a/src/simpleserver/events/RunningEvent.java +++ b/src/simpleserver/events/RunningEvent.java @@ -1,753 +1,751 @@ /* * Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS) * * 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 simpleserver.events; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import simpleserver.Coordinate; import simpleserver.Player; import simpleserver.Server; import simpleserver.bot.BotController.ConnectException; import simpleserver.bot.NpcBot; import simpleserver.command.ExternalCommand; import simpleserver.command.PlayerCommand; import simpleserver.command.ServerCommand; import simpleserver.config.xml.CommandConfig; import simpleserver.config.xml.CommandConfig.Forwarding; import simpleserver.config.xml.Event; import simpleserver.log.EventsLog; class RunningEvent extends Thread implements Runnable { /** * */ public boolean stopping = false; // indicates that the thread should stop protected EventHost eventHost; protected Server server; protected Event event; // currently run event protected Player player; // referred player context // (default -> triggering player) private String threadname = null; // null = just subroutine protected static final int MAXDEPTH = 5; protected static final char LOCALSCOPE = '#'; protected static final char PLAYERSCOPE = '@'; protected static final char GLOBALSCOPE = '$'; protected static final char REFERENCEOP = '\''; private HashMap<String, String> vars; // local vars private ArrayList<String> threadstack; // thread-shared data stack // for control structures private int stackdepth = 0; // to limit subroutines private String lastline; // line being executed private int currline = 0; // execution line pointer private ArrayList<Integer> ifstack; private ArrayList<Integer> whilestack; private boolean running = false; public RunningEvent(EventHost h, String n, Event e, Player p) { eventHost = h; server = h.server; event = e; player = p; threadname = n; // Top level event without initialized stack -> initialize empty data stack threadstack = new ArrayList<String>(); vars = new HashMap<String, String>(); ifstack = new ArrayList<Integer>(); whilestack = new ArrayList<Integer>(); } /* init as subroutine */ public RunningEvent(EventHost h, String n, Event e, Player p, int depth, ArrayList<String> stack) { this(h, n, e, p); stackdepth = depth; if (stack != null) { threadstack = stack; } } @Override public void run() { if (running) { // prevent running the same object twice return; } running = true; String script = event.script; if (script == null) { return; // no script data present } // Split actions by semicola and newlines ArrayList<String> actions = new ArrayList<String>(java.util.Arrays.asList(script.split("[\n;]"))); currline = 0; while (currline < actions.size()) { if (stopping) { break; } lastline = actions.get(currline); ArrayList<String> tokens = parseLine(lastline); evaluateVariables(tokens); if (tokens.size() == 0) { currline++; continue; } // run action String cmd = tokens.remove(0); if (cmd.equals("return")) { cmdreturn(tokens); return; } else if (cmd.equals("rem") || cmd.equals("endif")) { currline++; continue; } else if (cmd.equals("print") && tokens.size() > 0) { System.out.println("L" + String.valueOf(currline) + "@" + event.name + " msg: " + tokens.get(0)); - } - else if (cmd.equals("log") && tokens.size() > 0){ - server.eventsLog(event.name + " @L" + String.valueOf(currline),tokens.get(0)); - } - else if (cmd.equals("logprint") && tokens.size() > 0){ - server.eventsLog(event.name + " @L" + String.valueOf(currline),tokens.get(0)); - System.out.println("L" + String.valueOf(currline) + "@" + event.name + " msg: " + tokens.get(0)); - } else if (cmd.equals("sleep") && tokens.size() > 0) { + } else if (cmd.equals("log") && tokens.size() > 0){ + server.eventsLog(event.name + " @L" + String.valueOf(currline),tokens.get(0)); + } else if (cmd.equals("logprint") && tokens.size() > 0){ + server.eventsLog(event.name + " @L" + String.valueOf(currline),tokens.get(0)); + System.out.println("L" + String.valueOf(currline) + "@" + event.name + " msg: " + tokens.get(0)); + } else if (cmd.equals("sleep") && tokens.size() > 0) { try { Thread.sleep(Integer.valueOf(tokens.get(0))); } catch (InterruptedException e) { if (stopping) { break; } } } else if (cmd.equals("teleport")) { teleport(tokens); } else if (cmd.equals("npc")) { npcSpawn(tokens); } else if (cmd.equals("npckill")) { npcKill(tokens); } else if (cmd.equals("say")) { say(tokens); } else if (cmd.equals("broadcast")) { broadcast(tokens); } else if (cmd.equals("execsvrcmd")) { execsvrcmd(tokens); } else if (cmd.equals("execcmd")) { execcmd(tokens); } else if (cmd.equals("set")) { set(tokens); } else if (cmd.equals("inc")) { increment(tokens); } else if (cmd.equals("dec")) { decrement(tokens); } else if (cmd.equals("push")) { push(tokens); } else if (cmd.equals("if")) { condition(tokens, actions); } else if (cmd.equals("else")) { currline = ifstack.remove(0); } else if (cmd.equals("while")) { loop(tokens, actions); } else if (cmd.equals("break")) { breakloop(tokens, actions); } else if (cmd.equals("endwhile") || cmd.equals("continue")) { currline = whilestack.remove(0); } else if (cmd.equals("run")) { cmdrun(tokens, false); } else if (cmd.equals("launch")) { cmdrun(tokens, true); } else { notifyError("Command not found!"); } currline++; } // implicit return value -> empty array threadstack.add(0, PostfixEvaluator.fromArray(new ArrayList<String>())); // finished -> remove itself from the running thread list if (threadname != null) { eventHost.running.remove(threadname); } } private ArrayList<String> parseLine(String line) { ArrayList<String> tokens = new ArrayList<String>(); String currtok = null; boolean inString = false; for (int i = 0; i < line.length(); i++) { if (!inString && String.valueOf(line.charAt(i)).matches("\\s")) { if (currtok != null) { tokens.add(currtok); currtok = null; } continue; } if (currtok == null) { currtok = ""; } if (inString && line.charAt(i) == '\\') { // Escape character i++; currtok += line.charAt(i); continue; } if (line.charAt(i) == '"') { inString = !inString; continue; } currtok += line.charAt(i); } if (currtok != null) { tokens.add(currtok); } return tokens; } private void evaluateVariables(ArrayList<String> tokens) { for (int i = 0; i < tokens.size(); i++) { String var = evaluateVar(tokens.get(i)); if (var != null) { tokens.set(i, var); } } } protected String evaluateVar(String varname) { if (varname == null || varname.equals("")) { return ""; } if (varname.charAt(0) == REFERENCEOP) { // escape variable char c = varname.charAt(1); if (c == LOCALSCOPE || c == PLAYERSCOPE || c == GLOBALSCOPE) { return varname.substring(1); } else { return null; // not a variable } } else if (varname.charAt(0) == LOCALSCOPE) { // local var String loc = varname.substring(1); // check special vars if (loc.equals("PLAYER")) { return player != null ? player.getName() : "null"; } else if (loc.equals("EVENT")) { return event.name; } else if (loc.equals("THIS")) { return "$" + event.name; } else if (loc.equals("VALUE")) { return eventHost.globals.get(event.name); } else if (loc.equals("COORD")) { return String.valueOf(event.coordinate); } else if (loc.equals("POP")) { return threadstack.size() == 0 ? "null" : threadstack.remove(0); } else if (loc.equals("TOP")) { return threadstack.size() == 0 ? "null" : threadstack.get(0); } else if (eventHost.colors.containsKey(loc)) { return "\u00a7" + eventHost.colors.get(loc); } else { String v = vars.get(loc); if (v == null) { vars.put(loc, "null"); v = "null"; } return String.valueOf(v); } } else if (varname.charAt(0) == PLAYERSCOPE) { // player var return String.valueOf(player.vars.get(varname.substring(1))); } else if (varname.charAt(0) == GLOBALSCOPE) { // global perm var (event // value) String name = varname.substring(1); if (eventHost.globals.containsKey(name)) { String ret = eventHost.globals.get(name); return ret; } else { notifyError("Event " + name + " not found!"); return "null"; } } return null; // not a variable } /*---- Interaction ----*/ private void say(ArrayList<String> tokens) { if (tokens.size() < 2) { notifyError("Wrong number of arguments!"); return; } Player p = server.findPlayer(tokens.remove(0)); if (p == null) { notifyError("Player not found!"); return; } String message = new PostfixEvaluator(this).evaluateSingle(tokens); p.addTMessage(message); } private void broadcast(ArrayList<String> tokens) { String message = new PostfixEvaluator(this).evaluateSingle(tokens); server.runCommand("say", message); } private void teleport(ArrayList<String> tokens) { if (tokens.size() < 2) { notifyError("Wrong number of arguments!"); return; } Player p = server.findPlayer(tokens.get(0)); if (p == null) { notifyError("Source player not online!"); return; } Coordinate c = null; String dest = tokens.get(1); // Try to find such a player Player q = server.findPlayer(dest); if (q != null) { c = q.position.coordinate(); } // Try to find such an event if (c == null && dest.length() > 0 && dest.charAt(0) == GLOBALSCOPE) { Event evdest = eventHost.findEvent(dest.substring(1)); if (evdest != null) { c = evdest.coordinate; } } if (c == null) { // try to find a warp with that name String w = server.data.warp.getName(dest); if (w != null) { p.teleportSelf(server.data.warp.get(w)); // port to warp, ignore rest return; } } // try to parse as coordinate if (c == null) { c = Coordinate.fromString(dest); } if (c != null) { p.teleportSelf(c); } else { notifyError("Destination not found!"); } } private void execcmd(ArrayList<String> tokens) { if (tokens.size() == 0) { notifyError("Wrong number of arguments!"); return; // no command to execute } Player p = server.findPlayer(tokens.remove(0)); if (p == null) { notifyError("Player not found!"); return; } String message = server.options.getBoolean("useSlashes") ? "/" : "!"; for (String token : tokens) { message += token + " "; } message = message.substring(0, message.length() - 1); // execute the server command, overriding the player permissions p.parseCommand(message, true); // handle forwarding String cmd = tokens.get(0); PlayerCommand command = server.resolvePlayerCommand(cmd, p.getGroup()); // forwarding if necessary CommandConfig config = server.config.commands.getTopConfig(cmd); if ((command instanceof ExternalCommand) || (config != null && config.forwarding != Forwarding.NONE) || server.config.properties.getBoolean("forwardAllCommands")) { p.forwardMessage(message); } } private void execsvrcmd(ArrayList<String> tokens) { if (tokens.size() == 0) { notifyError("Wrong number of arguments!"); return; // no command to execute } String cmd = tokens.get(0); String args = ""; for (String t : tokens) { args += t + " "; } args = args.substring(0, args.length() - 1); ServerCommand command = server.getCommandParser().getServerCommand(cmd); if (command != null) { server.runCommand(cmd, args); } } private void npcSpawn(ArrayList<String> tokens) { if (tokens.size() < 5) { notifyError("Wrong number of arguments!"); return; } String name = tokens.remove(0); if (eventHost.npcs.get(name) != null) { notifyError("An NPC with this name still exists!"); return; } Event event = eventHost.findEvent(tokens.remove(0)); if (event == null) { notifyError("Event associated with NPC not found!"); return; } int x = 0; int y = 0; int z = 0; try { x = Integer.valueOf(tokens.remove(0)); y = Integer.valueOf(tokens.remove(0)); z = Integer.valueOf(tokens.remove(0)); } catch (Exception e) { notifyError("Invalid NPC spawn coordinate!"); return; } Coordinate c = new Coordinate(x, y, z); try { NpcBot s = new NpcBot(name, event.name, server, c); server.bots.connect(s); eventHost.npcs.put(name, s); } catch (IOException ex) { notifyError("Could not spawn NPC!"); ex.printStackTrace(); } catch (ConnectException e) { notifyError("Could not spawn NPC!"); e.printStackTrace(); } } private void npcKill(ArrayList<String> tokens) { if (tokens.size() < 1) { notifyError("Wrong number of arguments!"); return; } String name = new PostfixEvaluator(this).evaluateSingle(tokens); NpcBot b = eventHost.npcs.remove(name); if (b == null) { notifyError("An NPC with this name is not logged on!"); return; } try { b.logout(); } catch (IOException e) { notifyError("Error while logging out bot!"); e.printStackTrace(); } } /*---- variable & runtime ----*/ private void set(ArrayList<String> tokens) { if (tokens.size() < 2) { notifyError("Wrong number of arguments!"); return; } ArrayList<String> vals = new PostfixEvaluator(this).evaluate(tokens); if (vals == null || vals.size() < 2) { return; } /* only 2 elements left - normal behaviour like before */ if (vals.size() == 2) { String s = vals.remove(0); String v = vals.remove(0); assignVariable(s, v); } else if (vals.size() > 2) { /* more elements = multiple assignment */ /* separating symbols and values (looking for "to" keyword */ ArrayList<String> vars = new ArrayList<String>(); while (vals.size() > 0 && !vals.get(0).equals("to")) { vars.add(vals.remove(0)); } if (vals.size() == 0) { notifyError("Invalid multiple assignment / invalid expression! ('to' keyword missing?)"); return; } vals.remove(0); // remove 'to' /* execute multiple assignment */ while (vars.size() != 0) { String s = vars.remove(0); String v = "null"; if (vals.size() != 0) { if (vars.size() != 0 || vals.size() == 1) { v = vals.remove(0); } else { v = PostfixEvaluator.fromArray(vals); } } assignVariable(s, v); } } } private void increment(ArrayList<String> tokens) { if (tokens.size() != 1) { notifyError("Wrong number of arguments!"); return; } String v = tokens.get(0); assignVariable(v, String.valueOf(PostfixEvaluator.toNum(evaluateVar(v)) + 1)); } private void decrement(ArrayList<String> tokens) { if (tokens.size() != 1) { notifyError("Wrong number of arguments!"); return; } String v = tokens.get(0); assignVariable(v, String.valueOf(PostfixEvaluator.toNum(evaluateVar(v)) - 1)); } private void assignVariable(String symbol, String value) { if (symbol == null || symbol.length() < 2) { return; } if (value == null) { value = "null"; } char scope = symbol.charAt(0); String var = symbol.substring(1); if (scope == LOCALSCOPE) { vars.put(var, value); } else if (scope == PLAYERSCOPE) { player.vars.put(var, value); } else if (scope == GLOBALSCOPE) { if (eventHost.globals.containsKey(var)) { eventHost.globals.put(var, value); } else { notifyError("Assignment failed: event " + var + " not found!"); } } else { notifyError("Assignment failed: Invalid variable reference!"); } } private void push(ArrayList<String> tokens) { String exp = new PostfixEvaluator(this).evaluateSingle(tokens); if (exp == null) { threadstack.add(0, "null"); return; } threadstack.add(0, exp); } private void cmdreturn(ArrayList<String> tokens) { threadstack.add(0, PostfixEvaluator.fromArray(new PostfixEvaluator(this).evaluate(tokens))); } private void cmdrun(ArrayList<String> tokens, boolean newThread) { if (tokens.size() < 1) { notifyError("Wrong number of arguments!"); return; } Event e = eventHost.findEvent(tokens.remove(0)); if (e == null) { notifyError("Event to run not found!"); return; } String args = PostfixEvaluator.fromArray(new PostfixEvaluator(this).evaluate(tokens)); if (!newThread) { if (stackdepth < MAXDEPTH) { threadstack.add(0, args); (new RunningEvent(eventHost, null, e, player, stackdepth + 1, threadstack)).run(); } else { notifyError("Can not run event - stack level too deep!"); } } else { // run in a new thread (passing threadstack copy!) @SuppressWarnings("unchecked") ArrayList<String> clone = (ArrayList<String>) threadstack.clone(); clone.add(args); eventHost.executeEvent(e, player, clone); } } private void condition(ArrayList<String> tokens, ArrayList<String> actions) { boolean result = new PostfixEvaluator(this).evaluateCondition(tokens); int ifcounter = 0; boolean hasElse = false; if (result) { for (int i = currline + 1; i < actions.size(); i++) { ArrayList<String> line = parseLine(actions.get(i)); if (line.size() == 0) { continue; } String cmd = line.get(0); if (cmd.equals("if")) { ifcounter++; } if (cmd.equals("else") && ifcounter == 0) { hasElse = true; } if (cmd.equals("endif")) { if (ifcounter == 0) { if (hasElse) { ifstack.add(0, i); } break; } else { ifcounter--; } } } } else { for (int i = currline + 1; i < actions.size(); i++) { ArrayList<String> line = parseLine(actions.get(i)); if (line.size() == 0) { continue; } String cmd = line.get(0); if (cmd.equals("if")) { ifcounter++; } if (cmd.equals("endif")) { if (ifcounter == 0) { // no else found -> jump here currline = i; break; } ifcounter--; } if (cmd.equals("else") && ifcounter == 0) { // jump to else part currline = i; break; } } } } private void loop(ArrayList<String> tokens, ArrayList<String> actions) { boolean result = new PostfixEvaluator(this).evaluateCondition(tokens); if (!result) { // jump over while loop -> leave breakloop(tokens, actions); } else { // save current line for jump back -> enter whilestack.add(0, currline - 1); } } private void breakloop(ArrayList<String> tokens, ArrayList<String> actions) { int whilecounter = 0; for (int i = currline + 1; i < actions.size(); i++) { ArrayList<String> line = parseLine(actions.get(i)); if (line.size() == 0) { continue; } String cmd = line.get(0); if (cmd.equals("while")) { whilecounter++; } if (cmd.equals("endwhile")) { if (whilecounter == 0) { currline = i; break; } else { whilecounter--; } } } } /*--------*/ protected void notifyError(String err) { System.out.println("Error at L" + String.valueOf(currline) + "@" + event.name + ": " + lastline); System.out.println(err + "\n"); } }
true
true
public void run() { if (running) { // prevent running the same object twice return; } running = true; String script = event.script; if (script == null) { return; // no script data present } // Split actions by semicola and newlines ArrayList<String> actions = new ArrayList<String>(java.util.Arrays.asList(script.split("[\n;]"))); currline = 0; while (currline < actions.size()) { if (stopping) { break; } lastline = actions.get(currline); ArrayList<String> tokens = parseLine(lastline); evaluateVariables(tokens); if (tokens.size() == 0) { currline++; continue; } // run action String cmd = tokens.remove(0); if (cmd.equals("return")) { cmdreturn(tokens); return; } else if (cmd.equals("rem") || cmd.equals("endif")) { currline++; continue; } else if (cmd.equals("print") && tokens.size() > 0) { System.out.println("L" + String.valueOf(currline) + "@" + event.name + " msg: " + tokens.get(0)); } else if (cmd.equals("log") && tokens.size() > 0){ server.eventsLog(event.name + " @L" + String.valueOf(currline),tokens.get(0)); } else if (cmd.equals("logprint") && tokens.size() > 0){ server.eventsLog(event.name + " @L" + String.valueOf(currline),tokens.get(0)); System.out.println("L" + String.valueOf(currline) + "@" + event.name + " msg: " + tokens.get(0)); } else if (cmd.equals("sleep") && tokens.size() > 0) { try { Thread.sleep(Integer.valueOf(tokens.get(0))); } catch (InterruptedException e) { if (stopping) { break; } } } else if (cmd.equals("teleport")) { teleport(tokens); } else if (cmd.equals("npc")) { npcSpawn(tokens); } else if (cmd.equals("npckill")) { npcKill(tokens); } else if (cmd.equals("say")) { say(tokens); } else if (cmd.equals("broadcast")) { broadcast(tokens); } else if (cmd.equals("execsvrcmd")) { execsvrcmd(tokens); } else if (cmd.equals("execcmd")) { execcmd(tokens); } else if (cmd.equals("set")) { set(tokens); } else if (cmd.equals("inc")) { increment(tokens); } else if (cmd.equals("dec")) { decrement(tokens); } else if (cmd.equals("push")) { push(tokens); } else if (cmd.equals("if")) { condition(tokens, actions); } else if (cmd.equals("else")) { currline = ifstack.remove(0); } else if (cmd.equals("while")) { loop(tokens, actions); } else if (cmd.equals("break")) { breakloop(tokens, actions); } else if (cmd.equals("endwhile") || cmd.equals("continue")) { currline = whilestack.remove(0); } else if (cmd.equals("run")) { cmdrun(tokens, false); } else if (cmd.equals("launch")) { cmdrun(tokens, true); } else { notifyError("Command not found!"); } currline++; } // implicit return value -> empty array threadstack.add(0, PostfixEvaluator.fromArray(new ArrayList<String>())); // finished -> remove itself from the running thread list if (threadname != null) { eventHost.running.remove(threadname); } }
public void run() { if (running) { // prevent running the same object twice return; } running = true; String script = event.script; if (script == null) { return; // no script data present } // Split actions by semicola and newlines ArrayList<String> actions = new ArrayList<String>(java.util.Arrays.asList(script.split("[\n;]"))); currline = 0; while (currline < actions.size()) { if (stopping) { break; } lastline = actions.get(currline); ArrayList<String> tokens = parseLine(lastline); evaluateVariables(tokens); if (tokens.size() == 0) { currline++; continue; } // run action String cmd = tokens.remove(0); if (cmd.equals("return")) { cmdreturn(tokens); return; } else if (cmd.equals("rem") || cmd.equals("endif")) { currline++; continue; } else if (cmd.equals("print") && tokens.size() > 0) { System.out.println("L" + String.valueOf(currline) + "@" + event.name + " msg: " + tokens.get(0)); } else if (cmd.equals("log") && tokens.size() > 0){ server.eventsLog(event.name + " @L" + String.valueOf(currline),tokens.get(0)); } else if (cmd.equals("logprint") && tokens.size() > 0){ server.eventsLog(event.name + " @L" + String.valueOf(currline),tokens.get(0)); System.out.println("L" + String.valueOf(currline) + "@" + event.name + " msg: " + tokens.get(0)); } else if (cmd.equals("sleep") && tokens.size() > 0) { try { Thread.sleep(Integer.valueOf(tokens.get(0))); } catch (InterruptedException e) { if (stopping) { break; } } } else if (cmd.equals("teleport")) { teleport(tokens); } else if (cmd.equals("npc")) { npcSpawn(tokens); } else if (cmd.equals("npckill")) { npcKill(tokens); } else if (cmd.equals("say")) { say(tokens); } else if (cmd.equals("broadcast")) { broadcast(tokens); } else if (cmd.equals("execsvrcmd")) { execsvrcmd(tokens); } else if (cmd.equals("execcmd")) { execcmd(tokens); } else if (cmd.equals("set")) { set(tokens); } else if (cmd.equals("inc")) { increment(tokens); } else if (cmd.equals("dec")) { decrement(tokens); } else if (cmd.equals("push")) { push(tokens); } else if (cmd.equals("if")) { condition(tokens, actions); } else if (cmd.equals("else")) { currline = ifstack.remove(0); } else if (cmd.equals("while")) { loop(tokens, actions); } else if (cmd.equals("break")) { breakloop(tokens, actions); } else if (cmd.equals("endwhile") || cmd.equals("continue")) { currline = whilestack.remove(0); } else if (cmd.equals("run")) { cmdrun(tokens, false); } else if (cmd.equals("launch")) { cmdrun(tokens, true); } else { notifyError("Command not found!"); } currline++; } // implicit return value -> empty array threadstack.add(0, PostfixEvaluator.fromArray(new ArrayList<String>())); // finished -> remove itself from the running thread list if (threadname != null) { eventHost.running.remove(threadname); } }
diff --git a/impl/src/main/java/org/jboss/forge/addon/gradle/projects/GradleManagerImpl.java b/impl/src/main/java/org/jboss/forge/addon/gradle/projects/GradleManagerImpl.java index 287d1cf..786c5e2 100644 --- a/impl/src/main/java/org/jboss/forge/addon/gradle/projects/GradleManagerImpl.java +++ b/impl/src/main/java/org/jboss/forge/addon/gradle/projects/GradleManagerImpl.java @@ -1,87 +1,87 @@ /* * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.gradle.projects; import java.io.File; import java.util.List; import java.util.concurrent.CountDownLatch; import org.gradle.jarjar.com.google.common.collect.Lists; import org.gradle.tooling.BuildLauncher; import org.gradle.tooling.GradleConnectionException; import org.gradle.tooling.GradleConnector; import org.gradle.tooling.ProjectConnection; import org.gradle.tooling.ResultHandler; import org.jboss.forge.furnace.util.Strings; /** * @author Adam Wyłuda */ public class GradleManagerImpl implements GradleManager { private static class ResultHolder { private volatile boolean result; } @Override public boolean runGradleBuild(String directory, String task, String profile, String... arguments) { String gradleHome = System.getenv("GRADLE_HOME"); GradleConnector connector = GradleConnector.newConnector() .forProjectDirectory(new File(directory)); if (!Strings.isNullOrEmpty(gradleHome)) { - connector = connector.useGradleUserHomeDir(new File(gradleHome)); + connector = connector.useInstallation(new File(gradleHome)); } ProjectConnection connection = connector.connect(); BuildLauncher launcher = connection.newBuild().forTasks(task); List<String> argList = Lists.newArrayList(arguments); if (!Strings.isNullOrEmpty(profile)) { argList.add("-Pprofile=" + profile); } launcher = launcher.withArguments(argList.toArray(new String[argList.size()])); final ResultHolder holder = new ResultHolder(); final CountDownLatch latch = new CountDownLatch(1); launcher.run(new ResultHandler<Object>() { @Override public void onComplete(Object result) { holder.result = true; latch.countDown(); } @Override public void onFailure(GradleConnectionException failure) { holder.result = false; latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } return holder.result; } }
true
true
public boolean runGradleBuild(String directory, String task, String profile, String... arguments) { String gradleHome = System.getenv("GRADLE_HOME"); GradleConnector connector = GradleConnector.newConnector() .forProjectDirectory(new File(directory)); if (!Strings.isNullOrEmpty(gradleHome)) { connector = connector.useGradleUserHomeDir(new File(gradleHome)); } ProjectConnection connection = connector.connect(); BuildLauncher launcher = connection.newBuild().forTasks(task); List<String> argList = Lists.newArrayList(arguments); if (!Strings.isNullOrEmpty(profile)) { argList.add("-Pprofile=" + profile); } launcher = launcher.withArguments(argList.toArray(new String[argList.size()])); final ResultHolder holder = new ResultHolder(); final CountDownLatch latch = new CountDownLatch(1); launcher.run(new ResultHandler<Object>() { @Override public void onComplete(Object result) { holder.result = true; latch.countDown(); } @Override public void onFailure(GradleConnectionException failure) { holder.result = false; latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } return holder.result; }
public boolean runGradleBuild(String directory, String task, String profile, String... arguments) { String gradleHome = System.getenv("GRADLE_HOME"); GradleConnector connector = GradleConnector.newConnector() .forProjectDirectory(new File(directory)); if (!Strings.isNullOrEmpty(gradleHome)) { connector = connector.useInstallation(new File(gradleHome)); } ProjectConnection connection = connector.connect(); BuildLauncher launcher = connection.newBuild().forTasks(task); List<String> argList = Lists.newArrayList(arguments); if (!Strings.isNullOrEmpty(profile)) { argList.add("-Pprofile=" + profile); } launcher = launcher.withArguments(argList.toArray(new String[argList.size()])); final ResultHolder holder = new ResultHolder(); final CountDownLatch latch = new CountDownLatch(1); launcher.run(new ResultHandler<Object>() { @Override public void onComplete(Object result) { holder.result = true; latch.countDown(); } @Override public void onFailure(GradleConnectionException failure) { holder.result = false; latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } return holder.result; }
diff --git a/src/nodebox/client/FileUtils.java b/src/nodebox/client/FileUtils.java index 0ca0d2a0..b76297bd 100644 --- a/src/nodebox/client/FileUtils.java +++ b/src/nodebox/client/FileUtils.java @@ -1,163 +1,171 @@ package nodebox.client; import javax.swing.filechooser.FileFilter; import java.awt.*; import java.io.*; import java.util.StringTokenizer; public class FileUtils { /** * Gets the extension of a file. * * @param f the file * @return the extension of the file. */ public static String getExtension(File f) { return getExtension(f.getName()); } /** * Gets the extension of a file. * * @param fileName the file name * @return the extension of the file. */ public static String getExtension(String fileName) { String ext = null; int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { ext = fileName.substring(i + 1).toLowerCase(); } return ext; } public static File showOpenDialog(Frame owner, String pathName, String extensions, String description) { return showFileDialog(owner, pathName, extensions, description, FileDialog.LOAD); } public static File showSaveDialog(Frame owner, String pathName, String extensions, String description) { return showFileDialog(owner, pathName, extensions, description, FileDialog.SAVE); } private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) { FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType); if (pathName == null || pathName.trim().length() == 0) { - File documentFile = NodeBoxDocument.getCurrentDocument().getDocumentFile(); - if (documentFile != null) { - fileDialog.setFile(documentFile.getParentFile().getPath()); + NodeBoxDocument document = NodeBoxDocument.getCurrentDocument(); + if (document != null) { + File documentFile = document.getDocumentFile(); + if (documentFile != null) { + fileDialog.setFile(documentFile.getParentFile().getPath()); + } } } else { - fileDialog.setFile(pathName); + File f = new File(pathName); + if (f.isDirectory()) { + fileDialog.setDirectory(pathName); + } else { + fileDialog.setFile(pathName); + } } fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description)); fileDialog.setVisible(true); String chosenFile = fileDialog.getFile(); String dir = fileDialog.getDirectory(); if (chosenFile != null) { return new File(dir + chosenFile); } else { return null; } } public static String[] parseExtensions(String extensions) { StringTokenizer st = new StringTokenizer(extensions, ","); String[] ext = new String[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { ext[i++] = st.nextToken(); } return ext; } public static class FileExtensionFilter extends FileFilter implements FilenameFilter { String[] extensions; String description; public FileExtensionFilter(String extensions, String description) { this.extensions = parseExtensions(extensions); this.description = description; } public boolean accept(File f) { return f.isDirectory() || accept(null, f.getName()); } public boolean accept(File f, String s) { String extension = FileUtils.getExtension(s); if (extension != null) { for (String extension1 : extensions) { if (extension1.equals("*") || extension1.equalsIgnoreCase(extension)) { return true; } } } return false; } public String getDescription() { return description; } } public static String readFile(File file) { StringBuffer contents = new StringBuffer(); try { FileInputStream fstream = new FileInputStream(file); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; while ((line = br.readLine()) != null) { contents.append(line); contents.append("\n"); } in.close(); } catch (IOException e) { throw new RuntimeException("Could not read file " + file, e); } return contents.toString(); } public static void writeFile(File file, String s) { try { Writer out = new BufferedWriter(new FileWriter(file)); out.write(s); out.close(); } catch (IOException e) { throw new RuntimeException("Could not write file " + file, e); } } public static File createTemporaryDirectory(String prefix) { File tempDir = null; try { tempDir = File.createTempFile(prefix, ""); } catch (IOException e) { throw new RuntimeException("Could not create temporary file " + prefix); } boolean success = tempDir.delete(); if (!success) throw new RuntimeException("Could not delete temporary file " + tempDir); success = tempDir.mkdir(); if (!success) throw new RuntimeException("Could not create temporary directory " + tempDir); return tempDir; } public static boolean deleteDirectory(File directory) { if (directory.exists()) { File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { deleteDirectory(file); } else { //noinspection ResultOfMethodCallIgnored file.delete(); } } } return (directory.delete()); } }
false
true
private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) { FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType); if (pathName == null || pathName.trim().length() == 0) { File documentFile = NodeBoxDocument.getCurrentDocument().getDocumentFile(); if (documentFile != null) { fileDialog.setFile(documentFile.getParentFile().getPath()); } } else { fileDialog.setFile(pathName); } fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description)); fileDialog.setVisible(true); String chosenFile = fileDialog.getFile(); String dir = fileDialog.getDirectory(); if (chosenFile != null) { return new File(dir + chosenFile); } else { return null; } }
private static File showFileDialog(Frame owner, String pathName, String extensions, String description, int fileDialogType) { FileDialog fileDialog = new FileDialog(owner, pathName, fileDialogType); if (pathName == null || pathName.trim().length() == 0) { NodeBoxDocument document = NodeBoxDocument.getCurrentDocument(); if (document != null) { File documentFile = document.getDocumentFile(); if (documentFile != null) { fileDialog.setFile(documentFile.getParentFile().getPath()); } } } else { File f = new File(pathName); if (f.isDirectory()) { fileDialog.setDirectory(pathName); } else { fileDialog.setFile(pathName); } } fileDialog.setFilenameFilter(new FileExtensionFilter(extensions, description)); fileDialog.setVisible(true); String chosenFile = fileDialog.getFile(); String dir = fileDialog.getDirectory(); if (chosenFile != null) { return new File(dir + chosenFile); } else { return null; } }
diff --git a/src/pspnetparty/client/swt/ConnectAddressDialog.java b/src/pspnetparty/client/swt/ConnectAddressDialog.java index 89fddf9..0570573 100644 --- a/src/pspnetparty/client/swt/ConnectAddressDialog.java +++ b/src/pspnetparty/client/swt/ConnectAddressDialog.java @@ -1,134 +1,141 @@ /* Copyright (C) 2011 monte This file is part of PSP NetParty. PSP NetParty 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 pspnetparty.client.swt; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; import pspnetparty.lib.socket.TransportLayer; public class ConnectAddressDialog extends Dialog { private TransportLayer transport; private String hostname; private int port; protected ConnectAddressDialog(Shell parentShell) { super(parentShell); } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); newShell.setText("アドレスを入力してください"); } @Override protected Control createDialogArea(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(4, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); GridData gridData; { Label label = new Label(composite, SWT.NONE); label.setText("接続先のアドレス:"); label.setLayoutData(new GridData(SWT.DEFAULT, SWT.DEFAULT, false, false, 4, 1)); } { Combo transportCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); transportCombo.add("TCP"); transportCombo.add("UDP"); transportCombo.select(0); transport = TransportLayer.TCP; transportCombo.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { Combo transportCombo = (Combo) e.widget; switch (transportCombo.getSelectionIndex()) { case 0: transport = TransportLayer.TCP; break; case 1: transport = TransportLayer.UDP; break; } } }); } { Text hostnameText = new Text(composite, SWT.BORDER | SWT.SINGLE); hostnameText.setText(hostname = ""); gridData = new GridData(GridData.FILL, GridData.CENTER, true, false); gridData.minimumWidth = 100; hostnameText.setLayoutData(gridData); hostnameText.setFocus(); + hostnameText.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + Text hostnameText = (Text) e.widget; + hostname = hostnameText.getText(); + } + }); } { Label label = new Label(composite, SWT.NONE); label.setText(":"); } { Spinner portSpinner = new Spinner(composite, SWT.BORDER); portSpinner.setMinimum(1); portSpinner.setMaximum(65535); portSpinner.setSelection(port = 20000); portSpinner.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { Spinner portSpinner = (Spinner) e.widget; port = portSpinner.getSelection(); } }); } return composite; } public TransportLayer getTransport() { return transport; } public String getHostName() { return hostname; } public int getPort() { return port; } }
true
true
protected Control createDialogArea(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(4, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); GridData gridData; { Label label = new Label(composite, SWT.NONE); label.setText("接続先のアドレス:"); label.setLayoutData(new GridData(SWT.DEFAULT, SWT.DEFAULT, false, false, 4, 1)); } { Combo transportCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); transportCombo.add("TCP"); transportCombo.add("UDP"); transportCombo.select(0); transport = TransportLayer.TCP; transportCombo.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { Combo transportCombo = (Combo) e.widget; switch (transportCombo.getSelectionIndex()) { case 0: transport = TransportLayer.TCP; break; case 1: transport = TransportLayer.UDP; break; } } }); } { Text hostnameText = new Text(composite, SWT.BORDER | SWT.SINGLE); hostnameText.setText(hostname = ""); gridData = new GridData(GridData.FILL, GridData.CENTER, true, false); gridData.minimumWidth = 100; hostnameText.setLayoutData(gridData); hostnameText.setFocus(); } { Label label = new Label(composite, SWT.NONE); label.setText(":"); } { Spinner portSpinner = new Spinner(composite, SWT.BORDER); portSpinner.setMinimum(1); portSpinner.setMaximum(65535); portSpinner.setSelection(port = 20000); portSpinner.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { Spinner portSpinner = (Spinner) e.widget; port = portSpinner.getSelection(); } }); } return composite; }
protected Control createDialogArea(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(4, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); GridData gridData; { Label label = new Label(composite, SWT.NONE); label.setText("接続先のアドレス:"); label.setLayoutData(new GridData(SWT.DEFAULT, SWT.DEFAULT, false, false, 4, 1)); } { Combo transportCombo = new Combo(composite, SWT.BORDER | SWT.READ_ONLY); transportCombo.add("TCP"); transportCombo.add("UDP"); transportCombo.select(0); transport = TransportLayer.TCP; transportCombo.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { Combo transportCombo = (Combo) e.widget; switch (transportCombo.getSelectionIndex()) { case 0: transport = TransportLayer.TCP; break; case 1: transport = TransportLayer.UDP; break; } } }); } { Text hostnameText = new Text(composite, SWT.BORDER | SWT.SINGLE); hostnameText.setText(hostname = ""); gridData = new GridData(GridData.FILL, GridData.CENTER, true, false); gridData.minimumWidth = 100; hostnameText.setLayoutData(gridData); hostnameText.setFocus(); hostnameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { Text hostnameText = (Text) e.widget; hostname = hostnameText.getText(); } }); } { Label label = new Label(composite, SWT.NONE); label.setText(":"); } { Spinner portSpinner = new Spinner(composite, SWT.BORDER); portSpinner.setMinimum(1); portSpinner.setMaximum(65535); portSpinner.setSelection(port = 20000); portSpinner.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { Spinner portSpinner = (Spinner) e.widget; port = portSpinner.getSelection(); } }); } return composite; }
diff --git a/webapp/src/main/java/org/vaadin/tori/indexing/IndexableDashboardView.java b/webapp/src/main/java/org/vaadin/tori/indexing/IndexableDashboardView.java index d3ce9758..4ed5d46d 100644 --- a/webapp/src/main/java/org/vaadin/tori/indexing/IndexableDashboardView.java +++ b/webapp/src/main/java/org/vaadin/tori/indexing/IndexableDashboardView.java @@ -1,76 +1,76 @@ /* * Copyright 2012 Vaadin Ltd. * * 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.vaadin.tori.indexing; import java.util.List; import org.apache.log4j.Logger; import org.vaadin.tori.ToriNavigator; import org.vaadin.tori.ToriUtil; import org.vaadin.tori.data.DataSource; import org.vaadin.tori.data.entity.Category; import org.vaadin.tori.exception.DataSourceException; public class IndexableDashboardView extends IndexableView { public IndexableDashboardView(final List<String> arguments, final ToriIndexableApplication application) { super(arguments, application); } @Override public String getHtml() { return "<h1>Forum</h1>" + getCategoriesXhtml(application.getDataSource(), getLogger(), null); } public static String getCategoriesXhtml(final DataSource ds, final Logger logger, final Category currentCategory) { final StringBuilder sb = new StringBuilder(); try { final List<Category> subCategories = ds .getSubCategories(currentCategory); if (!subCategories.isEmpty()) { sb.append("<h2>Categories</h2>"); sb.append("<ul>"); for (final Category category : subCategories) { - sb.append(String.format("<li><a href=\"#%s\">%s</a>", + sb.append(String.format("<li><a href=\"%s\">%s</a>", getLink(category, ds), getDescription(category))); } sb.append("</ul>"); } } catch (final DataSourceException e) { logger.error(e); sb.append("There was an error when trying to fetch categories."); } return sb.toString(); } private static String getDescription(final Category category) { return ToriUtil.escapeXhtml(category.getName()) + "<br>" + ToriUtil.escapeXhtml(category.getDescription()); } private static String getLink(final Category category, final DataSource ds) { return ds.getPathRoot() + "#" + ToriNavigator.ApplicationView.CATEGORIES.getUrl() + "/" + category.getId(); } }
true
true
public static String getCategoriesXhtml(final DataSource ds, final Logger logger, final Category currentCategory) { final StringBuilder sb = new StringBuilder(); try { final List<Category> subCategories = ds .getSubCategories(currentCategory); if (!subCategories.isEmpty()) { sb.append("<h2>Categories</h2>"); sb.append("<ul>"); for (final Category category : subCategories) { sb.append(String.format("<li><a href=\"#%s\">%s</a>", getLink(category, ds), getDescription(category))); } sb.append("</ul>"); } } catch (final DataSourceException e) { logger.error(e); sb.append("There was an error when trying to fetch categories."); } return sb.toString(); }
public static String getCategoriesXhtml(final DataSource ds, final Logger logger, final Category currentCategory) { final StringBuilder sb = new StringBuilder(); try { final List<Category> subCategories = ds .getSubCategories(currentCategory); if (!subCategories.isEmpty()) { sb.append("<h2>Categories</h2>"); sb.append("<ul>"); for (final Category category : subCategories) { sb.append(String.format("<li><a href=\"%s\">%s</a>", getLink(category, ds), getDescription(category))); } sb.append("</ul>"); } } catch (final DataSourceException e) { logger.error(e); sb.append("There was an error when trying to fetch categories."); } return sb.toString(); }
diff --git a/src/main/java/hudson/plugins/selenium/HudsonRemoteControlPool.java b/src/main/java/hudson/plugins/selenium/HudsonRemoteControlPool.java index d68f631..21a9aa2 100644 --- a/src/main/java/hudson/plugins/selenium/HudsonRemoteControlPool.java +++ b/src/main/java/hudson/plugins/selenium/HudsonRemoteControlPool.java @@ -1,107 +1,111 @@ package hudson.plugins.selenium; import com.thoughtworks.selenium.grid.hub.Environment; import com.thoughtworks.selenium.grid.hub.remotecontrol.DynamicRemoteControlPool; import com.thoughtworks.selenium.grid.hub.remotecontrol.RemoteControlProxy; import java.util.HashSet; import java.util.Set; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.logging.Logger; import java.util.logging.Level; /** * {@link DynamicRemoteControlPool} that uses labels for matching. * * <P> * The "environment" that Selenium see is '/'-separated list of labels for the slave * (like /a/b/c/d), and we match incoming label to determine the {@link RemoteControlProxy}. * * @author Kohsuke Kawaguchi */ public class HudsonRemoteControlPool implements DynamicRemoteControlPool { private final Set<RemoteControlProxy> all = new HashSet<RemoteControlProxy>(); private final Map<String,RemoteControlProxy> sessions = new HashMap<String, RemoteControlProxy>(); public synchronized void register(RemoteControlProxy rc) { all.add(rc); } public synchronized boolean unregister(RemoteControlProxy rc) { return all.remove(rc); } public synchronized List<RemoteControlProxy> availableRemoteControls() { List<RemoteControlProxy> r = new ArrayList<RemoteControlProxy>(all.size()); for (RemoteControlProxy rc : all) if(rc.canHandleNewSession()) r.add(rc); return r; } public synchronized List<RemoteControlProxy> reservedRemoteControls() { List<RemoteControlProxy> r = new ArrayList<RemoteControlProxy>(all.size()); for (RemoteControlProxy rc : all) if(rc.concurrentSesssionCount() > 0) r.add(rc); return r; } public synchronized RemoteControlProxy reserve(Environment env) { String[] keys = env.name().split("&"); for (int i = 0; i < keys.length; i++) keys[i] = '/'+keys[i]+'/'; while(true) { boolean hadMatch=false; for (RemoteControlProxy rc : all) { if((hadMatch|=matches(rc,keys)) && rc.canHandleNewSession()) { rc.registerNewSession(); return rc; } } // is there any point in waiting? - if(!hadMatch) - throw new IllegalArgumentException("No RC satisifies the label criteria: "+env.name()); + if(!hadMatch) { + if(all.isEmpty()) + throw new IllegalArgumentException("No RCs available"); + else + throw new IllegalArgumentException("No RC satisifies the label criteria: "+env.name()+" - "+all); + } try { wait(); } catch (InterruptedException e) { // this is totally broken IMO, but the reserve method doesn't allow us to return LOGGER.log(Level.WARNING, "Interrupted while reserving remote control for "+env.name(), e); } } } private boolean matches(RemoteControlProxy rc, String[] keys) { for (String key : keys) if(!rc.environment().contains(key)) return false; return true; } public synchronized void release(RemoteControlProxy rc) { rc.unregisterSession(); notifyAll(); } public synchronized void associateWithSession(RemoteControlProxy rc, String sessionId) { RemoteControlProxy old = sessions.put(sessionId, rc); if(old!=null) throw new IllegalStateException("Session ID "+sessionId+" is already used by "+old); } public synchronized RemoteControlProxy retrieve(String sessionId) { return sessions.get(sessionId); } public synchronized void releaseForSession(String sessionId) { sessions.remove(sessionId).unregisterSession(); } private static final Logger LOGGER = Logger.getLogger(HudsonRemoteControlPool.class.getName()); }
true
true
public synchronized RemoteControlProxy reserve(Environment env) { String[] keys = env.name().split("&"); for (int i = 0; i < keys.length; i++) keys[i] = '/'+keys[i]+'/'; while(true) { boolean hadMatch=false; for (RemoteControlProxy rc : all) { if((hadMatch|=matches(rc,keys)) && rc.canHandleNewSession()) { rc.registerNewSession(); return rc; } } // is there any point in waiting? if(!hadMatch) throw new IllegalArgumentException("No RC satisifies the label criteria: "+env.name()); try { wait(); } catch (InterruptedException e) { // this is totally broken IMO, but the reserve method doesn't allow us to return LOGGER.log(Level.WARNING, "Interrupted while reserving remote control for "+env.name(), e); } } }
public synchronized RemoteControlProxy reserve(Environment env) { String[] keys = env.name().split("&"); for (int i = 0; i < keys.length; i++) keys[i] = '/'+keys[i]+'/'; while(true) { boolean hadMatch=false; for (RemoteControlProxy rc : all) { if((hadMatch|=matches(rc,keys)) && rc.canHandleNewSession()) { rc.registerNewSession(); return rc; } } // is there any point in waiting? if(!hadMatch) { if(all.isEmpty()) throw new IllegalArgumentException("No RCs available"); else throw new IllegalArgumentException("No RC satisifies the label criteria: "+env.name()+" - "+all); } try { wait(); } catch (InterruptedException e) { // this is totally broken IMO, but the reserve method doesn't allow us to return LOGGER.log(Level.WARNING, "Interrupted while reserving remote control for "+env.name(), e); } } }
diff --git a/src/main/java/jp/sf/fess/helper/CrawlingConfigHelper.java b/src/main/java/jp/sf/fess/helper/CrawlingConfigHelper.java index 842825a20..df4e2dbb8 100644 --- a/src/main/java/jp/sf/fess/helper/CrawlingConfigHelper.java +++ b/src/main/java/jp/sf/fess/helper/CrawlingConfigHelper.java @@ -1,290 +1,292 @@ /* * Copyright 2009-2013 the Fess Project and the Others. * * 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 jp.sf.fess.helper; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.http.HttpServletResponse; import jp.sf.fess.Constants; import jp.sf.fess.FessSystemException; import jp.sf.fess.db.exentity.CrawlingConfig; import jp.sf.fess.db.exentity.CrawlingConfig.ConfigType; import jp.sf.fess.helper.UserAgentHelper.UserAgentType; import jp.sf.fess.service.DataCrawlingConfigService; import jp.sf.fess.service.FileCrawlingConfigService; import jp.sf.fess.service.WebCrawlingConfigService; import org.apache.commons.io.IOUtils; import org.seasar.framework.container.SingletonS2Container; import org.seasar.framework.util.Base64Util; import org.seasar.robot.client.S2RobotClient; import org.seasar.robot.client.S2RobotClientFactory; import org.seasar.robot.entity.ResponseData; import org.seasar.robot.util.StreamUtil; import org.seasar.struts.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CrawlingConfigHelper implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory .getLogger(CrawlingConfigHelper.class); protected final Map<String, CrawlingConfig> crawlingConfigMap = new ConcurrentHashMap<String, CrawlingConfig>(); protected int count = 1; public ConfigType getConfigType(final String configId) { if (configId == null || configId.length() < 2) { return null; } final String configType = configId.substring(0, 1); if (ConfigType.WEB.getTypePrefix().equals(configType)) { return ConfigType.WEB; } else if (ConfigType.FILE.getTypePrefix().equals(configType)) { return ConfigType.FILE; } else if (ConfigType.DATA.getTypePrefix().equals(configType)) { return ConfigType.DATA; } return null; } protected Long getId(final String configId) { if (configId == null || configId.length() < 2) { return null; } try { final String idStr = configId.substring(1); return Long.parseLong(idStr); } catch (final NumberFormatException e) { // ignore } return null; } public CrawlingConfig getCrawlingConfig(final String configId) { final ConfigType configType = getConfigType(configId); if (configType == null) { return null; } final Long id = getId(configId); if (id == null) { return null; } switch (configType) { case WEB: final WebCrawlingConfigService webCrawlingConfigService = SingletonS2Container .getComponent(WebCrawlingConfigService.class); return webCrawlingConfigService.getWebCrawlingConfig(id); case FILE: final FileCrawlingConfigService fileCrawlingConfigService = SingletonS2Container .getComponent(FileCrawlingConfigService.class); return fileCrawlingConfigService.getFileCrawlingConfig(id); case DATA: final DataCrawlingConfigService dataCrawlingConfigService = SingletonS2Container .getComponent(DataCrawlingConfigService.class); return dataCrawlingConfigService.getDataCrawlingConfig(id); default: return null; } } public synchronized String store(final String sessionId, final CrawlingConfig crawlingConfig) { final String sessionCountId = sessionId + "-" + count; crawlingConfigMap.put(sessionCountId, crawlingConfig); count++; return sessionCountId; } public void remove(final String sessionId) { crawlingConfigMap.remove(sessionId); } public CrawlingConfig get(final String sessionId) { return crawlingConfigMap.get(sessionId); } public void writeContent(final Map<String, Object> doc) { if (logger.isDebugEnabled()) { logger.debug("writing the content of: " + doc); } final SystemHelper systemHelper = SingletonS2Container .getComponent("systemHelper"); final Object configIdObj = doc.get(systemHelper.configIdField); if (configIdObj == null) { throw new FessSystemException("Invalid configId: " + configIdObj); } final String configId = configIdObj.toString(); if (configId.length() < 2) { throw new FessSystemException("Invalid configId: " + configIdObj); } final ConfigType configType = getConfigType(configId); CrawlingConfig config = null; if (logger.isDebugEnabled()) { logger.debug("configType: " + configType + ", configId: " + configId); } if (ConfigType.WEB == configType) { final WebCrawlingConfigService webCrawlingConfigService = SingletonS2Container .getComponent(WebCrawlingConfigService.class); config = webCrawlingConfigService .getWebCrawlingConfig(getId(configId)); } else if (ConfigType.FILE == configType) { final FileCrawlingConfigService fileCrawlingConfigService = SingletonS2Container .getComponent(FileCrawlingConfigService.class); config = fileCrawlingConfigService .getFileCrawlingConfig(getId(configId)); } else if (ConfigType.DATA == configType) { final DataCrawlingConfigService dataCrawlingConfigService = SingletonS2Container .getComponent(DataCrawlingConfigService.class); config = dataCrawlingConfigService .getDataCrawlingConfig(getId(configId)); } if (config == null) { throw new FessSystemException("No crawlingConfig: " + configIdObj); } final String url = (String) doc.get(systemHelper.urlField); final S2RobotClientFactory robotClientFactory = SingletonS2Container .getComponent(S2RobotClientFactory.class); config.initializeClientFactory(robotClientFactory); final S2RobotClient client = robotClientFactory.getClient(url); if (client == null) { throw new FessSystemException("No S2RobotClient: " + configIdObj + ", url: " + url); } final ResponseData responseData = client.doGet(url); final HttpServletResponse response = ResponseUtil.getResponse(); writeFileName(response, responseData); writeContentType(response, responseData); writeNoCache(response, responseData); InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(responseData.getResponseBody()); os = new BufferedOutputStream(response.getOutputStream()); StreamUtil.drain(is, os); os.flush(); } catch (final IOException e) { - throw new FessSystemException( - "Failed to write a content. configId: " + configIdObj - + ", url: " + url, e); + if (!"ClientAbortException".equals(e.getClass().getSimpleName())) { + throw new FessSystemException( + "Failed to write a content. configId: " + configIdObj + + ", url: " + url, e); + } } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } if (logger.isDebugEnabled()) { logger.debug("Finished to write " + url); } } protected void writeNoCache(final HttpServletResponse response, final ResponseData responseData) { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Expires", "Thu, 01 Dec 1994 16:00:00 GMT"); } protected void writeFileName(final HttpServletResponse response, final ResponseData responseData) { final UserAgentHelper userAgentHelper = SingletonS2Container .getComponent(UserAgentHelper.class); final UserAgentType userAgentType = userAgentHelper.getUserAgentType(); String charset = responseData.getCharSet(); if (charset == null) { charset = Constants.UTF_8; } final String name; final String url = responseData.getUrl(); final int pos = url.lastIndexOf('/'); try { if (pos >= 0 && pos + 1 < url.length()) { name = URLDecoder.decode(url.substring(pos + 1), charset); } else { name = URLDecoder.decode(url, charset); } if (logger.isDebugEnabled()) { logger.debug("userAgentType: " + userAgentType + ", charset: " + charset + ", name: " + name); } switch (userAgentType) { case IE: response.setHeader( "Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(name, Constants.UTF_8) + "\""); break; case OPERA: response.setHeader( "Content-Disposition", "attachment; filename*=utf-8'ja'" + URLEncoder.encode(name, Constants.UTF_8)); break; case SAFARI: response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\""); break; case CHROME: case FIREFOX: case OTHER: response.setHeader( "Content-Disposition", "attachment; filename=\"=?utf-8?B?" + Base64Util.encode(name .getBytes(Constants.UTF_8)) + "?=\""); break; } } catch (final Exception e) { logger.warn("Failed to write a filename: " + responseData, e); } } protected void writeContentType(final HttpServletResponse response, final ResponseData responseData) { final String mimeType = responseData.getMimeType(); if (logger.isDebugEnabled()) { logger.debug("mimeType: " + mimeType); } if (mimeType == null) { return; } if (mimeType.startsWith("text/")) { final String charset = response.getCharacterEncoding(); if (charset != null) { response.setContentType(mimeType + "; charset=" + charset); return; } } response.setContentType(mimeType); } }
true
true
public void writeContent(final Map<String, Object> doc) { if (logger.isDebugEnabled()) { logger.debug("writing the content of: " + doc); } final SystemHelper systemHelper = SingletonS2Container .getComponent("systemHelper"); final Object configIdObj = doc.get(systemHelper.configIdField); if (configIdObj == null) { throw new FessSystemException("Invalid configId: " + configIdObj); } final String configId = configIdObj.toString(); if (configId.length() < 2) { throw new FessSystemException("Invalid configId: " + configIdObj); } final ConfigType configType = getConfigType(configId); CrawlingConfig config = null; if (logger.isDebugEnabled()) { logger.debug("configType: " + configType + ", configId: " + configId); } if (ConfigType.WEB == configType) { final WebCrawlingConfigService webCrawlingConfigService = SingletonS2Container .getComponent(WebCrawlingConfigService.class); config = webCrawlingConfigService .getWebCrawlingConfig(getId(configId)); } else if (ConfigType.FILE == configType) { final FileCrawlingConfigService fileCrawlingConfigService = SingletonS2Container .getComponent(FileCrawlingConfigService.class); config = fileCrawlingConfigService .getFileCrawlingConfig(getId(configId)); } else if (ConfigType.DATA == configType) { final DataCrawlingConfigService dataCrawlingConfigService = SingletonS2Container .getComponent(DataCrawlingConfigService.class); config = dataCrawlingConfigService .getDataCrawlingConfig(getId(configId)); } if (config == null) { throw new FessSystemException("No crawlingConfig: " + configIdObj); } final String url = (String) doc.get(systemHelper.urlField); final S2RobotClientFactory robotClientFactory = SingletonS2Container .getComponent(S2RobotClientFactory.class); config.initializeClientFactory(robotClientFactory); final S2RobotClient client = robotClientFactory.getClient(url); if (client == null) { throw new FessSystemException("No S2RobotClient: " + configIdObj + ", url: " + url); } final ResponseData responseData = client.doGet(url); final HttpServletResponse response = ResponseUtil.getResponse(); writeFileName(response, responseData); writeContentType(response, responseData); writeNoCache(response, responseData); InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(responseData.getResponseBody()); os = new BufferedOutputStream(response.getOutputStream()); StreamUtil.drain(is, os); os.flush(); } catch (final IOException e) { throw new FessSystemException( "Failed to write a content. configId: " + configIdObj + ", url: " + url, e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } if (logger.isDebugEnabled()) { logger.debug("Finished to write " + url); } }
public void writeContent(final Map<String, Object> doc) { if (logger.isDebugEnabled()) { logger.debug("writing the content of: " + doc); } final SystemHelper systemHelper = SingletonS2Container .getComponent("systemHelper"); final Object configIdObj = doc.get(systemHelper.configIdField); if (configIdObj == null) { throw new FessSystemException("Invalid configId: " + configIdObj); } final String configId = configIdObj.toString(); if (configId.length() < 2) { throw new FessSystemException("Invalid configId: " + configIdObj); } final ConfigType configType = getConfigType(configId); CrawlingConfig config = null; if (logger.isDebugEnabled()) { logger.debug("configType: " + configType + ", configId: " + configId); } if (ConfigType.WEB == configType) { final WebCrawlingConfigService webCrawlingConfigService = SingletonS2Container .getComponent(WebCrawlingConfigService.class); config = webCrawlingConfigService .getWebCrawlingConfig(getId(configId)); } else if (ConfigType.FILE == configType) { final FileCrawlingConfigService fileCrawlingConfigService = SingletonS2Container .getComponent(FileCrawlingConfigService.class); config = fileCrawlingConfigService .getFileCrawlingConfig(getId(configId)); } else if (ConfigType.DATA == configType) { final DataCrawlingConfigService dataCrawlingConfigService = SingletonS2Container .getComponent(DataCrawlingConfigService.class); config = dataCrawlingConfigService .getDataCrawlingConfig(getId(configId)); } if (config == null) { throw new FessSystemException("No crawlingConfig: " + configIdObj); } final String url = (String) doc.get(systemHelper.urlField); final S2RobotClientFactory robotClientFactory = SingletonS2Container .getComponent(S2RobotClientFactory.class); config.initializeClientFactory(robotClientFactory); final S2RobotClient client = robotClientFactory.getClient(url); if (client == null) { throw new FessSystemException("No S2RobotClient: " + configIdObj + ", url: " + url); } final ResponseData responseData = client.doGet(url); final HttpServletResponse response = ResponseUtil.getResponse(); writeFileName(response, responseData); writeContentType(response, responseData); writeNoCache(response, responseData); InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(responseData.getResponseBody()); os = new BufferedOutputStream(response.getOutputStream()); StreamUtil.drain(is, os); os.flush(); } catch (final IOException e) { if (!"ClientAbortException".equals(e.getClass().getSimpleName())) { throw new FessSystemException( "Failed to write a content. configId: " + configIdObj + ", url: " + url, e); } } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } if (logger.isDebugEnabled()) { logger.debug("Finished to write " + url); } }
diff --git a/src/me/libraryaddict/Hungergames/Utilities/MapLoader.java b/src/me/libraryaddict/Hungergames/Utilities/MapLoader.java index 51c27a6..d420d41 100644 --- a/src/me/libraryaddict/Hungergames/Utilities/MapLoader.java +++ b/src/me/libraryaddict/Hungergames/Utilities/MapLoader.java @@ -1,136 +1,138 @@ package me.libraryaddict.Hungergames.Utilities; 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.Collections; import java.util.List; import java.util.Random; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.craftbukkit.v1_5_R3.CraftServer; import me.libraryaddict.Hungergames.Hungergames; import me.libraryaddict.Hungergames.Managers.ConfigManager; import me.libraryaddict.Hungergames.Managers.TranslationManager; import me.libraryaddict.Hungergames.Types.HungergamesApi; public class MapLoader { public static void loadMap() { Hungergames hg = HungergamesApi.getHungergames(); File mapConfig = new File(hg.getDataFolder() + "\\map.yml"); try { if (!mapConfig.exists()) mapConfig.createNewFile(); YamlConfiguration config = YamlConfiguration.loadConfiguration(mapConfig); if (!config.contains("MapPath")) { config.set("MapPath", hg.getDataFolder().getAbsoluteFile().getParentFile().getParent() + "\\Maps\\"); config.save(mapConfig); } if (!config.contains("UseMaps")) { config.set("UseMaps", false); config.save(mapConfig); } String worldName = ((CraftServer) hg.getServer()).getServer().getPropertyManager().getString("level-name", "world"); File worldFolder = new File(hg.getDataFolder().getAbsoluteFile().getParentFile().getParent().toString() + "\\" + worldName); + if (!worldFolder.exists()) + worldFolder.mkdirs(); if (config.getBoolean("UseMaps")) { clear(worldFolder); File mapFolder = new File(config.getString("MapPath")); loadMap(mapFolder, worldFolder, config); } } catch (IOException e) { e.printStackTrace(); } } private static void loadMapConfiguration(File worldConfig) { ConfigManager configManager = HungergamesApi.getConfigManager(); TranslationManager tm = HungergamesApi.getTranslationManager(); try { System.out.print(tm.getLoggerMapConfigNowLoading()); if (!worldConfig.exists()) { System.out.print(tm.getLoggerMapConfigNotFound()); return; } YamlConfiguration config = YamlConfiguration.loadConfiguration(worldConfig); System.out.print(tm.getLoggerMapConfigLoaded()); if (config.contains("BorderSize")) { configManager.setBorderSize(config.getInt("BorderSize")); System.out.print(String.format(tm.getLoggerMapConfigChangedBorderSize(), config.getInt("BorderSize"))); } } catch (Exception ex) { ex.printStackTrace(); } } private static void loadMap(File mapDir, File dest, YamlConfiguration config) { TranslationManager tm = HungergamesApi.getTranslationManager(); System.out.print(String.format(tm.getLoggerNowAttemptingToLoadAMap(), mapDir.toString())); List<File> maps = new ArrayList<File>(); if (dest.exists()) { for (File file : dest.listFiles()) if (file.isDirectory()) { if (new File(file.toString() + "\\level.dat").exists()) maps.add(file); } } if (maps.size() > 0) { Collections.shuffle(maps, new Random()); File toLoad = maps.get(0); copy(toLoad, dest); System.out.print(String.format(HungergamesApi.getTranslationManager().getLoggerSucessfullyLoadedMap(), toLoad.getName())); loadMapConfiguration(new File(dest.toString() + "\\config.yml")); } else System.out.print(String.format(HungergamesApi.getTranslationManager().getLoggerNoMapsFound(), mapDir.toString())); } public static void copyFile(File source, File destination) throws IOException { if (source.getName().equalsIgnoreCase("uid.dat")) return; if (destination.isDirectory()) destination = new File(destination, source.getName()); FileInputStream input = new FileInputStream(source); copyFile(input, destination); } public static void copyFile(InputStream input, File destination) throws IOException { OutputStream output = null; output = new FileOutputStream(destination); byte[] buffer = new byte[1024]; int bytesRead = input.read(buffer); while (bytesRead >= 0) { output.write(buffer, 0, bytesRead); bytesRead = input.read(buffer); } input.close(); output.close(); } public static void copy(File from, File dest) { if (from.isFile()) { try { copyFile(from, dest); } catch (IOException e) { e.printStackTrace(); } } else for (File f : from.listFiles()) copy(f, dest); } public static void clear(File file) { if (file.isFile()) file.delete(); else for (File f : file.listFiles()) clear(f); } }
true
true
public static void loadMap() { Hungergames hg = HungergamesApi.getHungergames(); File mapConfig = new File(hg.getDataFolder() + "\\map.yml"); try { if (!mapConfig.exists()) mapConfig.createNewFile(); YamlConfiguration config = YamlConfiguration.loadConfiguration(mapConfig); if (!config.contains("MapPath")) { config.set("MapPath", hg.getDataFolder().getAbsoluteFile().getParentFile().getParent() + "\\Maps\\"); config.save(mapConfig); } if (!config.contains("UseMaps")) { config.set("UseMaps", false); config.save(mapConfig); } String worldName = ((CraftServer) hg.getServer()).getServer().getPropertyManager().getString("level-name", "world"); File worldFolder = new File(hg.getDataFolder().getAbsoluteFile().getParentFile().getParent().toString() + "\\" + worldName); if (config.getBoolean("UseMaps")) { clear(worldFolder); File mapFolder = new File(config.getString("MapPath")); loadMap(mapFolder, worldFolder, config); } } catch (IOException e) { e.printStackTrace(); } }
public static void loadMap() { Hungergames hg = HungergamesApi.getHungergames(); File mapConfig = new File(hg.getDataFolder() + "\\map.yml"); try { if (!mapConfig.exists()) mapConfig.createNewFile(); YamlConfiguration config = YamlConfiguration.loadConfiguration(mapConfig); if (!config.contains("MapPath")) { config.set("MapPath", hg.getDataFolder().getAbsoluteFile().getParentFile().getParent() + "\\Maps\\"); config.save(mapConfig); } if (!config.contains("UseMaps")) { config.set("UseMaps", false); config.save(mapConfig); } String worldName = ((CraftServer) hg.getServer()).getServer().getPropertyManager().getString("level-name", "world"); File worldFolder = new File(hg.getDataFolder().getAbsoluteFile().getParentFile().getParent().toString() + "\\" + worldName); if (!worldFolder.exists()) worldFolder.mkdirs(); if (config.getBoolean("UseMaps")) { clear(worldFolder); File mapFolder = new File(config.getString("MapPath")); loadMap(mapFolder, worldFolder, config); } } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/main/java/io/druid/data/input/impl/TimestampSpec.java b/src/main/java/io/druid/data/input/impl/TimestampSpec.java index 7565fce..03aebf9 100644 --- a/src/main/java/io/druid/data/input/impl/TimestampSpec.java +++ b/src/main/java/io/druid/data/input/impl/TimestampSpec.java @@ -1,50 +1,50 @@ package io.druid.data.input.impl; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Function; import com.metamx.common.parsers.ParserUtils; import org.joda.time.DateTime; import java.util.Map; /** */ public class TimestampSpec { private static final String defaultFormat = "auto"; private final String timestampColumn; private final String timestampFormat; private final Function<String, DateTime> timestampConverter; @JsonCreator public TimestampSpec( @JsonProperty("column") String timestampColumn, @JsonProperty("format") String format ) { this.timestampColumn = timestampColumn.toLowerCase(); - this.timestampFormat = format == null ? defaultFormat : format; + this.timestampFormat = format == null ? defaultFormat : format.toLowerCase(); this.timestampConverter = ParserUtils.createTimestampParser(timestampFormat); } @JsonProperty("column") public String getTimestampColumn() { return timestampColumn; } @JsonProperty("format") public String getTimestampFormat() { return timestampFormat; } public DateTime extractTimestamp(Map<String, Object> input) { final Object o = input.get(timestampColumn); return o == null ? null : timestampConverter.apply(o.toString()); } }
true
true
public TimestampSpec( @JsonProperty("column") String timestampColumn, @JsonProperty("format") String format ) { this.timestampColumn = timestampColumn.toLowerCase(); this.timestampFormat = format == null ? defaultFormat : format; this.timestampConverter = ParserUtils.createTimestampParser(timestampFormat); }
public TimestampSpec( @JsonProperty("column") String timestampColumn, @JsonProperty("format") String format ) { this.timestampColumn = timestampColumn.toLowerCase(); this.timestampFormat = format == null ? defaultFormat : format.toLowerCase(); this.timestampConverter = ParserUtils.createTimestampParser(timestampFormat); }
diff --git a/src/main/java/org/bukkit/command/Command.java b/src/main/java/org/bukkit/command/Command.java index a04c8701..073f1acf 100644 --- a/src/main/java/org/bukkit/command/Command.java +++ b/src/main/java/org/bukkit/command/Command.java @@ -1,371 +1,371 @@ package org.bukkit.command; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.permissions.Permissible; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.util.StringUtil; import com.google.common.collect.ImmutableList; /** * Represents a Command, which executes various tasks upon user input */ public abstract class Command { private final String name; private String nextLabel; private String label; private List<String> aliases; private List<String> activeAliases; private CommandMap commandMap = null; protected String description = ""; protected String usageMessage; private String permission; private String permissionMessage; protected Command(String name) { this(name, "", "/" + name, new ArrayList<String>()); } protected Command(String name, String description, String usageMessage, List<String> aliases) { this.name = name; this.nextLabel = name; this.label = name; this.description = description; this.usageMessage = usageMessage; this.aliases = aliases; this.activeAliases = new ArrayList<String>(aliases); } /** * Executes the command, returning its success * * @param sender Source object which is executing this command * @param commandLabel The alias of the command used * @param args All arguments passed to the command, split via ' ' * @return true if the command was successful, otherwise false */ public abstract boolean execute(CommandSender sender, String commandLabel, String[] args); /** * @deprecated This method is not supported and returns null */ @Deprecated public List<String> tabComplete(CommandSender sender, String[] args) { return null; } /** * Executed on tab completion for this command, returning a list of options * the player can tab through. * * @param sender Source object which is executing this command * @param alias the alias being used * @param args All arguments passed to the command, split via ' ' * @return a list of tab-completions for the specified arguments. This will never be null. List may be immutable. * @throws IllegalArgumentException if sender, alias, or args is null */ public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { Validate.notNull(sender, "Sender cannot be null"); Validate.notNull(args, "Arguments cannot be null"); Validate.notNull(alias, "Alias cannot be null"); if (args.length == 0) { return ImmutableList.of(); } String lastWord = args[args.length - 1]; Player senderPlayer = sender instanceof Player ? (Player) sender : null; ArrayList<String> matchedPlayers = new ArrayList<String>(); for (Player player : sender.getServer().getOnlinePlayers()) { String name = player.getName(); if ((senderPlayer == null || senderPlayer.canSee(player)) && StringUtil.startsWithIgnoreCase(name, lastWord)) { matchedPlayers.add(name); } } Collections.sort(matchedPlayers, String.CASE_INSENSITIVE_ORDER); return matchedPlayers; } /** * Returns the name of this command * * @return Name of this command */ public String getName() { return name; } /** * Gets the permission required by users to be able to perform this command * * @return Permission name, or null if none */ public String getPermission() { return permission; } /** * Sets the permission required by users to be able to perform this command * * @param permission Permission name or null */ public void setPermission(String permission) { this.permission = permission; } /** * Tests the given {@link CommandSender} to see if they can perform this command. * <p> * If they do not have permission, they will be informed that they cannot do this. * * @param target User to test * @return true if they can use it, otherwise false */ public boolean testPermission(CommandSender target) { if (testPermissionSilent(target)) { return true; } if (permissionMessage == null) { target.sendMessage(ChatColor.RED + "I'm sorry, but you do not have permission to perform this command. Please contact the server administrators if you believe that this is in error."); } else if (permissionMessage.length() != 0) { for (String line : permissionMessage.replace("<permission>", permission).split("\n")) { target.sendMessage(line); } } return false; } /** * Tests the given {@link CommandSender} to see if they can perform this command. * <p> * No error is sent to the sender. * * @param target User to test * @return true if they can use it, otherwise false */ public boolean testPermissionSilent(CommandSender target) { if ((permission == null) || (permission.length() == 0)) { return true; } for (String p : permission.split(";")) { if (target.hasPermission(p)) { return true; } } return false; } /** * Returns the current lable for this command * * @return Label of this command or null if not registered */ public String getLabel() { return label; } /** * Sets the label of this command * If the command is currently registered the label change will only take effect after * its been reregistered e.g. after a /reload * * @param name The command's name * @return returns true if the name change happened instantly or false if it was scheduled for reregistration */ public boolean setLabel(String name) { this.nextLabel = name; if (!isRegistered()) { this.label = name; return true; } return false; } /** * Registers this command to a CommandMap * Once called it only allows changes the registered CommandMap * * @param commandMap the CommandMap to register this command to * @return true if the registration was successful (the current registered CommandMap was the passed CommandMap or null) false otherwise */ public boolean register(CommandMap commandMap) { if (allowChangesFrom(commandMap)) { this.commandMap = commandMap; return true; } return false; } /** * Unregisters this command from the passed CommandMap applying any outstanding changes * * @param commandMap the CommandMap to unregister * @return true if the unregistration was successfull (the current registered CommandMap was the passed CommandMap or null) false otherwise */ public boolean unregister(CommandMap commandMap) { if (allowChangesFrom(commandMap)) { this.commandMap = null; this.activeAliases = new ArrayList<String>(this.aliases); this.label = this.nextLabel; return true; } return false; } private boolean allowChangesFrom(CommandMap commandMap) { return (null == this.commandMap || this.commandMap == commandMap); } /** * Returns the current registered state of this command * * @return true if this command is currently registered false otherwise */ public boolean isRegistered() { return (null != this.commandMap); } /** * Returns a list of active aliases of this command * * @return List of aliases */ public List<String> getAliases() { return activeAliases; } /** * Returns a message to be displayed on a failed permission check for this command * * @return Permission check failed message */ public String getPermissionMessage() { return permissionMessage; } /** * Gets a brief description of this command * * @return Description of this command */ public String getDescription() { return description; } /** * Gets an example usage of this command * * @return One or more example usages */ public String getUsage() { return usageMessage; } /** * Sets the list of aliases to request on registration for this command. * This is not effective outside of defining aliases in the {@link * PluginDescriptionFile#getCommands()} (under the * `<code>aliases</code>' node) is equivalent to this method. * * @param aliases aliases to register to this command * @return this command object, for chaining */ public Command setAliases(List<String> aliases) { this.aliases = aliases; if (!isRegistered()) { this.activeAliases = new ArrayList<String>(aliases); } return this; } /** * Sets a brief description of this command. Defining a description in the * {@link PluginDescriptionFile#getCommands()} (under the * `<code>description</code>' node) is equivalent to this method. * * @param description new command description * @return this command object, for chaining */ public Command setDescription(String description) { this.description = description; return this; } /** * Sets the message sent when a permission check fails * * @param permissionMessage new permission message, null to indicate * default message, or an empty string to indicate no message * @return this command object, for chaining */ public Command setPermissionMessage(String permissionMessage) { this.permissionMessage = permissionMessage; return this; } /** * Sets the example usage of this command * * @param usage new example usage * @return this command object, for chaining */ public Command setUsage(String usage) { this.usageMessage = usage; return this; } public static void broadcastCommandMessage(CommandSender source, String message) { broadcastCommandMessage(source, message, true); } public static void broadcastCommandMessage(CommandSender source, String message, boolean sendToSource) { String result = source.getName() + ": " + message; if (source instanceof BlockCommandSender && ((BlockCommandSender) source).getBlock().getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { Bukkit.getConsoleSender().sendMessage(result); return; } Set<Permissible> users = Bukkit.getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_ADMINISTRATIVE); - String colored = ChatColor.GRAY + "" + ChatColor.ITALIC + "[" + result + "]"; + String colored = ChatColor.GRAY + "" + ChatColor.ITALIC + "[" + result + ChatColor.GRAY + ChatColor.ITALIC + "]"; if (sendToSource && !(source instanceof ConsoleCommandSender)) { source.sendMessage(message); } for (Permissible user : users) { if (user instanceof CommandSender) { CommandSender target = (CommandSender) user; if (target instanceof ConsoleCommandSender) { target.sendMessage(result); } else if (target != source) { target.sendMessage(colored); } } } } @Override public String toString() { return getClass().getName() + '(' + name + ')'; } }
true
true
public static void broadcastCommandMessage(CommandSender source, String message, boolean sendToSource) { String result = source.getName() + ": " + message; if (source instanceof BlockCommandSender && ((BlockCommandSender) source).getBlock().getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { Bukkit.getConsoleSender().sendMessage(result); return; } Set<Permissible> users = Bukkit.getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_ADMINISTRATIVE); String colored = ChatColor.GRAY + "" + ChatColor.ITALIC + "[" + result + "]"; if (sendToSource && !(source instanceof ConsoleCommandSender)) { source.sendMessage(message); } for (Permissible user : users) { if (user instanceof CommandSender) { CommandSender target = (CommandSender) user; if (target instanceof ConsoleCommandSender) { target.sendMessage(result); } else if (target != source) { target.sendMessage(colored); } } } }
public static void broadcastCommandMessage(CommandSender source, String message, boolean sendToSource) { String result = source.getName() + ": " + message; if (source instanceof BlockCommandSender && ((BlockCommandSender) source).getBlock().getWorld().getGameRuleValue("commandBlockOutput").equalsIgnoreCase("false")) { Bukkit.getConsoleSender().sendMessage(result); return; } Set<Permissible> users = Bukkit.getPluginManager().getPermissionSubscriptions(Server.BROADCAST_CHANNEL_ADMINISTRATIVE); String colored = ChatColor.GRAY + "" + ChatColor.ITALIC + "[" + result + ChatColor.GRAY + ChatColor.ITALIC + "]"; if (sendToSource && !(source instanceof ConsoleCommandSender)) { source.sendMessage(message); } for (Permissible user : users) { if (user instanceof CommandSender) { CommandSender target = (CommandSender) user; if (target instanceof ConsoleCommandSender) { target.sendMessage(result); } else if (target != source) { target.sendMessage(colored); } } } }
diff --git a/src/net/aufdemrand/denizen/CommandExecuter.java b/src/net/aufdemrand/denizen/CommandExecuter.java index 5c02bc15c..05eae40d0 100644 --- a/src/net/aufdemrand/denizen/CommandExecuter.java +++ b/src/net/aufdemrand/denizen/CommandExecuter.java @@ -1,332 +1,332 @@ package net.aufdemrand.denizen; import java.util.ArrayList; import java.util.List; import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.npc.NPC; import net.citizensnpcs.trait.LookClose; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class CommandExecuter { public static enum Command { WAIT, ZAP, SPAWN, CHANGE, WEATHER, EFFECT, GIVE, TAKE, HEAL, TELEPORT, STRIKE, WALK, REMEMBER, RESPAWN, PERMISS, EXECUTE, SHOUT, WHISPER, CHAT, ANNOUNCE, GRANT, HINT, RETURN, LOOK, WALKTO, FINISH, FOLLOW, CAST, NARRATE, SWITCH, PRESS, HURT, REFUSE, WAITING, RESET, FAIL } public void execute(Player thePlayer, String theStep) { // Syntax of theStep // 0 Denizen ID; 1 Script Name; 2 Step Number; 3 Time added to Queue; 4 Command Denizen plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen"); String[] executerArgs = theStep.split(";"); String[] commandArgs = executerArgs[4].split(" "); if (commandArgs[0].startsWith("^")) commandArgs[0] = commandArgs[0].substring(1); switch (Command.valueOf(commandArgs[0].toUpperCase())) { case ZAP: // ZAP [Optional Step # to advance to] if (commandArgs.length == 1) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + ".Current Step", Integer.parseInt(executerArgs[2]) + 1); plugin.saveConfig(); } else { plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + ".Current Step", Integer.parseInt(commandArgs[1])); plugin.saveConfig(); } break; case SPAWN: // SPAWN [MOB NAME] [AMOUNT] (Location Bookmark) Location theSpawnLoc = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation(); if (commandArgs.length > 3) theSpawnLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[3], "Location"); if (theSpawnLoc != null) { for (int cx = 1; cx < Integer.valueOf("commandArgs[2]"); cx++) { thePlayer.getWorld().spawnCreature(theSpawnLoc, EntityType.valueOf(commandArgs[1])); } } break; case SWITCH: // SWITCH [Block Bookmark] ON|OFF Location switchLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Block"); if (switchLoc.getBlock().getType() == Material.LEVER) { World theWorld = switchLoc.getWorld(); net.minecraft.server.Block.LEVER.interact(((CraftWorld)theWorld).getHandle(), switchLoc.getBlockX(), switchLoc.getBlockY(), switchLoc.getBlockZ(), null); } break; case PRESS: // SWITCH [Block Bookmark] ON|OFF Location pressLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Block"); if (pressLoc.getBlock().getType() == Material.STONE_BUTTON) { World theWorld = pressLoc.getWorld(); net.minecraft.server.Block.STONE_BUTTON.interact(((CraftWorld)theWorld).getHandle(), pressLoc.getBlockX(), pressLoc.getBlockY(), pressLoc.getBlockZ(), null); } break; case WEATHER: // WEATHER [Sunny|Stormy|Precipitation] (Duration for Stormy/Rainy) if (commandArgs[1].equalsIgnoreCase("sunny")) { thePlayer.getWorld().setStorm(false); } else if (commandArgs[1].equalsIgnoreCase("stormy")) { thePlayer.getWorld().setThundering(true); } else if (commandArgs[1].equalsIgnoreCase("precipitation")) { thePlayer.getWorld().setStorm(true); } break; case CAST: // CAST [POTION_TYPE] [DURATION] [AMPLIFIER] thePlayer.addPotionEffect(new PotionEffect( PotionEffectType.getByName(commandArgs[1]), Integer.valueOf(commandArgs[2]) * 20, Integer.valueOf(commandArgs[3]))); break; case EFFECT: // EFFECT [EFFECT_TYPE] (Location Bookmark) // PLAYER INTERACTION case LOOK: // ENG if (commandArgs[1].equalsIgnoreCase("CLOSE")) { if (!CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle()) CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle(); } else if (commandArgs[1].equalsIgnoreCase("AWAY")) { if (CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle()) CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle(); } else if (!commandArgs[1].equalsIgnoreCase("AWAY") && !commandArgs[1].equalsIgnoreCase("CLOSE")) { NPC denizenLooking = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Location lookLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); denizenLooking.getBukkitEntity().getLocation().setPitch(lookLoc.getPitch()); denizenLooking.getBukkitEntity().getLocation().setYaw(lookLoc.getYaw()); } break; case GIVE: // GIVE [Item:Data] [Amount] [ENCHANTMENT_TYPE] ItemStack giveItem = new ItemStack(Material.getMaterial(commandArgs[1].toUpperCase())); if (commandArgs.length > 1) giveItem.setAmount(Integer.valueOf(commandArgs[2])); else giveItem.setAmount(1); CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getWorld() .dropItem(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation().add( CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation().getDirection().multiply(1.1)), giveItem); break; case TAKE: // TAKE [Item] [Amount] or TAKE ITEM_IN_HAND or TAKE MONEY [Amount] if (commandArgs[1].equalsIgnoreCase("MONEY")) { double playerMoneyAmt = Denizen.denizenEcon.getBalance(thePlayer.getName()); double amtToTake = Double.valueOf(commandArgs[2]); if (amtToTake > playerMoneyAmt) amtToTake = playerMoneyAmt; Denizen.denizenEcon.withdrawPlayer(thePlayer.getName(), amtToTake); } else if (commandArgs[1].equalsIgnoreCase("ITEMINHAND")) { thePlayer.setItemInHand(new ItemStack(Material.AIR)); } else { ItemStack itemToTake = new ItemStack(Material.valueOf(commandArgs[1])); if (commandArgs.length > 2) itemToTake.setAmount(Integer.valueOf(commandArgs[2])); else itemToTake.setAmount(1); thePlayer.getInventory().removeItem(itemToTake); } break; case HEAL: // HEAL or HEAL [# of Hearts] case HURT: case TELEPORT: // TELEPORT [Location Notable] thePlayer.teleport(Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "location")); case STRIKE: // STRIKE Strikes lightning on the player, with damage. thePlayer.getWorld().strikeLightning(thePlayer.getLocation()); break; // DENIZEN INTERACTION case WALK: // WALK Z(-NORTH(2)/+SOUTH(0)) X(-WEST(1)/+EAST(3)) Y (+UP/-DOWN) NPC theDenizenToWalk = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Denizen.previousDenizenLocation.put(theDenizenToWalk, theDenizenToWalk.getBukkitEntity().getLocation()); if (!commandArgs[1].isEmpty()) theDenizenToWalk.getAI().setDestination(theDenizenToWalk.getBukkitEntity().getLocation() .add(Double.parseDouble(commandArgs[2]), Double.parseDouble(commandArgs[3]), Double.parseDouble(commandArgs[1]))); break; case WALKTO: // WALKTO [Location Bookmark] NPC denizenWalking = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Location walkLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); Denizen.previousDenizenLocation.put(denizenWalking, denizenWalking.getBukkitEntity().getLocation()); denizenWalking.getAI().setDestination(walkLoc); break; case RETURN: NPC theDenizenToReturn = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (Denizen.previousDenizenLocation.containsKey(theDenizenToReturn)) theDenizenToReturn.getAI().setDestination(Denizen.previousDenizenLocation. get(theDenizenToReturn)); break; case FINISH: int finishes = plugin.getConfig().getInt("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Completed", 0); finishes++; plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Completed", finishes); plugin.saveConfig(); break; case FAIL: plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Failed", true); plugin.saveConfig(); break; case REMEMBER: // REMEMBER [CHAT|LOCATION|INVENTORY] break; case FOLLOW: // FOLLOW PLAYER|NOBODY NPC theDenizenFollowing = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (commandArgs[1].equalsIgnoreCase("PLAYER")) { theDenizenFollowing.getAI().setTarget(thePlayer, false); } if (commandArgs[1].equalsIgnoreCase("NOBODY")) { theDenizenFollowing.getAI().cancelDestination(); } break; case RESPAWN: // RESPAWN [Location Notable] Location respawnLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); NPC respawnDenizen = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Denizen.previousDenizenLocation.put(respawnDenizen, respawnDenizen.getBukkitEntity().getLocation()); respawnDenizen.getBukkitEntity().getWorld().playEffect(respawnDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2); respawnDenizen.despawn(); respawnDenizen.spawn(respawnLoc); respawnDenizen.getBukkitEntity().getWorld().playEffect(respawnDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2); break; case PERMISS: // PERMISS [Permission Node] Denizen.denizenPerms.playerAdd(thePlayer, commandArgs[1]); break; case REFUSE: // PERMISS [Permission Node] Denizen.denizenPerms.playerRemove(thePlayer, commandArgs[1]); break; case EXECUTE: // EXECUTE ASPLAYER [Command to Execute] String[] executeCommand = executerArgs[4].split(" ", 3); NPC theDenizenExecuting = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (commandArgs[1].equalsIgnoreCase("ASPLAYER")) { thePlayer.performCommand(executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } if (commandArgs[1].equalsIgnoreCase("ASNPC")) { ((Player) theDenizenExecuting.getBukkitEntity()).performCommand(executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } if (commandArgs[1].equalsIgnoreCase("ASSERVER")) { plugin.getServer().dispatchCommand(Bukkit.getConsoleSender(), executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } break; // SHOUT can be heard by players within 100 blocks. // WHISPER can only be heard by the player interacting with. // CHAT can be heard by the player, and players within 5 blocks. // NARRARATE can only be heard by the player and is not branded by the NPC. // ANNOUNCE can be heard by the entire server. case WHISPER: // ZAP [Optional Step # to advance to] case NARRATE: // ZAP [Optional Step # to advance to] if (executerArgs[4].split(" ", 2)[1].startsWith("*")) thePlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "").replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); else thePlayer.sendMessage(executerArgs[4].split(" ", 2)[1].replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); break; case SHOUT: // ZAP [Optional Step # to advance to] case CHAT: // CHAT [Message] NPC theDenizenChatting = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (executerArgs[4].split(" ", 2)[1].startsWith("*")) thePlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "")); - else thePlayer.sendMessage(plugin.getConfig().getString("npc_chat_to_player").replace("<TEXT>", executerArgs[4].split(" ", 2)[1]).replace("<PLAYER>", thePlayer.getDisplayName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); + else thePlayer.sendMessage(plugin.getConfig().getString("npc_chat_to_player").replace("<TEXT>", executerArgs[4].split(" ", 2)[1]).replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); for (Player eachPlayer : Denizen.getPlayer.getInRange(theDenizenChatting.getBukkitEntity(), plugin.getConfig().getInt("npc_to_player_chat_range_in_blocks", 15))) { if (eachPlayer != thePlayer) { if (executerArgs[4].split(" ", 2)[1].startsWith("*")) eachPlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "")); - else eachPlayer.sendMessage(plugin.getConfig().getString("npc_chat_to_player_bystander").replace("<TEXT>", executerArgs[4].split(" ", 2)[1]).replace("<PLAYER>", thePlayer.getDisplayName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); + else eachPlayer.sendMessage(plugin.getConfig().getString("npc_chat_to_player_bystander").replace("<TEXT>", executerArgs[4].split(" ", 2)[1]).replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); } } break; case ANNOUNCE: // ANNOUNCE [Message] // NOTABLES case RESET: // RESET FINISH(ED) [Name of Script] or RESET FAIL(ED) [NAME OF SCRIPT] String nameOfScript = executerArgs[4].split(" ", 3)[2]; if (commandArgs[1].equalsIgnoreCase("FINISH") || commandArgs[1].equalsIgnoreCase("FINISHED")) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + nameOfScript + "." + "Completed", 0); plugin.saveConfig(); } if (commandArgs[1].equalsIgnoreCase("FAIL") || commandArgs[1].equalsIgnoreCase("FAILED")) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + nameOfScript + "." + "Failed", false); plugin.saveConfig(); } break; case CHANGE: break; case WAIT: List<String> CurrentPlayerQue = new ArrayList<String>(); if (Denizen.playerQue.get(thePlayer) != null) CurrentPlayerQue = Denizen.playerQue.get(thePlayer); Denizen.playerQue.remove(thePlayer); // Should keep the talk queue from triggering mid-add Long timeDelay = Long.parseLong(commandArgs[1]) * 1000; String timeWithDelay = String.valueOf(System.currentTimeMillis() + timeDelay); CurrentPlayerQue.add(1, "0;none;0;" + timeWithDelay + ";WAITING"); Denizen.playerQue.put(thePlayer, CurrentPlayerQue); break; case WAITING: // ...and we're waiting. break; default: break; } } }
false
true
public void execute(Player thePlayer, String theStep) { // Syntax of theStep // 0 Denizen ID; 1 Script Name; 2 Step Number; 3 Time added to Queue; 4 Command Denizen plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen"); String[] executerArgs = theStep.split(";"); String[] commandArgs = executerArgs[4].split(" "); if (commandArgs[0].startsWith("^")) commandArgs[0] = commandArgs[0].substring(1); switch (Command.valueOf(commandArgs[0].toUpperCase())) { case ZAP: // ZAP [Optional Step # to advance to] if (commandArgs.length == 1) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + ".Current Step", Integer.parseInt(executerArgs[2]) + 1); plugin.saveConfig(); } else { plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + ".Current Step", Integer.parseInt(commandArgs[1])); plugin.saveConfig(); } break; case SPAWN: // SPAWN [MOB NAME] [AMOUNT] (Location Bookmark) Location theSpawnLoc = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation(); if (commandArgs.length > 3) theSpawnLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[3], "Location"); if (theSpawnLoc != null) { for (int cx = 1; cx < Integer.valueOf("commandArgs[2]"); cx++) { thePlayer.getWorld().spawnCreature(theSpawnLoc, EntityType.valueOf(commandArgs[1])); } } break; case SWITCH: // SWITCH [Block Bookmark] ON|OFF Location switchLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Block"); if (switchLoc.getBlock().getType() == Material.LEVER) { World theWorld = switchLoc.getWorld(); net.minecraft.server.Block.LEVER.interact(((CraftWorld)theWorld).getHandle(), switchLoc.getBlockX(), switchLoc.getBlockY(), switchLoc.getBlockZ(), null); } break; case PRESS: // SWITCH [Block Bookmark] ON|OFF Location pressLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Block"); if (pressLoc.getBlock().getType() == Material.STONE_BUTTON) { World theWorld = pressLoc.getWorld(); net.minecraft.server.Block.STONE_BUTTON.interact(((CraftWorld)theWorld).getHandle(), pressLoc.getBlockX(), pressLoc.getBlockY(), pressLoc.getBlockZ(), null); } break; case WEATHER: // WEATHER [Sunny|Stormy|Precipitation] (Duration for Stormy/Rainy) if (commandArgs[1].equalsIgnoreCase("sunny")) { thePlayer.getWorld().setStorm(false); } else if (commandArgs[1].equalsIgnoreCase("stormy")) { thePlayer.getWorld().setThundering(true); } else if (commandArgs[1].equalsIgnoreCase("precipitation")) { thePlayer.getWorld().setStorm(true); } break; case CAST: // CAST [POTION_TYPE] [DURATION] [AMPLIFIER] thePlayer.addPotionEffect(new PotionEffect( PotionEffectType.getByName(commandArgs[1]), Integer.valueOf(commandArgs[2]) * 20, Integer.valueOf(commandArgs[3]))); break; case EFFECT: // EFFECT [EFFECT_TYPE] (Location Bookmark) // PLAYER INTERACTION case LOOK: // ENG if (commandArgs[1].equalsIgnoreCase("CLOSE")) { if (!CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle()) CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle(); } else if (commandArgs[1].equalsIgnoreCase("AWAY")) { if (CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle()) CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle(); } else if (!commandArgs[1].equalsIgnoreCase("AWAY") && !commandArgs[1].equalsIgnoreCase("CLOSE")) { NPC denizenLooking = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Location lookLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); denizenLooking.getBukkitEntity().getLocation().setPitch(lookLoc.getPitch()); denizenLooking.getBukkitEntity().getLocation().setYaw(lookLoc.getYaw()); } break; case GIVE: // GIVE [Item:Data] [Amount] [ENCHANTMENT_TYPE] ItemStack giveItem = new ItemStack(Material.getMaterial(commandArgs[1].toUpperCase())); if (commandArgs.length > 1) giveItem.setAmount(Integer.valueOf(commandArgs[2])); else giveItem.setAmount(1); CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getWorld() .dropItem(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation().add( CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation().getDirection().multiply(1.1)), giveItem); break; case TAKE: // TAKE [Item] [Amount] or TAKE ITEM_IN_HAND or TAKE MONEY [Amount] if (commandArgs[1].equalsIgnoreCase("MONEY")) { double playerMoneyAmt = Denizen.denizenEcon.getBalance(thePlayer.getName()); double amtToTake = Double.valueOf(commandArgs[2]); if (amtToTake > playerMoneyAmt) amtToTake = playerMoneyAmt; Denizen.denizenEcon.withdrawPlayer(thePlayer.getName(), amtToTake); } else if (commandArgs[1].equalsIgnoreCase("ITEMINHAND")) { thePlayer.setItemInHand(new ItemStack(Material.AIR)); } else { ItemStack itemToTake = new ItemStack(Material.valueOf(commandArgs[1])); if (commandArgs.length > 2) itemToTake.setAmount(Integer.valueOf(commandArgs[2])); else itemToTake.setAmount(1); thePlayer.getInventory().removeItem(itemToTake); } break; case HEAL: // HEAL or HEAL [# of Hearts] case HURT: case TELEPORT: // TELEPORT [Location Notable] thePlayer.teleport(Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "location")); case STRIKE: // STRIKE Strikes lightning on the player, with damage. thePlayer.getWorld().strikeLightning(thePlayer.getLocation()); break; // DENIZEN INTERACTION case WALK: // WALK Z(-NORTH(2)/+SOUTH(0)) X(-WEST(1)/+EAST(3)) Y (+UP/-DOWN) NPC theDenizenToWalk = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Denizen.previousDenizenLocation.put(theDenizenToWalk, theDenizenToWalk.getBukkitEntity().getLocation()); if (!commandArgs[1].isEmpty()) theDenizenToWalk.getAI().setDestination(theDenizenToWalk.getBukkitEntity().getLocation() .add(Double.parseDouble(commandArgs[2]), Double.parseDouble(commandArgs[3]), Double.parseDouble(commandArgs[1]))); break; case WALKTO: // WALKTO [Location Bookmark] NPC denizenWalking = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Location walkLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); Denizen.previousDenizenLocation.put(denizenWalking, denizenWalking.getBukkitEntity().getLocation()); denizenWalking.getAI().setDestination(walkLoc); break; case RETURN: NPC theDenizenToReturn = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (Denizen.previousDenizenLocation.containsKey(theDenizenToReturn)) theDenizenToReturn.getAI().setDestination(Denizen.previousDenizenLocation. get(theDenizenToReturn)); break; case FINISH: int finishes = plugin.getConfig().getInt("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Completed", 0); finishes++; plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Completed", finishes); plugin.saveConfig(); break; case FAIL: plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Failed", true); plugin.saveConfig(); break; case REMEMBER: // REMEMBER [CHAT|LOCATION|INVENTORY] break; case FOLLOW: // FOLLOW PLAYER|NOBODY NPC theDenizenFollowing = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (commandArgs[1].equalsIgnoreCase("PLAYER")) { theDenizenFollowing.getAI().setTarget(thePlayer, false); } if (commandArgs[1].equalsIgnoreCase("NOBODY")) { theDenizenFollowing.getAI().cancelDestination(); } break; case RESPAWN: // RESPAWN [Location Notable] Location respawnLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); NPC respawnDenizen = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Denizen.previousDenizenLocation.put(respawnDenizen, respawnDenizen.getBukkitEntity().getLocation()); respawnDenizen.getBukkitEntity().getWorld().playEffect(respawnDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2); respawnDenizen.despawn(); respawnDenizen.spawn(respawnLoc); respawnDenizen.getBukkitEntity().getWorld().playEffect(respawnDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2); break; case PERMISS: // PERMISS [Permission Node] Denizen.denizenPerms.playerAdd(thePlayer, commandArgs[1]); break; case REFUSE: // PERMISS [Permission Node] Denizen.denizenPerms.playerRemove(thePlayer, commandArgs[1]); break; case EXECUTE: // EXECUTE ASPLAYER [Command to Execute] String[] executeCommand = executerArgs[4].split(" ", 3); NPC theDenizenExecuting = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (commandArgs[1].equalsIgnoreCase("ASPLAYER")) { thePlayer.performCommand(executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } if (commandArgs[1].equalsIgnoreCase("ASNPC")) { ((Player) theDenizenExecuting.getBukkitEntity()).performCommand(executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } if (commandArgs[1].equalsIgnoreCase("ASSERVER")) { plugin.getServer().dispatchCommand(Bukkit.getConsoleSender(), executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } break; // SHOUT can be heard by players within 100 blocks. // WHISPER can only be heard by the player interacting with. // CHAT can be heard by the player, and players within 5 blocks. // NARRARATE can only be heard by the player and is not branded by the NPC. // ANNOUNCE can be heard by the entire server. case WHISPER: // ZAP [Optional Step # to advance to] case NARRATE: // ZAP [Optional Step # to advance to] if (executerArgs[4].split(" ", 2)[1].startsWith("*")) thePlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "").replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); else thePlayer.sendMessage(executerArgs[4].split(" ", 2)[1].replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); break; case SHOUT: // ZAP [Optional Step # to advance to] case CHAT: // CHAT [Message] NPC theDenizenChatting = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (executerArgs[4].split(" ", 2)[1].startsWith("*")) thePlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "")); else thePlayer.sendMessage(plugin.getConfig().getString("npc_chat_to_player").replace("<TEXT>", executerArgs[4].split(" ", 2)[1]).replace("<PLAYER>", thePlayer.getDisplayName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); for (Player eachPlayer : Denizen.getPlayer.getInRange(theDenizenChatting.getBukkitEntity(), plugin.getConfig().getInt("npc_to_player_chat_range_in_blocks", 15))) { if (eachPlayer != thePlayer) { if (executerArgs[4].split(" ", 2)[1].startsWith("*")) eachPlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "")); else eachPlayer.sendMessage(plugin.getConfig().getString("npc_chat_to_player_bystander").replace("<TEXT>", executerArgs[4].split(" ", 2)[1]).replace("<PLAYER>", thePlayer.getDisplayName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); } } break; case ANNOUNCE: // ANNOUNCE [Message] // NOTABLES case RESET: // RESET FINISH(ED) [Name of Script] or RESET FAIL(ED) [NAME OF SCRIPT] String nameOfScript = executerArgs[4].split(" ", 3)[2]; if (commandArgs[1].equalsIgnoreCase("FINISH") || commandArgs[1].equalsIgnoreCase("FINISHED")) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + nameOfScript + "." + "Completed", 0); plugin.saveConfig(); } if (commandArgs[1].equalsIgnoreCase("FAIL") || commandArgs[1].equalsIgnoreCase("FAILED")) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + nameOfScript + "." + "Failed", false); plugin.saveConfig(); } break; case CHANGE: break; case WAIT: List<String> CurrentPlayerQue = new ArrayList<String>(); if (Denizen.playerQue.get(thePlayer) != null) CurrentPlayerQue = Denizen.playerQue.get(thePlayer); Denizen.playerQue.remove(thePlayer); // Should keep the talk queue from triggering mid-add Long timeDelay = Long.parseLong(commandArgs[1]) * 1000; String timeWithDelay = String.valueOf(System.currentTimeMillis() + timeDelay); CurrentPlayerQue.add(1, "0;none;0;" + timeWithDelay + ";WAITING"); Denizen.playerQue.put(thePlayer, CurrentPlayerQue); break; case WAITING: // ...and we're waiting. break; default: break; } }
public void execute(Player thePlayer, String theStep) { // Syntax of theStep // 0 Denizen ID; 1 Script Name; 2 Step Number; 3 Time added to Queue; 4 Command Denizen plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen"); String[] executerArgs = theStep.split(";"); String[] commandArgs = executerArgs[4].split(" "); if (commandArgs[0].startsWith("^")) commandArgs[0] = commandArgs[0].substring(1); switch (Command.valueOf(commandArgs[0].toUpperCase())) { case ZAP: // ZAP [Optional Step # to advance to] if (commandArgs.length == 1) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + ".Current Step", Integer.parseInt(executerArgs[2]) + 1); plugin.saveConfig(); } else { plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + ".Current Step", Integer.parseInt(commandArgs[1])); plugin.saveConfig(); } break; case SPAWN: // SPAWN [MOB NAME] [AMOUNT] (Location Bookmark) Location theSpawnLoc = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation(); if (commandArgs.length > 3) theSpawnLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[3], "Location"); if (theSpawnLoc != null) { for (int cx = 1; cx < Integer.valueOf("commandArgs[2]"); cx++) { thePlayer.getWorld().spawnCreature(theSpawnLoc, EntityType.valueOf(commandArgs[1])); } } break; case SWITCH: // SWITCH [Block Bookmark] ON|OFF Location switchLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Block"); if (switchLoc.getBlock().getType() == Material.LEVER) { World theWorld = switchLoc.getWorld(); net.minecraft.server.Block.LEVER.interact(((CraftWorld)theWorld).getHandle(), switchLoc.getBlockX(), switchLoc.getBlockY(), switchLoc.getBlockZ(), null); } break; case PRESS: // SWITCH [Block Bookmark] ON|OFF Location pressLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Block"); if (pressLoc.getBlock().getType() == Material.STONE_BUTTON) { World theWorld = pressLoc.getWorld(); net.minecraft.server.Block.STONE_BUTTON.interact(((CraftWorld)theWorld).getHandle(), pressLoc.getBlockX(), pressLoc.getBlockY(), pressLoc.getBlockZ(), null); } break; case WEATHER: // WEATHER [Sunny|Stormy|Precipitation] (Duration for Stormy/Rainy) if (commandArgs[1].equalsIgnoreCase("sunny")) { thePlayer.getWorld().setStorm(false); } else if (commandArgs[1].equalsIgnoreCase("stormy")) { thePlayer.getWorld().setThundering(true); } else if (commandArgs[1].equalsIgnoreCase("precipitation")) { thePlayer.getWorld().setStorm(true); } break; case CAST: // CAST [POTION_TYPE] [DURATION] [AMPLIFIER] thePlayer.addPotionEffect(new PotionEffect( PotionEffectType.getByName(commandArgs[1]), Integer.valueOf(commandArgs[2]) * 20, Integer.valueOf(commandArgs[3]))); break; case EFFECT: // EFFECT [EFFECT_TYPE] (Location Bookmark) // PLAYER INTERACTION case LOOK: // ENG if (commandArgs[1].equalsIgnoreCase("CLOSE")) { if (!CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle()) CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle(); } else if (commandArgs[1].equalsIgnoreCase("AWAY")) { if (CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle()) CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getTrait(LookClose.class).toggle(); } else if (!commandArgs[1].equalsIgnoreCase("AWAY") && !commandArgs[1].equalsIgnoreCase("CLOSE")) { NPC denizenLooking = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Location lookLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); denizenLooking.getBukkitEntity().getLocation().setPitch(lookLoc.getPitch()); denizenLooking.getBukkitEntity().getLocation().setYaw(lookLoc.getYaw()); } break; case GIVE: // GIVE [Item:Data] [Amount] [ENCHANTMENT_TYPE] ItemStack giveItem = new ItemStack(Material.getMaterial(commandArgs[1].toUpperCase())); if (commandArgs.length > 1) giveItem.setAmount(Integer.valueOf(commandArgs[2])); else giveItem.setAmount(1); CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getWorld() .dropItem(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation().add( CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])).getBukkitEntity().getLocation().getDirection().multiply(1.1)), giveItem); break; case TAKE: // TAKE [Item] [Amount] or TAKE ITEM_IN_HAND or TAKE MONEY [Amount] if (commandArgs[1].equalsIgnoreCase("MONEY")) { double playerMoneyAmt = Denizen.denizenEcon.getBalance(thePlayer.getName()); double amtToTake = Double.valueOf(commandArgs[2]); if (amtToTake > playerMoneyAmt) amtToTake = playerMoneyAmt; Denizen.denizenEcon.withdrawPlayer(thePlayer.getName(), amtToTake); } else if (commandArgs[1].equalsIgnoreCase("ITEMINHAND")) { thePlayer.setItemInHand(new ItemStack(Material.AIR)); } else { ItemStack itemToTake = new ItemStack(Material.valueOf(commandArgs[1])); if (commandArgs.length > 2) itemToTake.setAmount(Integer.valueOf(commandArgs[2])); else itemToTake.setAmount(1); thePlayer.getInventory().removeItem(itemToTake); } break; case HEAL: // HEAL or HEAL [# of Hearts] case HURT: case TELEPORT: // TELEPORT [Location Notable] thePlayer.teleport(Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "location")); case STRIKE: // STRIKE Strikes lightning on the player, with damage. thePlayer.getWorld().strikeLightning(thePlayer.getLocation()); break; // DENIZEN INTERACTION case WALK: // WALK Z(-NORTH(2)/+SOUTH(0)) X(-WEST(1)/+EAST(3)) Y (+UP/-DOWN) NPC theDenizenToWalk = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Denizen.previousDenizenLocation.put(theDenizenToWalk, theDenizenToWalk.getBukkitEntity().getLocation()); if (!commandArgs[1].isEmpty()) theDenizenToWalk.getAI().setDestination(theDenizenToWalk.getBukkitEntity().getLocation() .add(Double.parseDouble(commandArgs[2]), Double.parseDouble(commandArgs[3]), Double.parseDouble(commandArgs[1]))); break; case WALKTO: // WALKTO [Location Bookmark] NPC denizenWalking = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Location walkLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); Denizen.previousDenizenLocation.put(denizenWalking, denizenWalking.getBukkitEntity().getLocation()); denizenWalking.getAI().setDestination(walkLoc); break; case RETURN: NPC theDenizenToReturn = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (Denizen.previousDenizenLocation.containsKey(theDenizenToReturn)) theDenizenToReturn.getAI().setDestination(Denizen.previousDenizenLocation. get(theDenizenToReturn)); break; case FINISH: int finishes = plugin.getConfig().getInt("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Completed", 0); finishes++; plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Completed", finishes); plugin.saveConfig(); break; case FAIL: plugin.getConfig().set("Players." + thePlayer.getName() + "." + executerArgs[1] + "." + "Failed", true); plugin.saveConfig(); break; case REMEMBER: // REMEMBER [CHAT|LOCATION|INVENTORY] break; case FOLLOW: // FOLLOW PLAYER|NOBODY NPC theDenizenFollowing = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (commandArgs[1].equalsIgnoreCase("PLAYER")) { theDenizenFollowing.getAI().setTarget(thePlayer, false); } if (commandArgs[1].equalsIgnoreCase("NOBODY")) { theDenizenFollowing.getAI().cancelDestination(); } break; case RESPAWN: // RESPAWN [Location Notable] Location respawnLoc = Denizen.getDenizen.getBookmark(CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])), commandArgs[1], "Location"); NPC respawnDenizen = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); Denizen.previousDenizenLocation.put(respawnDenizen, respawnDenizen.getBukkitEntity().getLocation()); respawnDenizen.getBukkitEntity().getWorld().playEffect(respawnDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2); respawnDenizen.despawn(); respawnDenizen.spawn(respawnLoc); respawnDenizen.getBukkitEntity().getWorld().playEffect(respawnDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2); break; case PERMISS: // PERMISS [Permission Node] Denizen.denizenPerms.playerAdd(thePlayer, commandArgs[1]); break; case REFUSE: // PERMISS [Permission Node] Denizen.denizenPerms.playerRemove(thePlayer, commandArgs[1]); break; case EXECUTE: // EXECUTE ASPLAYER [Command to Execute] String[] executeCommand = executerArgs[4].split(" ", 3); NPC theDenizenExecuting = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (commandArgs[1].equalsIgnoreCase("ASPLAYER")) { thePlayer.performCommand(executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } if (commandArgs[1].equalsIgnoreCase("ASNPC")) { ((Player) theDenizenExecuting.getBukkitEntity()).performCommand(executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } if (commandArgs[1].equalsIgnoreCase("ASSERVER")) { plugin.getServer().dispatchCommand(Bukkit.getConsoleSender(), executeCommand[2].replace("<PLAYER>", thePlayer.getName().replace("<WORLD>", thePlayer.getWorld().getName()))); } break; // SHOUT can be heard by players within 100 blocks. // WHISPER can only be heard by the player interacting with. // CHAT can be heard by the player, and players within 5 blocks. // NARRARATE can only be heard by the player and is not branded by the NPC. // ANNOUNCE can be heard by the entire server. case WHISPER: // ZAP [Optional Step # to advance to] case NARRATE: // ZAP [Optional Step # to advance to] if (executerArgs[4].split(" ", 2)[1].startsWith("*")) thePlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "").replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); else thePlayer.sendMessage(executerArgs[4].split(" ", 2)[1].replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); break; case SHOUT: // ZAP [Optional Step # to advance to] case CHAT: // CHAT [Message] NPC theDenizenChatting = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executerArgs[0])); if (executerArgs[4].split(" ", 2)[1].startsWith("*")) thePlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "")); else thePlayer.sendMessage(plugin.getConfig().getString("npc_chat_to_player").replace("<TEXT>", executerArgs[4].split(" ", 2)[1]).replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); for (Player eachPlayer : Denizen.getPlayer.getInRange(theDenizenChatting.getBukkitEntity(), plugin.getConfig().getInt("npc_to_player_chat_range_in_blocks", 15))) { if (eachPlayer != thePlayer) { if (executerArgs[4].split(" ", 2)[1].startsWith("*")) eachPlayer.sendMessage(" " + executerArgs[4].split(" ", 2)[1].replace("*", "")); else eachPlayer.sendMessage(plugin.getConfig().getString("npc_chat_to_player_bystander").replace("<TEXT>", executerArgs[4].split(" ", 2)[1]).replace("<PLAYER>", thePlayer.getName()).replace("<NPC>", CitizensAPI.getNPCRegistry().getNPC(Integer.parseInt(executerArgs[0])).getName())); } } break; case ANNOUNCE: // ANNOUNCE [Message] // NOTABLES case RESET: // RESET FINISH(ED) [Name of Script] or RESET FAIL(ED) [NAME OF SCRIPT] String nameOfScript = executerArgs[4].split(" ", 3)[2]; if (commandArgs[1].equalsIgnoreCase("FINISH") || commandArgs[1].equalsIgnoreCase("FINISHED")) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + nameOfScript + "." + "Completed", 0); plugin.saveConfig(); } if (commandArgs[1].equalsIgnoreCase("FAIL") || commandArgs[1].equalsIgnoreCase("FAILED")) { plugin.getConfig().set("Players." + thePlayer.getName() + "." + nameOfScript + "." + "Failed", false); plugin.saveConfig(); } break; case CHANGE: break; case WAIT: List<String> CurrentPlayerQue = new ArrayList<String>(); if (Denizen.playerQue.get(thePlayer) != null) CurrentPlayerQue = Denizen.playerQue.get(thePlayer); Denizen.playerQue.remove(thePlayer); // Should keep the talk queue from triggering mid-add Long timeDelay = Long.parseLong(commandArgs[1]) * 1000; String timeWithDelay = String.valueOf(System.currentTimeMillis() + timeDelay); CurrentPlayerQue.add(1, "0;none;0;" + timeWithDelay + ";WAITING"); Denizen.playerQue.put(thePlayer, CurrentPlayerQue); break; case WAITING: // ...and we're waiting. break; default: break; } }
diff --git a/core/src/org/icepdf/core/util/Parser.java b/core/src/org/icepdf/core/util/Parser.java index f8febb77..025ebdcf 100644 --- a/core/src/org/icepdf/core/util/Parser.java +++ b/core/src/org/icepdf/core/util/Parser.java @@ -1,1279 +1,1279 @@ /* * Copyright 2006-2013 ICEsoft Technologies 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 org.icepdf.core.util; import org.icepdf.core.exceptions.PDFException; import org.icepdf.core.io.*; import org.icepdf.core.pobjects.*; import org.icepdf.core.pobjects.annotations.Annotation; import org.icepdf.core.pobjects.fonts.CMap; import org.icepdf.core.pobjects.fonts.Font; import org.icepdf.core.pobjects.fonts.FontDescriptor; import org.icepdf.core.pobjects.fonts.FontFactory; import org.icepdf.core.pobjects.graphics.TilingPattern; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; /** * put your documentation comment here */ public class Parser { private static final Logger logger = Logger.getLogger(Parser.class.toString()); public static final int PARSE_MODE_NORMAL = 0; public static final int PARSE_MODE_OBJECT_STREAM = 1; // InputStream has to support mark(), reset(), and markSupported() // DO NOT close this, since we have two cases: read everything up front, and progressive reads // private BufferedMarkedInputStream reader; private InputStream reader; boolean lastTokenHString = false; private Stack<Object> stack = new Stack<Object>(); private int parseMode; private boolean isTrailer; private int linearTraversalOffset; public Parser(SeekableInput r) { this(r, PARSE_MODE_NORMAL); } public Parser(SeekableInput r, int pm) { // reader = new BufferedMarkedInputStream(r.getInputStream()); reader = r.getInputStream(); parseMode = pm; } public Parser(InputStream r) { this(r, PARSE_MODE_NORMAL); } public Parser(InputStream r, int pm) { reader = new BufferedMarkedInputStream(r); parseMode = pm; } /** * Get an object from the pdf input DataInputStream. * * @param library all found objects in the pdf document * @return the next object in the DataInputStream. Null is returned * if there are no more objects left in the DataInputStream or * a I/O error is encountered. * @throws PDFException error getting object from library */ public Object getObject(Library library) throws PDFException { int deepnessCount = 0; boolean inObject = false; // currently parsing tokens in an object boolean complete = false; // flag used for do loop. Object nextToken; Reference objectReference = null; try { reader.mark(1); // capture the byte offset of this object so we can rebuild // the cross reference entries for lazy loading after CG. if (library.isLinearTraversal() && reader instanceof BufferedMarkedInputStream) { linearTraversalOffset = ((BufferedMarkedInputStream) reader).getMarkedPosition(); } do { //while (!complete); // keep track of currently parsed objects reference // get the next token inside the object stream try { nextToken = getToken(); // commented out for performance reasons //Thread.yield(); } catch (IOException e) { // eat it as it is what is expected logger.warning("IO reading error."); return null; } // check for specific primative object types returned by getToken() if (nextToken instanceof StringObject || nextToken instanceof Name || nextToken instanceof Number) { // Very Important, store the PDF object reference information, // as it is needed when to decrypt an encrypted string. if (nextToken instanceof StringObject) { StringObject tmp = (StringObject) nextToken; tmp.setReference(objectReference); } stack.push(nextToken); } // mark that we have entered a object declaration else if (nextToken.equals("obj")) { // a rare parsing error is that endobj is missing, so we need // to make sure if an object has been parsed that we don't loose it. if (inObject) { // pop off the object and ref number stack.pop(); stack.pop(); // return the passed over object on the stack. return addPObject(library, objectReference); } // Since we can return objects on "endstream", then we can // leave straggling "endobj", which would deepnessCount--, // even though they're done in a separate method invocation // Hence, "obj" does /deepnessCount = 1/ instead of /deepnessCount++/ deepnessCount = 0; inObject = true; Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); objectReference = new Reference(objectNumber, generationNumber); } // mark that we have reached the end of the object else if (nextToken.equals("endobj") || nextToken.equals("endobject")) { if (inObject) { // set flag to false, as we are done parsing an Object inObject = false; // return PObject, return addPObject(library, objectReference); // else, we ignore as the endStream token also returns a // PObject. } else { // return null; } } // found endstream object, we will return the PObject containing // the stream as there can be no further tokens. This addresses // an incorrect a syntax error with OpenOffice document where // the endobj tag is missing on some Stream objects. else if (nextToken.equals("endstream")) { deepnessCount--; // do nothing, but don't add it to the stack if (inObject) { inObject = false; // return PObject, return addPObject(library, objectReference); } } // found a stream object, streams are allways defined inside // of a object so we will always have a dictionary (hash) that // has the length and filter definitions in it else if (nextToken.equals("stream")) { deepnessCount++; // pop dictionary that defines the stream HashMap streamHash = (HashMap) stack.pop(); // find the length of the stream int streamLength = library.getInt(streamHash, Dictionary.LENGTH_KEY); SeekableInputConstrainedWrapper streamInputWrapper; try { // a stream token's end of line marker can be either: // - a carriage return and a line feed // - just a line feed, and not by a carriage return alone. // check for carriage return and line feed, but reset if // just a carriage return as it is a valid stream byte reader.mark(2); // alway eat a 13,against the spec but we have several examples of this. int curChar = reader.read(); if (curChar == 13) { reader.mark(1); if (reader.read() != 10) { reader.reset(); } } // always eat a 10 else if (curChar == 10) { // eat the stream character } // reset the rest else { reader.reset(); } if (reader instanceof SeekableInput) { SeekableInput streamDataInput = (SeekableInput) reader; long filePositionOfStreamData = streamDataInput.getAbsolutePosition(); long lengthOfStreamData; // If the stream has a length that we can currently use // such as a R that has been parsed or an integer if (streamLength > 0) { lengthOfStreamData = streamLength; streamDataInput.seekRelative(streamLength); // Read any extraneous data coming after the length, but before endstream lengthOfStreamData += skipUntilEndstream(null); } else { lengthOfStreamData = captureStreamData(null); } streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, lengthOfStreamData); } else { // reader is just regular InputStream (BufferedInputStream) // stream NOT SeekableInput ConservativeSizingByteArrayOutputStream out; // If the stream in from a regular InputStream, // then the PDF was probably linearly traversed, // in which case it doesn't matter if they have // specified the stream length, because we can't // trust that anyway if (!library.isLinearTraversal() && streamLength > 0) { byte[] buffer = new byte[streamLength]; int totalRead = 0; while (totalRead < buffer.length) { int currRead = reader.read(buffer, totalRead, buffer.length - totalRead); if (currRead <= 0) break; totalRead += currRead; } out = new ConservativeSizingByteArrayOutputStream( buffer); // Read any extraneous data coming after the length, but before endstream skipUntilEndstream(out); } // if stream doesn't have a length, read the stream // until end stream has been found else { // stream NOT SeekableInput No trusted streamLength"); out = new ConservativeSizingByteArrayOutputStream( 16 * 1024); captureStreamData(out); } int size = out.size(); out.trim(); byte[] buffer = out.relinquishByteArray(); SeekableInput streamDataInput = new SeekableByteArrayInputStream(buffer); long filePositionOfStreamData = 0L; streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, size); } } catch (IOException e) { e.printStackTrace(); return null; } PTrailer trailer = null; // set the stream know objects if possible Stream stream = null; Name type = (Name) library.getObject(streamHash, Dictionary.TYPE_KEY); Name subtype = (Name) library.getObject(streamHash, Dictionary.SUBTYPE_KEY); if (type != null) { // found a xref stream which is made up it's own entry format // different then an standard xref table, mainly used to // access cross-reference entries but also to compress xref tables. if (type.equals("XRef")) { stream = new Stream(library, streamHash, streamInputWrapper); stream.init(); InputStream in = stream.getDecodedByteArrayInputStream(); CrossReference xrefStream = new CrossReference(); if (in != null) { try { xrefStream.addXRefStreamEntries(library, streamHash, in); } finally { try { in.close(); } catch (Throwable e) { logger.log(Level.WARNING, "Error appending stream entries.", e); } } } // XRef dict is both Trailer dict and XRef stream dict. // PTrailer alters its dict, so copy it to keep everything sane HashMap trailerHash = (HashMap) streamHash.clone(); trailer = new PTrailer(library, trailerHash, null, xrefStream); } else if (type.equals("ObjStm")) { stream = new ObjectStream(library, streamHash, streamInputWrapper); } else if (type.equals("XObject") && "Image".equals(subtype)) { stream = new ImageStream(library, streamHash, streamInputWrapper); } // new Tiling Pattern Object, will have a stream. else if (type.equals("Pattern")) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (stream == null && subtype != null) { // new form object if (subtype.equals("Image")) { stream = new ImageStream(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && !"Pattern".equals(type)) { stream = new Form(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && "Pattern".equals(type)) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (trailer != null) { stack.push(trailer); } else { // finally create a generic stream object which will be parsed // at a later time if (stream == null) { stream = new Stream(library, streamHash, streamInputWrapper); } stack.push(stream); } } // end if (stream) // boolean objects are added to stack else if (nextToken.equals("true")) { stack.push(true); } else if (nextToken.equals("false")) { stack.push(false); } // Indirect Reference object found else if (nextToken.equals("R")) { // generationNumber number important for revisions Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); stack.push(new Reference(objectNumber, generationNumber)); } else if (nextToken.equals("[")) { deepnessCount++; stack.push(nextToken); } // Found an array else if (nextToken.equals("]")) { deepnessCount--; final int searchPosition = stack.search("["); final int size = searchPosition - 1; List v = new ArrayList(size); Object[] tmp = new Object[size]; if (searchPosition > 0) { for (int i = size - 1; i >= 0; i--) { tmp[i] = stack.pop(); } // we need a mutable array so copy into an arrayList // so we can't use Arrays.asList(). for (int i = 0; i < size; i++) { v.add(tmp[i]); } stack.pop(); // "[" } else { stack.clear(); } stack.push(v); } else if (nextToken.equals("<<")) { deepnessCount++; stack.push(nextToken); } // Found a Dictionary else if (nextToken.equals(">>")) { deepnessCount--; // check for extra >> which we want to ignore if (!isTrailer && deepnessCount >= 0) { if (!stack.isEmpty()) { HashMap hashMap = new HashMap(); Object obj = stack.pop(); // put all of the dictionary definistion into the // the hashTabl while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } obj = hashMap.get(Dictionary.TYPE_KEY); // Process the know first level dictionaries. if (obj != null && obj instanceof Name) { Name n = (Name) obj; if (n.equals(Catalog.TYPE)) { stack.push(new Catalog(library, hashMap)); } else if (n.equals(PageTree.TYPE)) { stack.push(new PageTree(library, hashMap)); } else if (n.equals(Page.TYPE)) { stack.push(new Page(library, hashMap)); } else if (n.equals(Font.TYPE)) { stack.push(FontFactory.getInstance() .getFont(library, hashMap)); } else if (n.equals(FontDescriptor.TYPE)) { stack.push(new FontDescriptor(library, hashMap)); } else if (n.equals(CMap.TYPE)) { stack.push(hashMap); } else if (n.equals(Annotation.TYPE)) { stack.push(Annotation.buildAnnotation(library, hashMap)); } else if (n.equals(OptionalContentGroup.TYPE)) { stack.push(new OptionalContentGroup(library, hashMap)); } else if (n.equals(OptionalContentMembership.TYPE)) { stack.push(new OptionalContentMembership(library, hashMap)); } else stack.push(hashMap); } // everything else gets pushed onto the stack else { stack.push(hashMap); } } - } else if (isTrailer && deepnessCount >= 0) { + } else if (isTrailer && deepnessCount == 0) { // we have an xref entry HashMap hashMap = new HashMap(); Object obj = stack.pop(); - // put all of the dictionary definistion into the - // the hashTabl + // put all of the dictionary definition into the + // the new map. while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } return hashMap; } } // found traditional XrefTable found in all documents. else if (nextToken.equals("xref")) { // parse out hte traditional CrossReference xrefTable = new CrossReference(); xrefTable.addXRefTableEntries(this); stack.push(xrefTable); } else if (nextToken.equals("trailer")) { CrossReference xrefTable = null; if (stack.peek() instanceof CrossReference) xrefTable = (CrossReference) stack.pop(); stack.clear(); isTrailer = true; HashMap trailerDictionary = (HashMap) getObject(library); isTrailer = false; return new PTrailer(library, trailerDictionary, xrefTable, null); } // comments else if (nextToken instanceof String && ((String) nextToken).startsWith("%")) { // Comment, ignored for now } // everything else gets pushed onto the stack else { stack.push(nextToken); } if (parseMode == PARSE_MODE_OBJECT_STREAM && deepnessCount == 0 && stack.size() > 0) { return stack.pop(); } } while (!complete); } catch (Exception e) { logger.log(Level.WARNING, "Fatal error parsing PDF file stream.", e); e.printStackTrace(); return null; } // return the top of the stack return stack.pop(); } /** * @return * @throws java.io.IOException */ public String peek2() throws IOException { reader.mark(2); char c[] = new char[2]; c[0] = (char) reader.read(); c[1] = (char) reader.read(); String s = new String(c); reader.reset(); return s; } /** * @return true if ate the ending EI delimiter * @throws java.io.IOException */ public boolean readLineForInlineImage(OutputStream out) throws IOException { // The encoder might not have put EI on its own line (as it should), // but might just put it right after the data final int STATE_PRE_E = 0; final int STATE_PRE_I = 1; final int STATE_PRE_WHITESPACE = 2; int state = STATE_PRE_E; while (true) { int c = reader.read(); if (c < 0) break; if (state == STATE_PRE_E && c == 'E') { state++; continue; } else if (state == STATE_PRE_I && c == 'I') { state++; continue; } else if (state == STATE_PRE_WHITESPACE && isWhitespace((char) (0xFF & c))) { // It's hard to tell if the EI + whitespace is part of the // image data or not, given that many PDFs are mis-encoded, // and don't give whitespace when necessary. So, instead of // assuming the need for whitespace, we're going to assume // that this is the real EI, and apply a heuristic to prove // ourselves wrong. boolean imageDataFound = isStillInlineImageData(reader, 32); if (imageDataFound) { out.write('E'); out.write('I'); out.write(c); state = STATE_PRE_E; if (c == '\r' || c == '\n') { break; } } else return true; } else { // If we got a fragment of the EI<whitespace> sequence, then we withheld // what we had so far. But if we're here, that fragment was incomplete, // so that was actual embedded data, and not the delimiter, so we have // to write it out. if (state > STATE_PRE_E) out.write('E'); if (state > STATE_PRE_I) out.write('I'); state = STATE_PRE_E; out.write((byte) c); if (c == '\r' || c == '\n') { break; } } } // If the input ends right after the EI, but with no whitespace, // then we're still done if (state == STATE_PRE_WHITESPACE) return true; return false; } /** * We want to be conservative in deciding that we're still in the inline * image, since we haven't found any of these cases before now. */ private static boolean isStillInlineImageData( InputStream reader, int numBytesToCheck) throws IOException { boolean imageDataFound = false; boolean onlyWhitespaceSoFar = true; reader.mark(numBytesToCheck); byte[] toCheck = new byte[numBytesToCheck]; int numReadToCheck = reader.read(toCheck); for (int i = 0; i < numReadToCheck; i++) { char charToCheck = (char) (((int) toCheck[i]) & 0xFF); // If the very first thing we read is a Q or S token boolean typicalTextTokenInContentStream = (charToCheck == 'Q' || charToCheck == 'q' || charToCheck == 'S' || charToCheck == 's'); if (onlyWhitespaceSoFar && typicalTextTokenInContentStream && (i + 1 < numReadToCheck) && isWhitespace((char) (((int) toCheck[i + 1]) & 0xFF))) { break; } if (!isWhitespace(charToCheck)) onlyWhitespaceSoFar = false; // If we find some binary image data if (!isExpectedInContentStream(charToCheck)) { imageDataFound = true; break; } } reader.reset(); return imageDataFound; } /** * This is not necessarily an exhaustive list of characters one would * expect in a Content Stream, it's a heuristic for whether the data * might still be part of an inline image, or the lattercontent stream */ private static boolean isExpectedInContentStream(char c) { return ((c >= 'a' && c <= 'Z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || isWhitespace(c) || isDelimiter(c) || (c == '\\') || (c == '\'') || (c == '\"') || (c == '*') || (c == '.')); } /** * Utility Method for getting a PObject from the stack and adding it to the * library. The retrieved PObject has an ObjectReference added to it for * decryption purposes. * * @param library HashMap of all objects in document * @param objectReference PObjet indirect reference data * @return a valid PObject. */ public PObject addPObject(Library library, Reference objectReference) { Object o = stack.pop(); // Add the streams object reference which is needed for // decrypting encrypted streams if (o instanceof Stream) { Stream tmp = (Stream) o; tmp.setPObjectReference(objectReference); } // Add the dictionary object reference which is needed for // decrypting encrypted string contained in the dictionary else if (o instanceof Dictionary) { Dictionary tmp = (Dictionary) o; tmp.setPObjectReference(objectReference); } // the the object to the library library.addObject(o, objectReference); return new PObject(o, objectReference); } /** * Returns the next object found in a content stream. * * @return next object in the input stream * @throws java.io.IOException when the end of the <code>InputStream</code> * has been encountered. */ public Object getStreamObject() throws IOException { Object o = getToken(); if (o instanceof String) { if (o.equals("<<")) { HashMap h = new HashMap(); Object o1 = getStreamObject(); while (!o1.equals(">>")) { h.put(o1, getStreamObject()); o1 = getStreamObject(); } o = h; } // arrays are only used for CID mappings, the hex decoding is delayed // as a result using the CID_STREAM flag else if (o.equals("[")) { List v = new ArrayList(); Object o1 = getStreamObject(); while (!o1.equals("]")) { v.add(o1); o1 = getStreamObject(); } o = v; } } return o; } /** * Utility method used to parse a valid pdf token from an DataIinputStream. * Each call to this method return one pdf token. The Reader object is * used to "mark" the location of the last "read". * * @return the next token in the pdf data stream * @throws java.io.IOException if an I/O error occurs. */ public Object getToken() throws IOException { int currentByte; char currentChar; boolean inString = false; // currently parsing a string boolean hexString = false; boolean inNumber = false; lastTokenHString = false; // strip all white space characters do { currentByte = reader.read(); // input stream interrupted if (currentByte < 0) { throw new IOException(); } currentChar = (char) currentByte; } while (isWhitespace(currentChar)); /** * look the start of different primitive pdf objects * ( - strints * [ - arrays * % - comments * numbers. */ if (currentChar == '(') { // mark that we are currrently processing a string inString = true; } else if (currentChar == ']') { // fount end of an array return "]"; } else if (currentChar == '[') { // fount begining of an array return "["; } else if (currentChar == '%') { // ignore all the characters after a comment token until // we get to the end of the line StringBuilder stringBuffer = new StringBuilder(); do { stringBuffer.append(currentChar); currentByte = reader.read(); if (currentByte < 0) { // Final %%EOF might not have CR LF afterwards if (stringBuffer.length() > 0) return stringBuffer.toString(); throw new IOException(); } currentChar = (char) currentByte; } while (currentChar != 13 && currentChar != 10); // return all the text that is in the comment return stringBuffer.toString(); } else if ((currentChar >= '0' && currentChar <= '9') || currentChar == '-' || currentChar == '+') { inNumber = true; } // mark this location in the input stream reader.mark(1); // read the next char from the reader char nextChar = (char) reader.read(); // Check for dictionaries, start '<<' and end '>>' if (currentChar == '>' && nextChar == '>') { return ">>"; } if (currentChar == '<') { // if two "<<" then we have a dictionary if (nextChar == '<') { return "<<"; } // Otherwise we have a hex number else { inString = true; hexString = true; } } // return to the previous mark reader.reset(); // store the parsed char in the token buffer. StringBuilder stringBuffer = new StringBuilder(); stringBuffer.append(currentChar); /** * Finally parse the contents of a complex token */ int parenthesisCount = 0; boolean complete = false; // indicates that the current char should be ignored and not added to // the current string. boolean ignoreChar = false; do { // while !complete // if we are not parsing a string mark the location if (!inString) { reader.mark(1); } // get the next byte and corresponding char currentByte = reader.read(); if (currentByte >= 0) { currentChar = (char) currentByte; } else { // if there are no more bytes (-1) then we must have reached the end of this token, // though maybe without appropriate termination of a string object. We'll just treat // them as if they were. break; } // if we are parsing a token that is a string, (...) if (inString) { if (hexString) { // found the end of a dictionary if (currentChar == '>') { stringBuffer.append(currentChar); break; } } else { // look for embedded strings if (currentChar == '(') { parenthesisCount++; } if (currentChar == ')') { if (parenthesisCount == 0) { stringBuffer.append(currentChar); break; } else { parenthesisCount--; } } // look for "\" character /** * The escape sequences can be as follows: * \n - line feed (LF) * \r - Carriage return (CR) * \t - Horizontal tab (HT) * \b - backspace (BS) * \f - form feed (FF) * \( - left parenthesis * \) - right parenthesis * \\ - backslash * \ddd - character code ddd (octal) * * Note: (\0053) denotes a string containing two characters, * \005 (Control-E) followed by the digit 3. */ if (currentChar == '\\') { // read next char currentChar = (char) reader.read(); // check for a digit, if so we have an octal // and we need to handle it correctly if (Character.isDigit(currentChar)) { // store the read digits StringBuilder digit = new StringBuilder(); digit.append(currentChar); // octals have a max size of 3 digits, we already // have one, so there can be up 2 more digits. for (int i = 0; i < 2; i++) { // mark the reader incase the next read is not // a digit. reader.mark(1); // read next char currentChar = (char) reader.read(); if (Character.isDigit(currentChar)) { digit.append(currentChar); } else { // back up the reader just incase // thre is only 1 or 2 digits in the octal reader.reset(); break; } } // finally convert digit to a character int charNumber = 0; try { charNumber = Integer.parseInt(digit.toString(), 8); } catch (NumberFormatException e) { logger.log(Level.FINE, "Integer parse error ", e); } // convert the interger from octal to dec. currentChar = (char) charNumber; } // do nothing else if (currentChar == '(' || currentChar == ')' || currentChar == '\\') { } // capture the horizontal tab (HT), tab character is hard // to find, only appears in files with font substitution and // as a result we ahve better luck drawing a space character. else if (currentChar == 't') { currentChar = '\t'; } // capture the carriage return (CR) else if (currentChar == 'r') { currentChar = '\r'; } // capture the line feed (LF) else if (currentChar == 'n') { currentChar = '\n'; } // capture the backspace (BS) else if (currentChar == 'b') { currentChar = '\b'; } // capture the form feed (FF) else if (currentChar == 'f') { currentChar = '\f'; } // ignor CF, which indicate a '\' lone split line token else if (currentChar == 13) { ignoreChar = true; } // otherwise report the file format error else { if (logger.isLoggable(Level.FINE)) { logger.warning("C=" + ((int) currentChar)); } } } } } // if we are not in a string definition we want to break // and return the current token, as white spaces or other elements // would mean that we are on the next token else if (isWhitespace(currentChar)) { // we need to return the CR LR, as it is need by stream parsing if (currentByte == 13 || currentByte == 10) { reader.reset(); break; } // break on any whitespace else { // return stringBuffer.toString(); break; } } else if (isDelimiter(currentChar)) { // reset the reader so we start on this token on the next parse reader.reset(); break; } // append the current char and keep parsing if needed // IgnoreChar is set by the the line split char '\' if (!ignoreChar) { if (inString) { stringBuffer.append(currentChar); } // eat any junk characters else if (currentChar < 128) { stringBuffer.append(currentChar); } } // reset the ignorChar flag else { ignoreChar = false; } } while (!complete); /** * Return what we found */ // if a hex string decode it as needed if (hexString) { lastTokenHString = true; return new HexStringObject(stringBuffer); } // do a little clean up for any object that may have been missed.. // this mainly for the the document trailer information // a orphaned string if (inString) { return new LiteralStringObject(stringBuffer); } // return a new name else if (stringBuffer.charAt(0) == '/') { return new Name(stringBuffer.deleteCharAt(0)); } // if a number try and parse it else if (inNumber) { return getFloat(stringBuffer); } return stringBuffer.toString(); } public Object getNumberOrStringWithMark(int maxLength) throws IOException { reader.mark(maxLength); StringBuilder sb = new StringBuilder(maxLength); boolean readNonWhitespaceYet = false; boolean foundDigit = false; boolean foundDecimal = false; for (int i = 0; i < maxLength; i++) { int curr = reader.read(); if (curr < 0) break; char currChar = (char) curr; if (isWhitespace(currChar)) { if (readNonWhitespaceYet) break; } else if (isDelimiter(currChar)) { // Number or string has delimiter immediately after it, // which we'll have to unread. // Had hoped it would be whitespace, so wouldn't have to unread reader.reset(); reader.mark(maxLength); for (int j = 0; j < i; j++) { reader.read(); } readNonWhitespaceYet = true; break; } else { readNonWhitespaceYet = true; if (currChar == '.') foundDecimal = true; else if (currChar >= '0' && curr <= '9') foundDigit = true; sb.append(currChar); } } // Only bother trying to interpret as a number if contains a digit somewhere, // to reduce NumberFormatExceptions if (foundDigit) { return getFloat(sb); } if (sb.length() > 0) return sb.toString(); return null; } public void ungetNumberOrStringWithReset() throws IOException { reader.reset(); } public int getIntSurroundedByWhitespace() { int num = 0; boolean makeNegative = false; boolean readNonWhitespace = false; try { while (true) { int curr = reader.read(); if (curr < 0) break; if (Character.isWhitespace((char) curr)) { if (readNonWhitespace) break; } else if (curr == '-') { makeNegative = true; readNonWhitespace = true; } else if (curr >= '0' && curr <= '9') { num *= 10; num += (curr - '0'); readNonWhitespace = true; } else { // break as we've hit a none digit and should bail break; } } } catch (IOException e) { logger.log(Level.FINE, "Error detecting int.", e); } if (makeNegative) num = num * -1; return num; } public float getFloat(StringBuilder value) { float digit = 0; float divisor = 10; boolean isDigit; boolean isDecimal = false; byte[] streamBytes = value.toString().getBytes(); int startTokenPos = 0; boolean singed = streamBytes[startTokenPos] == '-'; boolean positive = streamBytes[startTokenPos] == '+'; startTokenPos = singed || positive ? startTokenPos + 1 : startTokenPos; // check for double sign, thanks oracle forms! if (singed && streamBytes[startTokenPos] == '-') { startTokenPos++; } int current; for (int i = startTokenPos, max = streamBytes.length; i < max; i++) { current = streamBytes[i] - 48; isDigit = streamBytes[i] >= 48 && streamBytes[i] <= 57; if (!isDecimal && isDigit) { digit = (digit * 10) + current; } else if (isDecimal && isDigit) { digit += (current / divisor); divisor *= 10; } else if (streamBytes[i] == 46) { isDecimal = true; } else { // anything else we can assume malformed and should break. break; } } if (singed) { return -digit; } else { return digit; } } public long getLongSurroundedByWhitespace() { long num = 0L; boolean makeNegative = false; boolean readNonWhitespace = false; try { while (true) { int curr = reader.read(); if (curr < 0) break; if (Character.isWhitespace((char) curr)) { if (readNonWhitespace) break; } else if (curr == '-') { makeNegative = true; readNonWhitespace = true; } else if (curr >= '0' && curr <= '9') { num *= 10L; num += ((long) (curr - '0')); readNonWhitespace = true; } else { break; } } } catch (IOException e) { logger.log(Level.FINER, "Error detecting long.", e); } if (makeNegative) num = num * -1L; return num; } public int getLinearTraversalOffset() { return linearTraversalOffset; } public char getCharSurroundedByWhitespace() { char alpha = 0; try { while (true) { int curr = reader.read(); if (curr < 0) break; char c = (char) curr; if (!Character.isWhitespace(c)) { alpha = c; break; } } } catch (IOException e) { logger.log(Level.FINE, "Error detecting char.", e); } return alpha; } /** * White space characters defined by ' ', '\t', '\r', '\n', '\f' * * @param c true if character is white space */ public static boolean isWhitespace(char c) { return ((c == ' ') || (c == '\t') || (c == '\r') || (c == '\n') || (c == '\f')); } private static boolean isDelimiter(char c) { return ((c == '[') || (c == ']') || (c == '(') || (c == ')') || (c == '<') || (c == '>') || (c == '{') || (c == '}') || (c == '/') || (c == '%')); } private long captureStreamData(OutputStream out) throws IOException { long numBytes = 0; while (true) { // read bytes int nextByte = reader.read(); // look to see if we have the ending tag if (nextByte == 'e') { reader.mark(10); if (reader.read() == 'n' && reader.read() == 'd' && reader.read() == 's' && reader.read() == 't' && reader.read() == 'r' && reader.read() == 'e' && reader.read() == 'a' && reader.read() == 'm') { break; } else { reader.reset(); } } else if (nextByte < 0) break; // write the bytes if (out != null) out.write(nextByte); numBytes++; } return numBytes; } private long skipUntilEndstream(OutputStream out) throws IOException { long skipped = 0L; while (true) { reader.mark(10); // read bytes int nextByte = reader.read(); if (nextByte == 'e' && reader.read() == 'n' && reader.read() == 'd' && reader.read() == 's' && reader.read() == 't' && reader.read() == 'r' && reader.read() == 'e' && reader.read() == 'a' && reader.read() == 'm') { reader.reset(); break; } else if (nextByte < 0) break; else { if (nextByte == 0x0A || nextByte == 0x0D || nextByte == 0x20) continue; if (out != null) out.write(nextByte); } skipped++; } return skipped; } private float parseNumber(StringBuilder stringBuilder) { float digit = 0; float divisor = 10; boolean isDigit; boolean isDecimal = false; int startTokenPos = 0; int length = stringBuilder.length(); char[] streamBytes = new char[length]; stringBuilder.getChars(0, length, streamBytes, 0); boolean singed = streamBytes[startTokenPos] == '-'; startTokenPos = singed ? startTokenPos + 1 : startTokenPos; int current; for (int i = startTokenPos; i < length; i++) { current = streamBytes[i] - 48; isDigit = streamBytes[i] >= 48 && streamBytes[i] <= 57; if (!isDecimal && isDigit) { digit = (digit * 10) + current; } else if (isDecimal && isDigit) { digit += (current / divisor); divisor *= 10; } else if (streamBytes[i] == 46) { isDecimal = true; } else { // anything else we can assume malformed and should break. break; } } if (singed) { return -digit; } else { return digit; } } }
false
true
public Object getObject(Library library) throws PDFException { int deepnessCount = 0; boolean inObject = false; // currently parsing tokens in an object boolean complete = false; // flag used for do loop. Object nextToken; Reference objectReference = null; try { reader.mark(1); // capture the byte offset of this object so we can rebuild // the cross reference entries for lazy loading after CG. if (library.isLinearTraversal() && reader instanceof BufferedMarkedInputStream) { linearTraversalOffset = ((BufferedMarkedInputStream) reader).getMarkedPosition(); } do { //while (!complete); // keep track of currently parsed objects reference // get the next token inside the object stream try { nextToken = getToken(); // commented out for performance reasons //Thread.yield(); } catch (IOException e) { // eat it as it is what is expected logger.warning("IO reading error."); return null; } // check for specific primative object types returned by getToken() if (nextToken instanceof StringObject || nextToken instanceof Name || nextToken instanceof Number) { // Very Important, store the PDF object reference information, // as it is needed when to decrypt an encrypted string. if (nextToken instanceof StringObject) { StringObject tmp = (StringObject) nextToken; tmp.setReference(objectReference); } stack.push(nextToken); } // mark that we have entered a object declaration else if (nextToken.equals("obj")) { // a rare parsing error is that endobj is missing, so we need // to make sure if an object has been parsed that we don't loose it. if (inObject) { // pop off the object and ref number stack.pop(); stack.pop(); // return the passed over object on the stack. return addPObject(library, objectReference); } // Since we can return objects on "endstream", then we can // leave straggling "endobj", which would deepnessCount--, // even though they're done in a separate method invocation // Hence, "obj" does /deepnessCount = 1/ instead of /deepnessCount++/ deepnessCount = 0; inObject = true; Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); objectReference = new Reference(objectNumber, generationNumber); } // mark that we have reached the end of the object else if (nextToken.equals("endobj") || nextToken.equals("endobject")) { if (inObject) { // set flag to false, as we are done parsing an Object inObject = false; // return PObject, return addPObject(library, objectReference); // else, we ignore as the endStream token also returns a // PObject. } else { // return null; } } // found endstream object, we will return the PObject containing // the stream as there can be no further tokens. This addresses // an incorrect a syntax error with OpenOffice document where // the endobj tag is missing on some Stream objects. else if (nextToken.equals("endstream")) { deepnessCount--; // do nothing, but don't add it to the stack if (inObject) { inObject = false; // return PObject, return addPObject(library, objectReference); } } // found a stream object, streams are allways defined inside // of a object so we will always have a dictionary (hash) that // has the length and filter definitions in it else if (nextToken.equals("stream")) { deepnessCount++; // pop dictionary that defines the stream HashMap streamHash = (HashMap) stack.pop(); // find the length of the stream int streamLength = library.getInt(streamHash, Dictionary.LENGTH_KEY); SeekableInputConstrainedWrapper streamInputWrapper; try { // a stream token's end of line marker can be either: // - a carriage return and a line feed // - just a line feed, and not by a carriage return alone. // check for carriage return and line feed, but reset if // just a carriage return as it is a valid stream byte reader.mark(2); // alway eat a 13,against the spec but we have several examples of this. int curChar = reader.read(); if (curChar == 13) { reader.mark(1); if (reader.read() != 10) { reader.reset(); } } // always eat a 10 else if (curChar == 10) { // eat the stream character } // reset the rest else { reader.reset(); } if (reader instanceof SeekableInput) { SeekableInput streamDataInput = (SeekableInput) reader; long filePositionOfStreamData = streamDataInput.getAbsolutePosition(); long lengthOfStreamData; // If the stream has a length that we can currently use // such as a R that has been parsed or an integer if (streamLength > 0) { lengthOfStreamData = streamLength; streamDataInput.seekRelative(streamLength); // Read any extraneous data coming after the length, but before endstream lengthOfStreamData += skipUntilEndstream(null); } else { lengthOfStreamData = captureStreamData(null); } streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, lengthOfStreamData); } else { // reader is just regular InputStream (BufferedInputStream) // stream NOT SeekableInput ConservativeSizingByteArrayOutputStream out; // If the stream in from a regular InputStream, // then the PDF was probably linearly traversed, // in which case it doesn't matter if they have // specified the stream length, because we can't // trust that anyway if (!library.isLinearTraversal() && streamLength > 0) { byte[] buffer = new byte[streamLength]; int totalRead = 0; while (totalRead < buffer.length) { int currRead = reader.read(buffer, totalRead, buffer.length - totalRead); if (currRead <= 0) break; totalRead += currRead; } out = new ConservativeSizingByteArrayOutputStream( buffer); // Read any extraneous data coming after the length, but before endstream skipUntilEndstream(out); } // if stream doesn't have a length, read the stream // until end stream has been found else { // stream NOT SeekableInput No trusted streamLength"); out = new ConservativeSizingByteArrayOutputStream( 16 * 1024); captureStreamData(out); } int size = out.size(); out.trim(); byte[] buffer = out.relinquishByteArray(); SeekableInput streamDataInput = new SeekableByteArrayInputStream(buffer); long filePositionOfStreamData = 0L; streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, size); } } catch (IOException e) { e.printStackTrace(); return null; } PTrailer trailer = null; // set the stream know objects if possible Stream stream = null; Name type = (Name) library.getObject(streamHash, Dictionary.TYPE_KEY); Name subtype = (Name) library.getObject(streamHash, Dictionary.SUBTYPE_KEY); if (type != null) { // found a xref stream which is made up it's own entry format // different then an standard xref table, mainly used to // access cross-reference entries but also to compress xref tables. if (type.equals("XRef")) { stream = new Stream(library, streamHash, streamInputWrapper); stream.init(); InputStream in = stream.getDecodedByteArrayInputStream(); CrossReference xrefStream = new CrossReference(); if (in != null) { try { xrefStream.addXRefStreamEntries(library, streamHash, in); } finally { try { in.close(); } catch (Throwable e) { logger.log(Level.WARNING, "Error appending stream entries.", e); } } } // XRef dict is both Trailer dict and XRef stream dict. // PTrailer alters its dict, so copy it to keep everything sane HashMap trailerHash = (HashMap) streamHash.clone(); trailer = new PTrailer(library, trailerHash, null, xrefStream); } else if (type.equals("ObjStm")) { stream = new ObjectStream(library, streamHash, streamInputWrapper); } else if (type.equals("XObject") && "Image".equals(subtype)) { stream = new ImageStream(library, streamHash, streamInputWrapper); } // new Tiling Pattern Object, will have a stream. else if (type.equals("Pattern")) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (stream == null && subtype != null) { // new form object if (subtype.equals("Image")) { stream = new ImageStream(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && !"Pattern".equals(type)) { stream = new Form(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && "Pattern".equals(type)) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (trailer != null) { stack.push(trailer); } else { // finally create a generic stream object which will be parsed // at a later time if (stream == null) { stream = new Stream(library, streamHash, streamInputWrapper); } stack.push(stream); } } // end if (stream) // boolean objects are added to stack else if (nextToken.equals("true")) { stack.push(true); } else if (nextToken.equals("false")) { stack.push(false); } // Indirect Reference object found else if (nextToken.equals("R")) { // generationNumber number important for revisions Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); stack.push(new Reference(objectNumber, generationNumber)); } else if (nextToken.equals("[")) { deepnessCount++; stack.push(nextToken); } // Found an array else if (nextToken.equals("]")) { deepnessCount--; final int searchPosition = stack.search("["); final int size = searchPosition - 1; List v = new ArrayList(size); Object[] tmp = new Object[size]; if (searchPosition > 0) { for (int i = size - 1; i >= 0; i--) { tmp[i] = stack.pop(); } // we need a mutable array so copy into an arrayList // so we can't use Arrays.asList(). for (int i = 0; i < size; i++) { v.add(tmp[i]); } stack.pop(); // "[" } else { stack.clear(); } stack.push(v); } else if (nextToken.equals("<<")) { deepnessCount++; stack.push(nextToken); } // Found a Dictionary else if (nextToken.equals(">>")) { deepnessCount--; // check for extra >> which we want to ignore if (!isTrailer && deepnessCount >= 0) { if (!stack.isEmpty()) { HashMap hashMap = new HashMap(); Object obj = stack.pop(); // put all of the dictionary definistion into the // the hashTabl while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } obj = hashMap.get(Dictionary.TYPE_KEY); // Process the know first level dictionaries. if (obj != null && obj instanceof Name) { Name n = (Name) obj; if (n.equals(Catalog.TYPE)) { stack.push(new Catalog(library, hashMap)); } else if (n.equals(PageTree.TYPE)) { stack.push(new PageTree(library, hashMap)); } else if (n.equals(Page.TYPE)) { stack.push(new Page(library, hashMap)); } else if (n.equals(Font.TYPE)) { stack.push(FontFactory.getInstance() .getFont(library, hashMap)); } else if (n.equals(FontDescriptor.TYPE)) { stack.push(new FontDescriptor(library, hashMap)); } else if (n.equals(CMap.TYPE)) { stack.push(hashMap); } else if (n.equals(Annotation.TYPE)) { stack.push(Annotation.buildAnnotation(library, hashMap)); } else if (n.equals(OptionalContentGroup.TYPE)) { stack.push(new OptionalContentGroup(library, hashMap)); } else if (n.equals(OptionalContentMembership.TYPE)) { stack.push(new OptionalContentMembership(library, hashMap)); } else stack.push(hashMap); } // everything else gets pushed onto the stack else { stack.push(hashMap); } } } else if (isTrailer && deepnessCount >= 0) { // we have an xref entry HashMap hashMap = new HashMap(); Object obj = stack.pop(); // put all of the dictionary definistion into the // the hashTabl while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } return hashMap; } } // found traditional XrefTable found in all documents. else if (nextToken.equals("xref")) { // parse out hte traditional CrossReference xrefTable = new CrossReference(); xrefTable.addXRefTableEntries(this); stack.push(xrefTable); } else if (nextToken.equals("trailer")) { CrossReference xrefTable = null; if (stack.peek() instanceof CrossReference) xrefTable = (CrossReference) stack.pop(); stack.clear(); isTrailer = true; HashMap trailerDictionary = (HashMap) getObject(library); isTrailer = false; return new PTrailer(library, trailerDictionary, xrefTable, null); } // comments else if (nextToken instanceof String && ((String) nextToken).startsWith("%")) { // Comment, ignored for now } // everything else gets pushed onto the stack else { stack.push(nextToken); } if (parseMode == PARSE_MODE_OBJECT_STREAM && deepnessCount == 0 && stack.size() > 0) { return stack.pop(); } } while (!complete); } catch (Exception e) { logger.log(Level.WARNING, "Fatal error parsing PDF file stream.", e); e.printStackTrace(); return null; } // return the top of the stack return stack.pop(); }
public Object getObject(Library library) throws PDFException { int deepnessCount = 0; boolean inObject = false; // currently parsing tokens in an object boolean complete = false; // flag used for do loop. Object nextToken; Reference objectReference = null; try { reader.mark(1); // capture the byte offset of this object so we can rebuild // the cross reference entries for lazy loading after CG. if (library.isLinearTraversal() && reader instanceof BufferedMarkedInputStream) { linearTraversalOffset = ((BufferedMarkedInputStream) reader).getMarkedPosition(); } do { //while (!complete); // keep track of currently parsed objects reference // get the next token inside the object stream try { nextToken = getToken(); // commented out for performance reasons //Thread.yield(); } catch (IOException e) { // eat it as it is what is expected logger.warning("IO reading error."); return null; } // check for specific primative object types returned by getToken() if (nextToken instanceof StringObject || nextToken instanceof Name || nextToken instanceof Number) { // Very Important, store the PDF object reference information, // as it is needed when to decrypt an encrypted string. if (nextToken instanceof StringObject) { StringObject tmp = (StringObject) nextToken; tmp.setReference(objectReference); } stack.push(nextToken); } // mark that we have entered a object declaration else if (nextToken.equals("obj")) { // a rare parsing error is that endobj is missing, so we need // to make sure if an object has been parsed that we don't loose it. if (inObject) { // pop off the object and ref number stack.pop(); stack.pop(); // return the passed over object on the stack. return addPObject(library, objectReference); } // Since we can return objects on "endstream", then we can // leave straggling "endobj", which would deepnessCount--, // even though they're done in a separate method invocation // Hence, "obj" does /deepnessCount = 1/ instead of /deepnessCount++/ deepnessCount = 0; inObject = true; Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); objectReference = new Reference(objectNumber, generationNumber); } // mark that we have reached the end of the object else if (nextToken.equals("endobj") || nextToken.equals("endobject")) { if (inObject) { // set flag to false, as we are done parsing an Object inObject = false; // return PObject, return addPObject(library, objectReference); // else, we ignore as the endStream token also returns a // PObject. } else { // return null; } } // found endstream object, we will return the PObject containing // the stream as there can be no further tokens. This addresses // an incorrect a syntax error with OpenOffice document where // the endobj tag is missing on some Stream objects. else if (nextToken.equals("endstream")) { deepnessCount--; // do nothing, but don't add it to the stack if (inObject) { inObject = false; // return PObject, return addPObject(library, objectReference); } } // found a stream object, streams are allways defined inside // of a object so we will always have a dictionary (hash) that // has the length and filter definitions in it else if (nextToken.equals("stream")) { deepnessCount++; // pop dictionary that defines the stream HashMap streamHash = (HashMap) stack.pop(); // find the length of the stream int streamLength = library.getInt(streamHash, Dictionary.LENGTH_KEY); SeekableInputConstrainedWrapper streamInputWrapper; try { // a stream token's end of line marker can be either: // - a carriage return and a line feed // - just a line feed, and not by a carriage return alone. // check for carriage return and line feed, but reset if // just a carriage return as it is a valid stream byte reader.mark(2); // alway eat a 13,against the spec but we have several examples of this. int curChar = reader.read(); if (curChar == 13) { reader.mark(1); if (reader.read() != 10) { reader.reset(); } } // always eat a 10 else if (curChar == 10) { // eat the stream character } // reset the rest else { reader.reset(); } if (reader instanceof SeekableInput) { SeekableInput streamDataInput = (SeekableInput) reader; long filePositionOfStreamData = streamDataInput.getAbsolutePosition(); long lengthOfStreamData; // If the stream has a length that we can currently use // such as a R that has been parsed or an integer if (streamLength > 0) { lengthOfStreamData = streamLength; streamDataInput.seekRelative(streamLength); // Read any extraneous data coming after the length, but before endstream lengthOfStreamData += skipUntilEndstream(null); } else { lengthOfStreamData = captureStreamData(null); } streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, lengthOfStreamData); } else { // reader is just regular InputStream (BufferedInputStream) // stream NOT SeekableInput ConservativeSizingByteArrayOutputStream out; // If the stream in from a regular InputStream, // then the PDF was probably linearly traversed, // in which case it doesn't matter if they have // specified the stream length, because we can't // trust that anyway if (!library.isLinearTraversal() && streamLength > 0) { byte[] buffer = new byte[streamLength]; int totalRead = 0; while (totalRead < buffer.length) { int currRead = reader.read(buffer, totalRead, buffer.length - totalRead); if (currRead <= 0) break; totalRead += currRead; } out = new ConservativeSizingByteArrayOutputStream( buffer); // Read any extraneous data coming after the length, but before endstream skipUntilEndstream(out); } // if stream doesn't have a length, read the stream // until end stream has been found else { // stream NOT SeekableInput No trusted streamLength"); out = new ConservativeSizingByteArrayOutputStream( 16 * 1024); captureStreamData(out); } int size = out.size(); out.trim(); byte[] buffer = out.relinquishByteArray(); SeekableInput streamDataInput = new SeekableByteArrayInputStream(buffer); long filePositionOfStreamData = 0L; streamInputWrapper = new SeekableInputConstrainedWrapper( streamDataInput, filePositionOfStreamData, size); } } catch (IOException e) { e.printStackTrace(); return null; } PTrailer trailer = null; // set the stream know objects if possible Stream stream = null; Name type = (Name) library.getObject(streamHash, Dictionary.TYPE_KEY); Name subtype = (Name) library.getObject(streamHash, Dictionary.SUBTYPE_KEY); if (type != null) { // found a xref stream which is made up it's own entry format // different then an standard xref table, mainly used to // access cross-reference entries but also to compress xref tables. if (type.equals("XRef")) { stream = new Stream(library, streamHash, streamInputWrapper); stream.init(); InputStream in = stream.getDecodedByteArrayInputStream(); CrossReference xrefStream = new CrossReference(); if (in != null) { try { xrefStream.addXRefStreamEntries(library, streamHash, in); } finally { try { in.close(); } catch (Throwable e) { logger.log(Level.WARNING, "Error appending stream entries.", e); } } } // XRef dict is both Trailer dict and XRef stream dict. // PTrailer alters its dict, so copy it to keep everything sane HashMap trailerHash = (HashMap) streamHash.clone(); trailer = new PTrailer(library, trailerHash, null, xrefStream); } else if (type.equals("ObjStm")) { stream = new ObjectStream(library, streamHash, streamInputWrapper); } else if (type.equals("XObject") && "Image".equals(subtype)) { stream = new ImageStream(library, streamHash, streamInputWrapper); } // new Tiling Pattern Object, will have a stream. else if (type.equals("Pattern")) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (stream == null && subtype != null) { // new form object if (subtype.equals("Image")) { stream = new ImageStream(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && !"Pattern".equals(type)) { stream = new Form(library, streamHash, streamInputWrapper); } else if (subtype.equals("Form") && "Pattern".equals(type)) { stream = new TilingPattern(library, streamHash, streamInputWrapper); } } if (trailer != null) { stack.push(trailer); } else { // finally create a generic stream object which will be parsed // at a later time if (stream == null) { stream = new Stream(library, streamHash, streamInputWrapper); } stack.push(stream); } } // end if (stream) // boolean objects are added to stack else if (nextToken.equals("true")) { stack.push(true); } else if (nextToken.equals("false")) { stack.push(false); } // Indirect Reference object found else if (nextToken.equals("R")) { // generationNumber number important for revisions Number generationNumber = (Number) (stack.pop()); Number objectNumber = (Number) (stack.pop()); stack.push(new Reference(objectNumber, generationNumber)); } else if (nextToken.equals("[")) { deepnessCount++; stack.push(nextToken); } // Found an array else if (nextToken.equals("]")) { deepnessCount--; final int searchPosition = stack.search("["); final int size = searchPosition - 1; List v = new ArrayList(size); Object[] tmp = new Object[size]; if (searchPosition > 0) { for (int i = size - 1; i >= 0; i--) { tmp[i] = stack.pop(); } // we need a mutable array so copy into an arrayList // so we can't use Arrays.asList(). for (int i = 0; i < size; i++) { v.add(tmp[i]); } stack.pop(); // "[" } else { stack.clear(); } stack.push(v); } else if (nextToken.equals("<<")) { deepnessCount++; stack.push(nextToken); } // Found a Dictionary else if (nextToken.equals(">>")) { deepnessCount--; // check for extra >> which we want to ignore if (!isTrailer && deepnessCount >= 0) { if (!stack.isEmpty()) { HashMap hashMap = new HashMap(); Object obj = stack.pop(); // put all of the dictionary definistion into the // the hashTabl while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } obj = hashMap.get(Dictionary.TYPE_KEY); // Process the know first level dictionaries. if (obj != null && obj instanceof Name) { Name n = (Name) obj; if (n.equals(Catalog.TYPE)) { stack.push(new Catalog(library, hashMap)); } else if (n.equals(PageTree.TYPE)) { stack.push(new PageTree(library, hashMap)); } else if (n.equals(Page.TYPE)) { stack.push(new Page(library, hashMap)); } else if (n.equals(Font.TYPE)) { stack.push(FontFactory.getInstance() .getFont(library, hashMap)); } else if (n.equals(FontDescriptor.TYPE)) { stack.push(new FontDescriptor(library, hashMap)); } else if (n.equals(CMap.TYPE)) { stack.push(hashMap); } else if (n.equals(Annotation.TYPE)) { stack.push(Annotation.buildAnnotation(library, hashMap)); } else if (n.equals(OptionalContentGroup.TYPE)) { stack.push(new OptionalContentGroup(library, hashMap)); } else if (n.equals(OptionalContentMembership.TYPE)) { stack.push(new OptionalContentMembership(library, hashMap)); } else stack.push(hashMap); } // everything else gets pushed onto the stack else { stack.push(hashMap); } } } else if (isTrailer && deepnessCount == 0) { // we have an xref entry HashMap hashMap = new HashMap(); Object obj = stack.pop(); // put all of the dictionary definition into the // the new map. while (!((obj instanceof String) && (obj.equals("<<"))) && !stack.isEmpty()) { Object key = stack.pop(); hashMap.put(key, obj); if (!stack.isEmpty()) { obj = stack.pop(); } else { break; } } return hashMap; } } // found traditional XrefTable found in all documents. else if (nextToken.equals("xref")) { // parse out hte traditional CrossReference xrefTable = new CrossReference(); xrefTable.addXRefTableEntries(this); stack.push(xrefTable); } else if (nextToken.equals("trailer")) { CrossReference xrefTable = null; if (stack.peek() instanceof CrossReference) xrefTable = (CrossReference) stack.pop(); stack.clear(); isTrailer = true; HashMap trailerDictionary = (HashMap) getObject(library); isTrailer = false; return new PTrailer(library, trailerDictionary, xrefTable, null); } // comments else if (nextToken instanceof String && ((String) nextToken).startsWith("%")) { // Comment, ignored for now } // everything else gets pushed onto the stack else { stack.push(nextToken); } if (parseMode == PARSE_MODE_OBJECT_STREAM && deepnessCount == 0 && stack.size() > 0) { return stack.pop(); } } while (!complete); } catch (Exception e) { logger.log(Level.WARNING, "Fatal error parsing PDF file stream.", e); e.printStackTrace(); return null; } // return the top of the stack return stack.pop(); }
diff --git a/src/husacct/analyse/task/HistoryLogger.java b/src/husacct/analyse/task/HistoryLogger.java index 91ec938b..ed86dc90 100644 --- a/src/husacct/analyse/task/HistoryLogger.java +++ b/src/husacct/analyse/task/HistoryLogger.java @@ -1,239 +1,239 @@ package husacct.analyse.task; import husacct.ServiceProvider; import husacct.analyse.IAnalyseService; import husacct.common.OSDetector; import husacct.common.dto.ApplicationDTO; import husacct.common.dto.ProjectDTO; import husacct.control.task.configuration.ConfigurationManager; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.GregorianCalendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; 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; public class HistoryLogger { private IAnalyseService service; private ArrayList<ProjectDTO> projects; private Document doc; private Element rootElement; private String xmlFile = OSDetector.getAppFolder() + ConfigurationManager.getProperty("ApplicationHistoryXMLFilename"); public void logHistory(ApplicationDTO applicationDTO, String workspaceName) { this.service = ServiceProvider.getInstance().getAnalyseService(); File file = new File(xmlFile); if(file.exists()) { addToExistingXml(applicationDTO, workspaceName); } else { if(saveHistory(applicationDTO, workspaceName)) { createXML(doc, rootElement); } } } private boolean saveHistory(ApplicationDTO adto, String workspaceName) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); //Husacct root doc = docBuilder.newDocument(); rootElement = doc.createElement("hussact"); doc.appendChild(rootElement); rootElement.setAttribute("version", adto.version); //Workspace Element workspace = getWorkspace(workspaceName); rootElement.appendChild(workspace); //Application Element application = getApplicationElement(adto); workspace.appendChild(application); for(Element project : getProjectElement(adto)) { application.appendChild(project); } } catch (ParserConfigurationException pce) { pce.printStackTrace(); } return true; } private boolean addToExistingXml(ApplicationDTO adto, String workspaceName) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.parse(xmlFile); Node root = doc.getFirstChild(); NodeList workspaces = root.getChildNodes(); ArrayList<String> workspaceList = new ArrayList<String>(); for(int i = 0; i < workspaces.getLength(); i++) { workspaceList.add(workspaces.item(i).getAttributes().getNamedItem("name").getNodeValue()); } if(workspaceList.contains(workspaceName)) { if(workspaces.item(workspaceList.indexOf(workspaceName)).getAttributes().getNamedItem("name").getNodeValue().equals(workspaceName)) { Node application = workspaces.item(workspaceList.indexOf(workspaceName)).getFirstChild(); if(application.getAttributes().getNamedItem("name").getNodeValue().equals(adto.name)) { NodeList projects = application.getChildNodes(); for(int i = 0; i < projects.getLength(); i++) { Node p = projects.item(i); if(p.getAttributes().getNamedItem("name").getNodeValue().equals(adto.projects.get(i).name)) { p.appendChild(getAnalyseElement((Element) p, adto.projects.get(i))); } else { for(Element project : getProjectElement(adto)) { p.appendChild(project); } } } } else { - Node workspace = workspaces.item(workspaceList.indexOf(workspaceName)).getFirstChild(); + Node workspace = workspaces.item(workspaceList.indexOf(workspaceName)); Node tempApplication = getApplicationElement(adto); for(Element project : getProjectElement(adto)) { tempApplication.appendChild(project); } workspace.appendChild(tempApplication); } } } else { Node workspace = getWorkspace(workspaceName); Node tempApplication = getApplicationElement(adto); for(Element project : getProjectElement(adto)) { tempApplication.appendChild(project); } workspace.appendChild(tempApplication); root.appendChild(workspace); } createXML(doc, (Element)root); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException saxe) { saxe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return true; } private void createXML(Document doc, Element rootElement) { try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(xmlFile)); // Output to console for testing //StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (TransformerException tfe) { tfe.printStackTrace(); } } private Element getWorkspace(String workspaceName) { Element workspace = doc.createElement("workspace"); workspace.setAttribute("name", workspaceName); return workspace; } private Element getApplicationElement(ApplicationDTO adto) { Element application = doc.createElement("application"); application.setAttribute("name", adto.name); return application; } private ArrayList<Element> getProjectElement(ApplicationDTO adto) { projects = adto.projects; ArrayList <Element> projectList = new ArrayList<Element>(); for(ProjectDTO pdto : projects) { Element project = null; project = doc.createElement("project"); project.setAttribute("name", pdto.name); project.appendChild(getAnalyseElement(project, pdto)); projectList.add(project); } return projectList; } private Element getAnalyseElement(Element project, ProjectDTO pdto) { Element analyse = doc.createElement("analyse"); GregorianCalendar cal = new GregorianCalendar(); long millis = cal.getTimeInMillis(); analyse.setAttribute("timestamp", millis + ""); String projectPath = ""; projectPath = pdto.paths.get(0); Element path = doc.createElement("path"); path.appendChild(doc.createTextNode(projectPath)); analyse.appendChild(path); //packages Element packages = doc.createElement("packages"); packages.appendChild(doc.createTextNode(service.getAmountOfPackages() + "")); analyse.appendChild(packages); //classes Element classes = doc.createElement("classes"); classes.appendChild(doc.createTextNode(service.getAmountOfClasses() + "")); analyse.appendChild(classes); //interfaces Element interfaces = doc.createElement("interfaces"); interfaces.appendChild(doc.createTextNode(service.getAmountOfInterfaces() + "")); analyse.appendChild(interfaces); //dependencies Element dependencies = doc.createElement("dependencies"); dependencies.appendChild(doc.createTextNode(service.getAmountOfDependencies() + "")); analyse.appendChild(dependencies); //violations Element violations = doc.createElement("violations"); violations.appendChild(doc.createTextNode("0")); analyse.appendChild(violations); return analyse; } }
true
true
private boolean addToExistingXml(ApplicationDTO adto, String workspaceName) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.parse(xmlFile); Node root = doc.getFirstChild(); NodeList workspaces = root.getChildNodes(); ArrayList<String> workspaceList = new ArrayList<String>(); for(int i = 0; i < workspaces.getLength(); i++) { workspaceList.add(workspaces.item(i).getAttributes().getNamedItem("name").getNodeValue()); } if(workspaceList.contains(workspaceName)) { if(workspaces.item(workspaceList.indexOf(workspaceName)).getAttributes().getNamedItem("name").getNodeValue().equals(workspaceName)) { Node application = workspaces.item(workspaceList.indexOf(workspaceName)).getFirstChild(); if(application.getAttributes().getNamedItem("name").getNodeValue().equals(adto.name)) { NodeList projects = application.getChildNodes(); for(int i = 0; i < projects.getLength(); i++) { Node p = projects.item(i); if(p.getAttributes().getNamedItem("name").getNodeValue().equals(adto.projects.get(i).name)) { p.appendChild(getAnalyseElement((Element) p, adto.projects.get(i))); } else { for(Element project : getProjectElement(adto)) { p.appendChild(project); } } } } else { Node workspace = workspaces.item(workspaceList.indexOf(workspaceName)).getFirstChild(); Node tempApplication = getApplicationElement(adto); for(Element project : getProjectElement(adto)) { tempApplication.appendChild(project); } workspace.appendChild(tempApplication); } } } else { Node workspace = getWorkspace(workspaceName); Node tempApplication = getApplicationElement(adto); for(Element project : getProjectElement(adto)) { tempApplication.appendChild(project); } workspace.appendChild(tempApplication); root.appendChild(workspace); } createXML(doc, (Element)root); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException saxe) { saxe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return true; }
private boolean addToExistingXml(ApplicationDTO adto, String workspaceName) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.parse(xmlFile); Node root = doc.getFirstChild(); NodeList workspaces = root.getChildNodes(); ArrayList<String> workspaceList = new ArrayList<String>(); for(int i = 0; i < workspaces.getLength(); i++) { workspaceList.add(workspaces.item(i).getAttributes().getNamedItem("name").getNodeValue()); } if(workspaceList.contains(workspaceName)) { if(workspaces.item(workspaceList.indexOf(workspaceName)).getAttributes().getNamedItem("name").getNodeValue().equals(workspaceName)) { Node application = workspaces.item(workspaceList.indexOf(workspaceName)).getFirstChild(); if(application.getAttributes().getNamedItem("name").getNodeValue().equals(adto.name)) { NodeList projects = application.getChildNodes(); for(int i = 0; i < projects.getLength(); i++) { Node p = projects.item(i); if(p.getAttributes().getNamedItem("name").getNodeValue().equals(adto.projects.get(i).name)) { p.appendChild(getAnalyseElement((Element) p, adto.projects.get(i))); } else { for(Element project : getProjectElement(adto)) { p.appendChild(project); } } } } else { Node workspace = workspaces.item(workspaceList.indexOf(workspaceName)); Node tempApplication = getApplicationElement(adto); for(Element project : getProjectElement(adto)) { tempApplication.appendChild(project); } workspace.appendChild(tempApplication); } } } else { Node workspace = getWorkspace(workspaceName); Node tempApplication = getApplicationElement(adto); for(Element project : getProjectElement(adto)) { tempApplication.appendChild(project); } workspace.appendChild(tempApplication); root.appendChild(workspace); } createXML(doc, (Element)root); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException saxe) { saxe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return true; }
diff --git a/reseller-huuto/src/main/java/com/abudko/reseller/huuto/query/rules/html/HtmlSearchQueryRules.java b/reseller-huuto/src/main/java/com/abudko/reseller/huuto/query/rules/html/HtmlSearchQueryRules.java index ddd1b39..7a68d55 100644 --- a/reseller-huuto/src/main/java/com/abudko/reseller/huuto/query/rules/html/HtmlSearchQueryRules.java +++ b/reseller-huuto/src/main/java/com/abudko/reseller/huuto/query/rules/html/HtmlSearchQueryRules.java @@ -1,17 +1,17 @@ package com.abudko.reseller.huuto.query.rules.html; import org.springframework.stereotype.Component; import com.abudko.reseller.huuto.query.params.SearchParams; import com.abudko.reseller.huuto.query.rules.SearchQueryRules; @Component public class HtmlSearchQueryRules implements SearchQueryRules { @Override public void apply(SearchParams searchParams) { searchParams.setLocation("Helsinki%20OR%20Espoo%20OR%20Vantaa%20OR%20Kauniainen"); - searchParams.setClassification("1"); - searchParams.setSellstyle("O"); + searchParams.setClassification("new"); + searchParams.setSellstyle("buy-now"); } }
true
true
public void apply(SearchParams searchParams) { searchParams.setLocation("Helsinki%20OR%20Espoo%20OR%20Vantaa%20OR%20Kauniainen"); searchParams.setClassification("1"); searchParams.setSellstyle("O"); }
public void apply(SearchParams searchParams) { searchParams.setLocation("Helsinki%20OR%20Espoo%20OR%20Vantaa%20OR%20Kauniainen"); searchParams.setClassification("new"); searchParams.setSellstyle("buy-now"); }
diff --git a/src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java b/src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java index 67573c992..f23b1d88c 100644 --- a/src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java +++ b/src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java @@ -1,91 +1,91 @@ /* * Copyright 1999-2004 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. */ /* $Id$ */ package org.apache.fop.render.rtf.rtflib.rtfdoc; //Java import java.io.Writer; import java.io.IOException; //FOP import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTextrun; /** Model of an RTF footnote * @author Peter Herweg, [email protected] * @author Marc Wilhelm Kuester */ public class RtfFootnote extends RtfContainer implements IRtfTextrunContainer, IRtfListContainer { RtfTextrun textrunInline = null; RtfContainer body = null; RtfList list = null; boolean bBody = false; /** Create an RTF list item as a child of given container with default attributes */ RtfFootnote(RtfContainer parent, Writer w) throws IOException { super(parent, w); textrunInline = new RtfTextrun(this, writer, null); body = new RtfContainer(this, writer); } public RtfTextrun getTextrun() throws IOException { if (bBody) { RtfTextrun textrun = RtfTextrun.getTextrun(body, writer, null); textrun.setSuppressLastPar(true); return textrun; } else { return textrunInline; } } /** * write RTF code of all our children * @throws IOException for I/O problems */ protected void writeRtfContent() throws IOException { textrunInline.writeRtfContent(); writeGroupMark(true); writeControlWord("footnote"); - writeControlWord("ftnallt"); + writeControlWord("ftnalt"); body.writeRtfContent(); writeGroupMark(false); } public RtfList newList(RtfAttributes attrs) throws IOException { if (list != null) { list.close(); } list = new RtfList(body, writer, attrs); return list; } public void startBody() { bBody = true; } public void endBody() { bBody = false; } }
true
true
protected void writeRtfContent() throws IOException { textrunInline.writeRtfContent(); writeGroupMark(true); writeControlWord("footnote"); writeControlWord("ftnallt"); body.writeRtfContent(); writeGroupMark(false); }
protected void writeRtfContent() throws IOException { textrunInline.writeRtfContent(); writeGroupMark(true); writeControlWord("footnote"); writeControlWord("ftnalt"); body.writeRtfContent(); writeGroupMark(false); }
diff --git a/src/main/java/org/jfrog/hudson/maven3/Maven3Builder.java b/src/main/java/org/jfrog/hudson/maven3/Maven3Builder.java index c78538b3..fcb64479 100644 --- a/src/main/java/org/jfrog/hudson/maven3/Maven3Builder.java +++ b/src/main/java/org/jfrog/hudson/maven3/Maven3Builder.java @@ -1,345 +1,345 @@ /* * Copyright (C) 2010 JFrog Ltd. * * 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.jfrog.hudson.maven3; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.model.*; import hudson.remoting.VirtualChannel; import hudson.remoting.Which; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.SlaveComputer; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.tasks.Maven; import hudson.tools.ToolInstallation; import hudson.tools.ToolLocationNodeProperty; import hudson.util.ArgumentListBuilder; import hudson.util.DescribableList; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.jfrog.build.api.BuildInfoConfigProperties; import org.jfrog.build.extractor.maven.Maven3BuildInfoLogger; import org.jfrog.hudson.util.PluginDependencyHelper; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLDecoder; import java.util.List; /** * Maven3 builder. Hudson 1.392 added native support for maven 3 but this one is useful for free style. * * @author Yossi Shaul */ public class Maven3Builder extends Builder { public static final String CLASSWORLDS_LAUNCHER = "org.codehaus.plexus.classworlds.launcher.Launcher"; private final String mavenName; private final String rootPom; private final String goals; private final String mavenOpts; @DataBoundConstructor public Maven3Builder(String mavenName, String rootPom, String goals, String mavenOpts) { this.mavenName = mavenName; this.rootPom = rootPom; this.goals = goals; this.mavenOpts = mavenOpts; } public String getMavenName() { return mavenName; } public String getRootPom() { return rootPom; } public String getGoals() { return goals; } public String getMavenOpts() { return mavenOpts; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { EnvVars env = build.getEnvironment(listener); FilePath workDir = build.getModuleRoot(); ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env); StringBuilder javaPathBuilder = new StringBuilder(); JDK configuredJdk = build.getProject().getJDK(); if (configuredJdk != null) { javaPathBuilder.append(build.getProject().getJDK().getBinDir().getCanonicalPath()).append(File.separator); } javaPathBuilder.append("java"); if (!launcher.isUnix()) { javaPathBuilder.append(".exe"); } String[] cmds = cmdLine.toCommandArray(); try { //listener.getLogger().println("Executing: " + cmdLine.toStringWithQuote()); int exitValue = launcher.launch().cmds(new File(javaPathBuilder.toString()), cmds).envs(env).stdout(listener) .pwd(workDir).join(); boolean success = (exitValue == 0); build.setResult(success ? Result.SUCCESS : Result.FAILURE); return success; } catch (IOException e) { Util.displayIOException(e, listener); e.printStackTrace(listener.fatalError("command execution failed")); build.setResult(Result.FAILURE); return false; } } private ArgumentListBuilder buildMavenCmdLine(AbstractBuild<?, ?> build, BuildListener listener, EnvVars env) throws IOException, InterruptedException { FilePath mavenHome = getMavenHomeDir(build, listener, env); if (!mavenHome.exists()) { listener.error("Couldn't find Maven home: " + mavenHome.getRemote()); throw new Run.RunnerAbortedException(); } ArgumentListBuilder args = new ArgumentListBuilder(); FilePath mavenBootDir = new FilePath(mavenHome, "boot"); FilePath[] classworldsCandidates = mavenBootDir.list("plexus-classworlds*.jar"); if (classworldsCandidates == null || classworldsCandidates.length == 0) { listener.error("Couldn't find classworlds jar under " + mavenBootDir.getRemote()); throw new Run.RunnerAbortedException(); } FilePath classWorldsJar = classworldsCandidates[0]; // classpath args.add("-classpath"); //String cpSeparator = launcher.isUnix() ? ":" : ";"; args.add(classWorldsJar.getRemote()); String buildInfoPropertiesFile = env.get(BuildInfoConfigProperties.PROP_PROPS_FILE); boolean artifactoryIntegration = StringUtils.isNotBlank(buildInfoPropertiesFile); if (artifactoryIntegration) { args.addKeyValuePair("-D", BuildInfoConfigProperties.PROP_PROPS_FILE, buildInfoPropertiesFile, false); } // maven home args.addKeyValuePair("-D", "maven.home", mavenHome.getRemote(), false); String classworldsConfPath; if (artifactoryIntegration) { // use the classworlds conf packaged with this plugin and resolve the extractor libs File maven3ExtractorJar = Which.jarFile(Maven3BuildInfoLogger.class); FilePath actualDependencyDirectory = PluginDependencyHelper.getActualDependencyDirectory(build, maven3ExtractorJar); - if (StringUtils.isNotBlank(getMavenOpts()) && !getMavenOpts().contains("m3plugin.lib")) { + if (getMavenOpts() == null || !getMavenOpts().contains("-Dm3plugin.lib")) { args.addKeyValuePair("-D", "m3plugin.lib", actualDependencyDirectory.getRemote(), false); } URL classworldsResource = getClass().getClassLoader().getResource("org/jfrog/hudson/maven3/classworlds-freestyle.conf"); File classworldsConfFile = new File(URLDecoder.decode(classworldsResource.getFile(), "utf-8")); if (!classworldsConfFile.exists()) { listener.error("Unable to locate classworlds configuration file under " + classworldsConfFile.getAbsolutePath()); throw new Run.RunnerAbortedException(); } //If we are on a remote slave, make a temp copy of the customized classworlds conf if (Computer.currentComputer() instanceof SlaveComputer) { FilePath remoteClassworlds = build.getWorkspace().createTextTempFile("classworlds", "conf", "", false); remoteClassworlds.copyFrom(classworldsResource); classworldsConfPath = remoteClassworlds.getRemote(); } else { classworldsConfPath = classworldsConfFile.getCanonicalPath(); } } else { classworldsConfPath = new FilePath(mavenHome, "bin/m2.conf").getRemote(); } args.addKeyValuePair("-D", "classworlds.conf", classworldsConfPath, false); // maven opts if (StringUtils.isNotBlank(getMavenOpts())) { String mavenOpts = Util.replaceMacro(getMavenOpts(), build.getBuildVariableResolver()); args.add(mavenOpts); } // classworlds launcher main class args.add(CLASSWORLDS_LAUNCHER); // pom file to build String rootPom = getRootPom(); if (StringUtils.isNotBlank(rootPom)) { args.add("-f", rootPom); } // maven goals args.addTokenized(getGoals()); return args; } private FilePath getMavenHomeDir(AbstractBuild<?, ?> build, BuildListener listener, EnvVars env) { Computer computer = Computer.currentComputer(); VirtualChannel virtualChannel = computer.getChannel(); String mavenHome = null; //Check for a node defined tool if we are on a slave if (computer instanceof SlaveComputer) { mavenHome = getNodeDefinedMavenHome(build); } //Either we are on the master or that no node tool was defined if (StringUtils.isBlank(mavenHome)) { mavenHome = getJobDefinedMavenInstallation(listener, virtualChannel); } //Try to find the home via the env vars if (StringUtils.isBlank(mavenHome)) { mavenHome = getEnvDefinedMavenHome(env); } return new FilePath(virtualChannel, mavenHome); } private String getNodeDefinedMavenHome(AbstractBuild<?, ?> build) { Node currentNode = build.getBuiltOn(); DescribableList<NodeProperty<?>, NodePropertyDescriptor> properties = currentNode.getNodeProperties(); ToolLocationNodeProperty toolLocation = properties.get(ToolLocationNodeProperty.class); if (toolLocation != null) { List<ToolLocationNodeProperty.ToolLocation> locations = toolLocation.getLocations(); if (locations != null) { for (ToolLocationNodeProperty.ToolLocation location : locations) { if (location.getType().isSubTypeOf(Maven.MavenInstallation.class)) { String installationHome = location.getHome(); if (StringUtils.isNotBlank(installationHome)) { return installationHome; } } } } } return null; } private String getEnvDefinedMavenHome(EnvVars env) { String mavenHome = env.get("MAVEN_HOME"); if (StringUtils.isNotBlank(mavenHome)) { return mavenHome; } return env.get("M2_HOME"); } private String getJobDefinedMavenInstallation(BuildListener listener, VirtualChannel channel) { Maven.MavenInstallation mvn = getMavenInstallation(); if (mvn == null) { listener.error("Maven version is not configured for this project. Can't determine which Maven to run"); throw new Run.RunnerAbortedException(); } String mvnHome = mvn.getHome(); if (mvnHome == null) { listener.error("Maven '%s' doesn't have its home set", mvn.getName()); throw new Run.RunnerAbortedException(); } return mvnHome; } public Maven.MavenInstallation getMavenInstallation() { Maven.MavenInstallation[] installations = getDescriptor().getInstallations(); for (Maven.MavenInstallation installation : installations) { if (installation.getName().equals(mavenName)) { return installation; } } // not found, return the first installation if exists return installations.length > 0 ? installations[0] : null; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { public DescriptorImpl() { load(); } protected DescriptorImpl(Class<? extends Maven3Builder> clazz) { super(clazz); } /** * Obtains the {@link hudson.tasks.Maven.MavenInstallation.DescriptorImpl} instance. */ public Maven.MavenInstallation.DescriptorImpl getToolDescriptor() { return ToolInstallation.all().get(Maven.MavenInstallation.DescriptorImpl.class); } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return jobType.equals(FreeStyleProject.class); } @Override public String getHelpFile() { return "/plugin/artifactory/maven3/help.html"; } @Override public String getDisplayName() { return Messages.step_displayName(); } public Maven.DescriptorImpl getMavenDescriptor() { return Hudson.getInstance().getDescriptorByType(Maven.DescriptorImpl.class); } public Maven.MavenInstallation[] getInstallations() { return getMavenDescriptor().getInstallations(); } @Override public Maven3Builder newInstance(StaplerRequest request, JSONObject formData) throws FormException { return (Maven3Builder) request.bindJSON(clazz, formData); } } }
true
true
private ArgumentListBuilder buildMavenCmdLine(AbstractBuild<?, ?> build, BuildListener listener, EnvVars env) throws IOException, InterruptedException { FilePath mavenHome = getMavenHomeDir(build, listener, env); if (!mavenHome.exists()) { listener.error("Couldn't find Maven home: " + mavenHome.getRemote()); throw new Run.RunnerAbortedException(); } ArgumentListBuilder args = new ArgumentListBuilder(); FilePath mavenBootDir = new FilePath(mavenHome, "boot"); FilePath[] classworldsCandidates = mavenBootDir.list("plexus-classworlds*.jar"); if (classworldsCandidates == null || classworldsCandidates.length == 0) { listener.error("Couldn't find classworlds jar under " + mavenBootDir.getRemote()); throw new Run.RunnerAbortedException(); } FilePath classWorldsJar = classworldsCandidates[0]; // classpath args.add("-classpath"); //String cpSeparator = launcher.isUnix() ? ":" : ";"; args.add(classWorldsJar.getRemote()); String buildInfoPropertiesFile = env.get(BuildInfoConfigProperties.PROP_PROPS_FILE); boolean artifactoryIntegration = StringUtils.isNotBlank(buildInfoPropertiesFile); if (artifactoryIntegration) { args.addKeyValuePair("-D", BuildInfoConfigProperties.PROP_PROPS_FILE, buildInfoPropertiesFile, false); } // maven home args.addKeyValuePair("-D", "maven.home", mavenHome.getRemote(), false); String classworldsConfPath; if (artifactoryIntegration) { // use the classworlds conf packaged with this plugin and resolve the extractor libs File maven3ExtractorJar = Which.jarFile(Maven3BuildInfoLogger.class); FilePath actualDependencyDirectory = PluginDependencyHelper.getActualDependencyDirectory(build, maven3ExtractorJar); if (StringUtils.isNotBlank(getMavenOpts()) && !getMavenOpts().contains("m3plugin.lib")) { args.addKeyValuePair("-D", "m3plugin.lib", actualDependencyDirectory.getRemote(), false); } URL classworldsResource = getClass().getClassLoader().getResource("org/jfrog/hudson/maven3/classworlds-freestyle.conf"); File classworldsConfFile = new File(URLDecoder.decode(classworldsResource.getFile(), "utf-8")); if (!classworldsConfFile.exists()) { listener.error("Unable to locate classworlds configuration file under " + classworldsConfFile.getAbsolutePath()); throw new Run.RunnerAbortedException(); } //If we are on a remote slave, make a temp copy of the customized classworlds conf if (Computer.currentComputer() instanceof SlaveComputer) { FilePath remoteClassworlds = build.getWorkspace().createTextTempFile("classworlds", "conf", "", false); remoteClassworlds.copyFrom(classworldsResource); classworldsConfPath = remoteClassworlds.getRemote(); } else { classworldsConfPath = classworldsConfFile.getCanonicalPath(); } } else { classworldsConfPath = new FilePath(mavenHome, "bin/m2.conf").getRemote(); } args.addKeyValuePair("-D", "classworlds.conf", classworldsConfPath, false); // maven opts if (StringUtils.isNotBlank(getMavenOpts())) { String mavenOpts = Util.replaceMacro(getMavenOpts(), build.getBuildVariableResolver()); args.add(mavenOpts); } // classworlds launcher main class args.add(CLASSWORLDS_LAUNCHER); // pom file to build String rootPom = getRootPom(); if (StringUtils.isNotBlank(rootPom)) { args.add("-f", rootPom); } // maven goals args.addTokenized(getGoals()); return args; }
private ArgumentListBuilder buildMavenCmdLine(AbstractBuild<?, ?> build, BuildListener listener, EnvVars env) throws IOException, InterruptedException { FilePath mavenHome = getMavenHomeDir(build, listener, env); if (!mavenHome.exists()) { listener.error("Couldn't find Maven home: " + mavenHome.getRemote()); throw new Run.RunnerAbortedException(); } ArgumentListBuilder args = new ArgumentListBuilder(); FilePath mavenBootDir = new FilePath(mavenHome, "boot"); FilePath[] classworldsCandidates = mavenBootDir.list("plexus-classworlds*.jar"); if (classworldsCandidates == null || classworldsCandidates.length == 0) { listener.error("Couldn't find classworlds jar under " + mavenBootDir.getRemote()); throw new Run.RunnerAbortedException(); } FilePath classWorldsJar = classworldsCandidates[0]; // classpath args.add("-classpath"); //String cpSeparator = launcher.isUnix() ? ":" : ";"; args.add(classWorldsJar.getRemote()); String buildInfoPropertiesFile = env.get(BuildInfoConfigProperties.PROP_PROPS_FILE); boolean artifactoryIntegration = StringUtils.isNotBlank(buildInfoPropertiesFile); if (artifactoryIntegration) { args.addKeyValuePair("-D", BuildInfoConfigProperties.PROP_PROPS_FILE, buildInfoPropertiesFile, false); } // maven home args.addKeyValuePair("-D", "maven.home", mavenHome.getRemote(), false); String classworldsConfPath; if (artifactoryIntegration) { // use the classworlds conf packaged with this plugin and resolve the extractor libs File maven3ExtractorJar = Which.jarFile(Maven3BuildInfoLogger.class); FilePath actualDependencyDirectory = PluginDependencyHelper.getActualDependencyDirectory(build, maven3ExtractorJar); if (getMavenOpts() == null || !getMavenOpts().contains("-Dm3plugin.lib")) { args.addKeyValuePair("-D", "m3plugin.lib", actualDependencyDirectory.getRemote(), false); } URL classworldsResource = getClass().getClassLoader().getResource("org/jfrog/hudson/maven3/classworlds-freestyle.conf"); File classworldsConfFile = new File(URLDecoder.decode(classworldsResource.getFile(), "utf-8")); if (!classworldsConfFile.exists()) { listener.error("Unable to locate classworlds configuration file under " + classworldsConfFile.getAbsolutePath()); throw new Run.RunnerAbortedException(); } //If we are on a remote slave, make a temp copy of the customized classworlds conf if (Computer.currentComputer() instanceof SlaveComputer) { FilePath remoteClassworlds = build.getWorkspace().createTextTempFile("classworlds", "conf", "", false); remoteClassworlds.copyFrom(classworldsResource); classworldsConfPath = remoteClassworlds.getRemote(); } else { classworldsConfPath = classworldsConfFile.getCanonicalPath(); } } else { classworldsConfPath = new FilePath(mavenHome, "bin/m2.conf").getRemote(); } args.addKeyValuePair("-D", "classworlds.conf", classworldsConfPath, false); // maven opts if (StringUtils.isNotBlank(getMavenOpts())) { String mavenOpts = Util.replaceMacro(getMavenOpts(), build.getBuildVariableResolver()); args.add(mavenOpts); } // classworlds launcher main class args.add(CLASSWORLDS_LAUNCHER); // pom file to build String rootPom = getRootPom(); if (StringUtils.isNotBlank(rootPom)) { args.add("-f", rootPom); } // maven goals args.addTokenized(getGoals()); return args; }
diff --git a/tools/host/src/com/android/cts/CtsTestResult.java b/tools/host/src/com/android/cts/CtsTestResult.java index 0aea74b3..851b07d3 100644 --- a/tools/host/src/com/android/cts/CtsTestResult.java +++ b/tools/host/src/com/android/cts/CtsTestResult.java @@ -1,203 +1,209 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.cts; import junit.framework.TestFailure; import junit.framework.TestResult; import java.util.Enumeration; import java.util.HashMap; /** * Store the result of a specific test. */ public class CtsTestResult { private int mResultCode; private String mFailedMessage; private String mStackTrace; public static final int CODE_INIT = -1; public static final int CODE_NOT_EXECUTED = 0; public static final int CODE_PASS = 1; public static final int CODE_FAIL = 2; public static final int CODE_ERROR = 3; public static final int CODE_TIMEOUT = 4; public static final int CODE_OMITTED = 5; public static final int CODE_FIRST = CODE_INIT; public static final int CODE_LAST = CODE_OMITTED; public static final String STR_ERROR = "error"; public static final String STR_TIMEOUT = "timeout"; public static final String STR_NOT_EXECUTED = "notExecuted"; public static final String STR_OMITTED = "omitted"; public static final String STR_FAIL = "fail"; public static final String STR_PASS = "pass"; private static HashMap<Integer, String> sCodeToResultMap; private static HashMap<String, Integer> sResultToCodeMap; static { sCodeToResultMap = new HashMap<Integer, String>(); sCodeToResultMap.put(CODE_NOT_EXECUTED, STR_NOT_EXECUTED); sCodeToResultMap.put(CODE_PASS, STR_PASS); sCodeToResultMap.put(CODE_FAIL, STR_FAIL); sCodeToResultMap.put(CODE_ERROR, STR_ERROR); sCodeToResultMap.put(CODE_TIMEOUT, STR_TIMEOUT); sCodeToResultMap.put(CODE_OMITTED, STR_OMITTED); sResultToCodeMap = new HashMap<String, Integer>(); for (int code : sCodeToResultMap.keySet()) { sResultToCodeMap.put(sCodeToResultMap.get(code), code); } } public CtsTestResult(int resCode) { mResultCode = resCode; } public CtsTestResult(int resCode, final String failedMessage, final String stackTrace) { mResultCode = resCode; mFailedMessage = failedMessage; mStackTrace = stackTrace; } public CtsTestResult(final String result, final String failedMessage, final String stackTrace) throws InvalidTestResultStringException { if (!sResultToCodeMap.containsKey(result)) { throw new InvalidTestResultStringException(result); } mResultCode = sResultToCodeMap.get(result); mFailedMessage = failedMessage; mStackTrace = stackTrace; } /** * Check if the result indicates failure. * * @return If failed, return true; else, return false. */ public boolean isFail() { return mResultCode == CODE_FAIL; } /** * Check if the result indicates pass. * * @return If pass, return true; else, return false. */ public boolean isPass() { return mResultCode == CODE_PASS; } /** * Check if the result indicates not executed. * * @return If not executed, return true; else, return false. */ public boolean isNotExecuted() { return mResultCode == CODE_NOT_EXECUTED; } /** * Get result code of the test. * * @return The result code of the test. * The following is the possible result codes: * <ul> * <li> notExecuted * <li> pass * <li> fail * <li> error * <li> timeout * </ul> */ public int getResultCode() { return mResultCode; } /** * Get the failed message. * * @return The failed message. */ public String getFailedMessage() { return mFailedMessage; } /** * Get the stack trace. * * @return The stack trace. */ public String getStackTrace() { return mStackTrace; } /** * Set the result. * * @param testResult The result in the form of JUnit test result. */ @SuppressWarnings("unchecked") public void setResult(TestResult testResult) { int resCode = CODE_PASS; String failedMessage = null; String stackTrace = null; - if ((testResult != null) && (testResult.failureCount() > 0)) { + if ((testResult != null) && (testResult.failureCount() > 0 || testResult.errorCount() > 0)) { resCode = CODE_FAIL; Enumeration<TestFailure> failures = testResult.failures(); while (failures.hasMoreElements()) { TestFailure failure = failures.nextElement(); failedMessage += failure.exceptionMessage(); stackTrace += failure.trace(); } + Enumeration<TestFailure> errors = testResult.errors(); + while (errors.hasMoreElements()) { + TestFailure failure = errors.nextElement(); + failedMessage += failure.exceptionMessage(); + stackTrace += failure.trace(); + } } mResultCode = resCode; mFailedMessage = failedMessage; mStackTrace = stackTrace; } /** * Reverse the result code. */ public void reverse() { if (isPass()) { mResultCode = CtsTestResult.CODE_FAIL; } else if (isFail()){ mResultCode = CtsTestResult.CODE_PASS; } } /** * Get the test result as string. * * @return The readable result string. */ public String getResultString() { return sCodeToResultMap.get(mResultCode); } /** * Check if the given resultType is a valid result type defined.. * * @param resultType The result type to be checked. * @return If valid, return true; else, return false. */ static public boolean isValidResultType(final String resultType) { return sResultToCodeMap.containsKey(resultType); } }
false
true
public void setResult(TestResult testResult) { int resCode = CODE_PASS; String failedMessage = null; String stackTrace = null; if ((testResult != null) && (testResult.failureCount() > 0)) { resCode = CODE_FAIL; Enumeration<TestFailure> failures = testResult.failures(); while (failures.hasMoreElements()) { TestFailure failure = failures.nextElement(); failedMessage += failure.exceptionMessage(); stackTrace += failure.trace(); } } mResultCode = resCode; mFailedMessage = failedMessage; mStackTrace = stackTrace; }
public void setResult(TestResult testResult) { int resCode = CODE_PASS; String failedMessage = null; String stackTrace = null; if ((testResult != null) && (testResult.failureCount() > 0 || testResult.errorCount() > 0)) { resCode = CODE_FAIL; Enumeration<TestFailure> failures = testResult.failures(); while (failures.hasMoreElements()) { TestFailure failure = failures.nextElement(); failedMessage += failure.exceptionMessage(); stackTrace += failure.trace(); } Enumeration<TestFailure> errors = testResult.errors(); while (errors.hasMoreElements()) { TestFailure failure = errors.nextElement(); failedMessage += failure.exceptionMessage(); stackTrace += failure.trace(); } } mResultCode = resCode; mFailedMessage = failedMessage; mStackTrace = stackTrace; }
diff --git a/src/com/engine9/FavouriteActivity.java b/src/com/engine9/FavouriteActivity.java index acff377..f124168 100644 --- a/src/com/engine9/FavouriteActivity.java +++ b/src/com/engine9/FavouriteActivity.java @@ -1,42 +1,42 @@ package com.engine9; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; /*Add and save the favourite services*/ public class FavouriteActivity extends Activity { private ListView favList; //create a list to store the favourite services private FavouriteAdapter adapter; private EditText favText; protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_favourite); favList = (ListView) findViewById(R.id.listView1); adapter = new FavouriteAdapter(getApplicationContext(), FavouriteManager.getFavourites(getApplicationContext())); Log.d("DEBUG", String.valueOf(adapter.getCount())); favList.setAdapter(adapter); - favText = (EditText) findViewById(R.id.fav_text); + favText = (EditText) findViewById(R.id.fav_text1); } public void onAddButtonPush(View view) { if (!FavouriteManager.inFavourites(getApplicationContext(), favText.getText().toString())) { FavouriteManager.AddFavourite(favText.getText().toString(), getApplicationContext()); adapter.clear(); adapter.addAll(FavouriteManager.getFavourites(getApplicationContext())); adapter.notifyDataSetChanged(); } } }
true
true
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_favourite); favList = (ListView) findViewById(R.id.listView1); adapter = new FavouriteAdapter(getApplicationContext(), FavouriteManager.getFavourites(getApplicationContext())); Log.d("DEBUG", String.valueOf(adapter.getCount())); favList.setAdapter(adapter); favText = (EditText) findViewById(R.id.fav_text); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_favourite); favList = (ListView) findViewById(R.id.listView1); adapter = new FavouriteAdapter(getApplicationContext(), FavouriteManager.getFavourites(getApplicationContext())); Log.d("DEBUG", String.valueOf(adapter.getCount())); favList.setAdapter(adapter); favText = (EditText) findViewById(R.id.fav_text1); }
diff --git a/org.whole.lang.e4.ui/src/org/whole/lang/e4/ui/dialogs/E4FindReplaceDialog.java b/org.whole.lang.e4.ui/src/org/whole/lang/e4/ui/dialogs/E4FindReplaceDialog.java index d6e896dd5..07fd071d7 100644 --- a/org.whole.lang.e4.ui/src/org/whole/lang/e4/ui/dialogs/E4FindReplaceDialog.java +++ b/org.whole.lang.e4.ui/src/org/whole/lang/e4/ui/dialogs/E4FindReplaceDialog.java @@ -1,416 +1,416 @@ /** * Copyright 2004-2013 Riccardo Solmi. All rights reserved. * This file is part of the Whole Platform. * * The Whole Platform 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. * * The Whole Platform 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 the Whole Platform. If not, see <http://www.gnu.org/licenses/>. */ package org.whole.lang.e4.ui.dialogs; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.eclipse.e4.core.contexts.Active; import org.eclipse.e4.core.contexts.ContextInjectionFactory; import org.eclipse.e4.core.contexts.EclipseContextFactory; import org.eclipse.e4.core.contexts.IEclipseContext; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.ui.model.application.ui.basic.MPart; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.gef.ContextMenuProvider; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Point; 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.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.whole.lang.bindings.IBindingManager; import org.whole.lang.commons.factories.CommonsEntityFactory; import org.whole.lang.e4.ui.actions.ActionRegistry; import org.whole.lang.e4.ui.actions.E4KeyHandler; import org.whole.lang.e4.ui.actions.E4NavigationKeyHandler; import org.whole.lang.e4.ui.actions.IUIConstants; import org.whole.lang.e4.ui.util.E4Utils; import org.whole.lang.e4.ui.viewers.E4GraphicalViewer; import org.whole.lang.iterators.IteratorFactory; import org.whole.lang.iterators.MatcherIterator; import org.whole.lang.model.IEntity; import org.whole.lang.ui.commands.ModelTransactionCommand; import org.whole.lang.ui.editparts.IEntityPart; import org.whole.lang.ui.editparts.IPartFocusListener; import org.whole.lang.ui.viewers.IEntityPartViewer; import org.whole.lang.util.EntityUtils; /** * @author Enrico Persiani */ @Singleton public class E4FindReplaceDialog extends E4Dialog { private static final int FIND_ID = IDialogConstants.CLIENT_ID + 1; private static final int REPLACE_ID = IDialogConstants.CLIENT_ID + 2; private static final int REPLACE_FIND_ID = IDialogConstants.CLIENT_ID + 3; private static final int REPLACE_ALL_ID = IDialogConstants.CLIENT_ID + 4; private static final int VIEWER_MINIMUM_HEIGHT = 200; private static final int VIEWER_MINIMUM_WIDTH = 400; protected MatcherIterator<IEntity> iterator; protected IBindingManager selection; protected boolean selectionTracking; protected Control replaceArea; protected E4GraphicalViewer replaceViewer; protected ActionRegistry replaceActionRegistry; protected Control buttonPanel; protected Control statusPanel; protected Label statusLabel; protected IEntity foundEntity; protected boolean freshTemplate; @Inject public E4FindReplaceDialog(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell) { super(shell); setShellStyle(SWT.CLOSE | SWT.MODELESS | SWT.RESIZE | SWT.TITLE); this.iterator = IteratorFactory.descendantOrSelfMatcherIterator(); enableSelectionTracking(true); clearFoundEntity(); clearFreshTemplate(); } @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(IUIConstants.FIND_REPLACE_DIALOG_TEXT); setBlockOnOpen(false); } @Override protected Control createDialogArea(Composite parent) { SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL | SWT.SMOOTH); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); super.createDialogArea(sashForm); this.replaceArea = createReplaceArea(sashForm); return sashForm; } protected Control createReplaceArea(Composite parent) { IEclipseContext params = EclipseContextFactory.create(); params.set("parent", parent); replaceViewer = ContextInjectionFactory.make(E4GraphicalViewer.class, context, params); replaceViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); replaceViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { updateSelection(E4Utils.createSelectionBindings(event, context)); } }); replaceViewer.getControl().addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { context.remove(IEntityPartViewer.class); context.remove(ActionRegistry.class); } @SuppressWarnings("unchecked") @Override public void focusGained(FocusEvent e) { context.set(IEntityPartViewer.class, replaceViewer); context.set(ActionRegistry.class, replaceActionRegistry); updateSelection(E4Utils.createSelectionBindings(replaceViewer.getSelectedEditParts(), replaceViewer, context)); } }); - viewer.addPartFocusListener(new IPartFocusListener() { + replaceViewer.addPartFocusListener(new IPartFocusListener() { @SuppressWarnings("unchecked") public void focusChanged(IEntityPart oldPart, IEntityPart newPart) { - updateSelection(E4Utils.createSelectionBindings(viewer.getSelectedEditParts(), viewer, context)); + updateSelection(E4Utils.createSelectionBindings(replaceViewer.getSelectedEditParts(), replaceViewer, context)); } }); E4KeyHandler keyHandler = new E4KeyHandler(context); keyHandler.setParent(new E4NavigationKeyHandler(context)); replaceViewer.setKeyHandler(keyHandler); replaceViewer.setEntityContents(createDefaultContents()); context.set(IEntityPartViewer.class, replaceViewer); replaceActionRegistry = ContextInjectionFactory.make(ActionRegistry.class, context); replaceActionRegistry.registerWorkbenchActions(); context.set(ActionRegistry.class, replaceActionRegistry); replaceViewer.setContextMenu(new ContextMenuProvider(replaceViewer) { @Override public void buildContextMenu(IMenuManager menuManager) { contextMenuProvider.populate(menuManager); } }); return parent; } @Override protected Control createButtonBar(Composite parent) { buttonPanel = createButtonPanel(parent); statusPanel = createStatusPanel(parent); return buttonPanel; } protected Control createButtonPanel(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(-2, false); composite.setLayout(layout); //FIXME workaround to prevent button reordering on Shell.setDefaultButton() final Button button = createButton(composite, FIND_ID, IUIConstants.FIND_BUTTON_TEXT, false); getShell().addShellListener(new ShellAdapter() { @Override public void shellActivated(ShellEvent e) { ((Shell) e.widget).setDefaultButton(button); } }); createButton(composite, REPLACE_ID, IUIConstants.REPLACE_BUTTON_TEXT, false); createButton(composite, REPLACE_FIND_ID, IUIConstants.REPLACE_FIND_BUTTON_TEXT, false); createButton(composite, REPLACE_ALL_ID, IUIConstants.REPLACE_ALL_BUTTON_TEXT, false); composite.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, true, false)); return composite; } protected Control createStatusPanel(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(1, false); composite.setLayout(layout); statusLabel = new Label(composite, SWT.LEFT); statusLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); Button button = createButton(composite, IDialogConstants.CLOSE_ID, "Close", false); GridData gridData = (GridData) button.getLayoutData(); gridData.horizontalAlignment = SWT.RIGHT; gridData.verticalAlignment = SWT.BOTTOM; gridData.grabExcessHorizontalSpace = gridData.grabExcessVerticalSpace = false; composite.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false)); return composite; } protected void updateButtonsEnablement(boolean enabled) { Button button = getButton(REPLACE_FIND_ID); if (button != null) button.setEnabled(enabled); button = getButton(REPLACE_ID); if (button != null) button.setEnabled(enabled); } protected Control getButtonPanel() { return buttonPanel; } protected Control getStatusPanel() { return statusPanel; } protected void setStatusMessage(String message) { statusLabel.setText(message); } @Override protected void buttonPressed(int buttonId) { super.buttonPressed(buttonId); clearFreshTemplate(); boolean state = enableSelectionTracking(false); try { switch (buttonId) { case FIND_ID: doFind(); break; case REPLACE_ID: doReplace(true); break; case REPLACE_FIND_ID: doReplace(false); doFind(); break; case REPLACE_ALL_ID: doReplaceAll(); break; case IDialogConstants.CLOSE_ID: default: okPressed(); break; } } finally { enableSelectionTracking(state); } } protected void doFind() { iterator.withPattern(viewer.getEntityContents()); if (findNext(true)) selectAndReveal(getFoundEntity()); } protected void doReplace(boolean updateSelection) { if (!hasFoundEntity()) return; final IEntity replacement = EntityUtils.clone(replaceViewer.getEntityContents()); ModelTransactionCommand command = new ModelTransactionCommand(); try { command.setModel(getFoundEntity()); command.begin(); iterator.set(replacement); command.commit(); } catch (Exception e) { command.rollback(); } finally { clearFoundEntity(); } IEntityPartViewer viewer = (IEntityPartViewer) selection.wGetValue("viewer"); viewer.getCommandStack().execute(command); if (updateSelection) { Control control = viewer.getControl(); control.getDisplay().asyncExec(new Runnable() { @Override public void run() { boolean state = enableSelectionTracking(false); selectAndReveal(replacement); enableSelectionTracking(state); } }); } } protected void doReplaceAll() { IEntity self = selection.wGet("self"); iterator.reset(self); if (!findNext(true)) return; boolean state = enableSelectionTracking(false); IEntity replacement = replaceViewer.getEntityContents(); ModelTransactionCommand command = new ModelTransactionCommand(); command.setModel(getFoundEntity()); try { command.begin(); do { iterator.set(replacement = EntityUtils.clone(replacement)); } while (findNext(true)); command.commit(); } catch (Exception e) { command.rollback(); } finally { clearFoundEntity(); } IEntityPartViewer viewer = (IEntityPartViewer) selection.wGetValue("viewer"); viewer.getCommandStack().execute(command); Control control = viewer.getControl(); final IEntity revealEntity = replacement; control.getDisplay().asyncExec(new Runnable() { @Override public void run() { boolean state = enableSelectionTracking(false); selectAndReveal(revealEntity); enableSelectionTracking(state); } }); enableSelectionTracking(state); } protected void selectAndReveal(IEntity entity) { IEntityPartViewer viewer = (IEntityPartViewer) selection.wGetValue("viewer"); viewer.selectAndReveal(entity); } @Inject protected void setSelection(@Optional @Named(IServiceConstants.ACTIVE_SELECTION) IBindingManager selection,@Named(IServiceConstants.ACTIVE_PART) Object aPart, @Active MPart activePart, MPart part) { if (selection == null || !isSelectionTracking() || selection.wGetValue("viewer") == viewer || selection.wGetValue("viewer") == replaceViewer) return; this.selection = selection.clone(); IEntity self = this.selection.wGet("self"); iterator.reset(self); if (this.selection.wIsSet("primarySelectedEntity")) { IEntity primarySelectedEntity = this.selection.wGet("primarySelectedEntity"); if (primarySelectedEntity != self) { iterator.skipToSame(primarySelectedEntity); if (isFreshTemplate()) findNext(false); } } } protected boolean isSelectionTracking() { return selectionTracking; } protected boolean enableSelectionTracking(boolean enable) { boolean state = selectionTracking; selectionTracking = enable; return state; } protected boolean findNext(boolean updateStatus) { boolean hasNext = iterator.hasNext(); foundEntity = hasNext ? iterator.next() : null; updateButtonsEnablement(hasNext); if (updateStatus) setStatusMessage(hasNext ? "" : IUIConstants.PATTERN_NOT_FOUND_TEXT); return hasNext; } protected void clearFoundEntity() { foundEntity = null; updateButtonsEnablement(false); } protected IEntity getFoundEntity() { return foundEntity; } protected boolean hasFoundEntity() { return foundEntity != null; } protected void setFreshTemplate() { this.freshTemplate = true; } protected void clearFreshTemplate() { this.freshTemplate = false; } protected boolean isFreshTemplate() { return freshTemplate; } public void setTemplate(IEntity template) { viewer.setEntityContents(template); replaceViewer.setEntityContents(CommonsEntityFactory.instance.createResolver()); // set dialog minimum size Point buttonBarSize = getStatusPanel().getSize(); Point buttonPanelSize = getButtonPanel().getSize(); int minWidth = Math.max(VIEWER_MINIMUM_WIDTH, Math.max(buttonBarSize.x, buttonPanelSize.x)); int minHeight = VIEWER_MINIMUM_HEIGHT + buttonBarSize.y + buttonPanelSize.y; getShell().setMinimumSize(new Point(minWidth, minHeight)); setFreshTemplate(); setStatusMessage(""); } }
false
true
protected Control createReplaceArea(Composite parent) { IEclipseContext params = EclipseContextFactory.create(); params.set("parent", parent); replaceViewer = ContextInjectionFactory.make(E4GraphicalViewer.class, context, params); replaceViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); replaceViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { updateSelection(E4Utils.createSelectionBindings(event, context)); } }); replaceViewer.getControl().addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { context.remove(IEntityPartViewer.class); context.remove(ActionRegistry.class); } @SuppressWarnings("unchecked") @Override public void focusGained(FocusEvent e) { context.set(IEntityPartViewer.class, replaceViewer); context.set(ActionRegistry.class, replaceActionRegistry); updateSelection(E4Utils.createSelectionBindings(replaceViewer.getSelectedEditParts(), replaceViewer, context)); } }); viewer.addPartFocusListener(new IPartFocusListener() { @SuppressWarnings("unchecked") public void focusChanged(IEntityPart oldPart, IEntityPart newPart) { updateSelection(E4Utils.createSelectionBindings(viewer.getSelectedEditParts(), viewer, context)); } }); E4KeyHandler keyHandler = new E4KeyHandler(context); keyHandler.setParent(new E4NavigationKeyHandler(context)); replaceViewer.setKeyHandler(keyHandler); replaceViewer.setEntityContents(createDefaultContents()); context.set(IEntityPartViewer.class, replaceViewer); replaceActionRegistry = ContextInjectionFactory.make(ActionRegistry.class, context); replaceActionRegistry.registerWorkbenchActions(); context.set(ActionRegistry.class, replaceActionRegistry); replaceViewer.setContextMenu(new ContextMenuProvider(replaceViewer) { @Override public void buildContextMenu(IMenuManager menuManager) { contextMenuProvider.populate(menuManager); } }); return parent; }
protected Control createReplaceArea(Composite parent) { IEclipseContext params = EclipseContextFactory.create(); params.set("parent", parent); replaceViewer = ContextInjectionFactory.make(E4GraphicalViewer.class, context, params); replaceViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); replaceViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { updateSelection(E4Utils.createSelectionBindings(event, context)); } }); replaceViewer.getControl().addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { context.remove(IEntityPartViewer.class); context.remove(ActionRegistry.class); } @SuppressWarnings("unchecked") @Override public void focusGained(FocusEvent e) { context.set(IEntityPartViewer.class, replaceViewer); context.set(ActionRegistry.class, replaceActionRegistry); updateSelection(E4Utils.createSelectionBindings(replaceViewer.getSelectedEditParts(), replaceViewer, context)); } }); replaceViewer.addPartFocusListener(new IPartFocusListener() { @SuppressWarnings("unchecked") public void focusChanged(IEntityPart oldPart, IEntityPart newPart) { updateSelection(E4Utils.createSelectionBindings(replaceViewer.getSelectedEditParts(), replaceViewer, context)); } }); E4KeyHandler keyHandler = new E4KeyHandler(context); keyHandler.setParent(new E4NavigationKeyHandler(context)); replaceViewer.setKeyHandler(keyHandler); replaceViewer.setEntityContents(createDefaultContents()); context.set(IEntityPartViewer.class, replaceViewer); replaceActionRegistry = ContextInjectionFactory.make(ActionRegistry.class, context); replaceActionRegistry.registerWorkbenchActions(); context.set(ActionRegistry.class, replaceActionRegistry); replaceViewer.setContextMenu(new ContextMenuProvider(replaceViewer) { @Override public void buildContextMenu(IMenuManager menuManager) { contextMenuProvider.populate(menuManager); } }); return parent; }
diff --git a/application/src/com.phdroid/smsb/storage/TestMessageProvider.java b/application/src/com.phdroid/smsb/storage/TestMessageProvider.java index c1d0834..4d449a4 100644 --- a/application/src/com.phdroid/smsb/storage/TestMessageProvider.java +++ b/application/src/com.phdroid/smsb/storage/TestMessageProvider.java @@ -1,224 +1,224 @@ package com.phdroid.smsb.storage; import com.phdroid.smsb.SmsPojo; import com.phdroid.smsb.TestSmsPojo; import java.util.ArrayList; import java.util.Calendar; import java.util.Hashtable; import java.util.List; public class TestMessageProvider implements IMessageProvider { private ArrayList<SmsPojo> mList; private Hashtable<SmsPojo, SmsAction> mActions; private int mUnreadCount = 0; public TestMessageProvider() { mActions = new Hashtable<SmsPojo, SmsAction>(); mList = new ArrayList<SmsPojo>(); Calendar c = Calendar.getInstance(); - SmsPojo sms = new TestSmsPojo(); + TestSmsPojo sms = new TestSmsPojo(); sms.setMessage("Hey you there! How you doin'?"); sms.setSender("+380971122333"); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Nova aktsia vid magazinu Target! Kupuy 2 kartopli ta otrymay 1 v podarunok!"); sms.setSender("TARGET"); c.add(Calendar.SECOND, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("This is my new number. B. Obama."); sms.setSender("+1570333444555"); c.add(Calendar.MINUTE, -5); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("How about having some beer tonight? Stranger."); sms.setSender("+380509998887"); sms.setRead(true); c.add(Calendar.MINUTE, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Vash rakhunok na 9.05.2011 stanovyt 27,35 uah."); sms.setSender("KYIVSTAR"); c.add(Calendar.MINUTE, -20); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Skydky v ALDO. Kupuy 1 ked ta otrymuy dryguy v podarunok!"); sms.setSender("ALDO"); c.add(Calendar.HOUR, -2); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Big football tonight v taverne chili!"); sms.setSender("+380991001010"); sms.setRead(true); c.add(Calendar.HOUR, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("15:43 ZABLOKOVANO 17,99 UAH, SUPERMARKET PORTAL"); sms.setSender("PUMB"); c.add(Calendar.HOUR, -400); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Vash rakhunok na 8.05.2011 stanovyt 24 uah."); sms.setSender("KYIVSTAR"); sms.setRead(true); c.add(Calendar.MINUTE, -20); sms.setReceived(c.getTime().getTime()); mList.add(sms); mUnreadCount = 6; } public int size(){ return mList.size(); } public List<SmsPojo> getMessages() { return mList; } public Hashtable<SmsPojo, SmsAction> getActionMessages() { return mActions; } public void delete(long id) { mActions.clear(); SmsPojo sms = get(id); if (sms != null){ mActions.put(sms, SmsAction.Deleted); mList.remove((int) id); } } public void delete(long[] ids) { mActions.clear(); for (long id = ids.length - 1; id >= 0; id--) { SmsPojo sms = get(ids[(int)id]); if (sms != null){ if (!sms.isRead()) mUnreadCount--; mActions.put(sms, SmsAction.Deleted); mList.remove((int) id); } } } public void deleteAll() { for (SmsPojo sms : mList) { mActions.put(sms, SmsAction.Deleted); } mList.clear(); } public void notSpam(long id) { mActions.clear(); SmsPojo sms = get(id); if(sms != null){ mActions.put(sms, SmsAction.MarkedAsNotSpam); mList.remove((int) id); } } public void notSpam(long[] ids) { mActions.clear(); for (long id = ids.length - 1; id >= 0; id--) { SmsPojo sms = get(ids[(int)id]); if (sms != null){ if (!sms.isRead()) mUnreadCount--; mActions.put(sms, SmsAction.MarkedAsNotSpam); mList.remove((int) id); } } } @Override public int getIndex(SmsPojo message) { return mList.indexOf(message); } @Override public boolean isFirstMessage(SmsPojo message) { return mList.indexOf(message) == 0; } @Override public boolean isLastMessage(SmsPojo message) { return mList.indexOf(message) == mList.size()-1; } @Override public SmsPojo getPreviousMessage(SmsPojo message) { int index = mList.indexOf(message); if (index <= 0) { return null; } return mList.get(--index); } @Override public SmsPojo getNextMessage(SmsPojo message) { int index = mList.indexOf(message); if (index >= mList.size()-1) { return null; } return mList.get(++index); } public SmsPojo getMessage(long id) { return get(id); } public void read(long id) { SmsPojo smsPojo = get(id); if (smsPojo != null && !smsPojo.isRead()) { smsPojo.setRead(true); mUnreadCount--; } } public int getUnreadCount() { return mUnreadCount; } public void undo() { for (SmsPojo sms : mActions.keySet()) { mList.add(0, sms); } mActions.clear(); mUnreadCount = 0; for (SmsPojo sms : mList) { if (!sms.isRead()) { mUnreadCount++; } } } public void performActions() { mActions.clear(); } private SmsPojo get(long id) { if(id < 0) return null; if(id > mList.size()) return null; return mList.get((int) id); } }
true
true
public TestMessageProvider() { mActions = new Hashtable<SmsPojo, SmsAction>(); mList = new ArrayList<SmsPojo>(); Calendar c = Calendar.getInstance(); SmsPojo sms = new TestSmsPojo(); sms.setMessage("Hey you there! How you doin'?"); sms.setSender("+380971122333"); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Nova aktsia vid magazinu Target! Kupuy 2 kartopli ta otrymay 1 v podarunok!"); sms.setSender("TARGET"); c.add(Calendar.SECOND, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("This is my new number. B. Obama."); sms.setSender("+1570333444555"); c.add(Calendar.MINUTE, -5); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("How about having some beer tonight? Stranger."); sms.setSender("+380509998887"); sms.setRead(true); c.add(Calendar.MINUTE, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Vash rakhunok na 9.05.2011 stanovyt 27,35 uah."); sms.setSender("KYIVSTAR"); c.add(Calendar.MINUTE, -20); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Skydky v ALDO. Kupuy 1 ked ta otrymuy dryguy v podarunok!"); sms.setSender("ALDO"); c.add(Calendar.HOUR, -2); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Big football tonight v taverne chili!"); sms.setSender("+380991001010"); sms.setRead(true); c.add(Calendar.HOUR, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("15:43 ZABLOKOVANO 17,99 UAH, SUPERMARKET PORTAL"); sms.setSender("PUMB"); c.add(Calendar.HOUR, -400); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Vash rakhunok na 8.05.2011 stanovyt 24 uah."); sms.setSender("KYIVSTAR"); sms.setRead(true); c.add(Calendar.MINUTE, -20); sms.setReceived(c.getTime().getTime()); mList.add(sms); mUnreadCount = 6; }
public TestMessageProvider() { mActions = new Hashtable<SmsPojo, SmsAction>(); mList = new ArrayList<SmsPojo>(); Calendar c = Calendar.getInstance(); TestSmsPojo sms = new TestSmsPojo(); sms.setMessage("Hey you there! How you doin'?"); sms.setSender("+380971122333"); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Nova aktsia vid magazinu Target! Kupuy 2 kartopli ta otrymay 1 v podarunok!"); sms.setSender("TARGET"); c.add(Calendar.SECOND, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("This is my new number. B. Obama."); sms.setSender("+1570333444555"); c.add(Calendar.MINUTE, -5); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("How about having some beer tonight? Stranger."); sms.setSender("+380509998887"); sms.setRead(true); c.add(Calendar.MINUTE, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Vash rakhunok na 9.05.2011 stanovyt 27,35 uah."); sms.setSender("KYIVSTAR"); c.add(Calendar.MINUTE, -20); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Skydky v ALDO. Kupuy 1 ked ta otrymuy dryguy v podarunok!"); sms.setSender("ALDO"); c.add(Calendar.HOUR, -2); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Big football tonight v taverne chili!"); sms.setSender("+380991001010"); sms.setRead(true); c.add(Calendar.HOUR, -30); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("15:43 ZABLOKOVANO 17,99 UAH, SUPERMARKET PORTAL"); sms.setSender("PUMB"); c.add(Calendar.HOUR, -400); sms.setReceived(c.getTime().getTime()); mList.add(sms); sms = new TestSmsPojo(); sms.setMessage("Vash rakhunok na 8.05.2011 stanovyt 24 uah."); sms.setSender("KYIVSTAR"); sms.setRead(true); c.add(Calendar.MINUTE, -20); sms.setReceived(c.getTime().getTime()); mList.add(sms); mUnreadCount = 6; }
diff --git a/core/src/main/java/org/apache/oozie/client/rest/JsonWorkflowJob.java b/core/src/main/java/org/apache/oozie/client/rest/JsonWorkflowJob.java index 7ca293c1..a63e9272 100644 --- a/core/src/main/java/org/apache/oozie/client/rest/JsonWorkflowJob.java +++ b/core/src/main/java/org/apache/oozie/client/rest/JsonWorkflowJob.java @@ -1,292 +1,292 @@ /** * Copyright (c) 2010 Yahoo! Inc. All rights reserved. * 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. See accompanying LICENSE file. */ package org.apache.oozie.client.rest; import org.apache.oozie.client.WorkflowAction; import org.apache.oozie.client.WorkflowJob; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.*; /** * Json Bean that represents an Oozie workflow job. */ @Entity @Table(name = "WF_JOBS") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "bean_type", discriminatorType = DiscriminatorType.STRING) public class JsonWorkflowJob implements WorkflowJob, JsonBean { @Id private String id; @Basic @Column(name = "app_name") private String appName = null; @Basic @Column(name = "app_path") private String appPath = null; @Transient private String externalId = null; @Column(name = "conf") @Lob private String conf = null; @Transient private Status status = WorkflowJob.Status.PREP; @Transient private Date createdTime; @Transient private Date startTime; @Transient private Date endTime; @Transient private Date lastModifiedTime; @Basic @Column(name = "user_name") private String user = null; @Basic @Column(name = "group_name") private String group; @Basic @Column(name = "run") private int run = 1; @Basic @Column(name = "parentId") private String parentId; @Transient private String consoleUrl; @Transient private List<? extends JsonWorkflowAction> actions; public JsonWorkflowJob() { actions = new ArrayList<JsonWorkflowAction>(); } @SuppressWarnings("unchecked") public JSONObject toJSONObject() { JSONObject json = new JSONObject(); - json.put(JsonTags.WORKFLOW_APP_PATH, appPath); - json.put(JsonTags.WORKFLOW_APP_NAME, appName); - json.put(JsonTags.WORKFLOW_ID, id); - json.put(JsonTags.WORKFLOW_EXTERNAL_ID, externalId); - json.put(JsonTags.WORKFLOW_PARENT_ID, parentId); - json.put(JsonTags.WORKFLOW_CONF, conf); - json.put(JsonTags.WORKFLOW_STATUS, status.toString()); - json.put(JsonTags.WORKFLOW_LAST_MOD_TIME, JsonUtils.formatDateRfc822(lastModifiedTime)); - json.put(JsonTags.WORKFLOW_CREATED_TIME, JsonUtils.formatDateRfc822(createdTime)); - json.put(JsonTags.WORKFLOW_START_TIME, JsonUtils.formatDateRfc822(startTime)); - json.put(JsonTags.WORKFLOW_END_TIME, JsonUtils.formatDateRfc822(endTime)); - json.put(JsonTags.WORKFLOW_USER, user); - json.put(JsonTags.WORKFLOW_GROUP, group); - json.put(JsonTags.WORKFLOW_RUN, (long) run); - json.put(JsonTags.WORKFLOW_CONSOLE_URL, consoleUrl); + json.put(JsonTags.WORKFLOW_APP_PATH, getAppPath()); + json.put(JsonTags.WORKFLOW_APP_NAME, getAppName()); + json.put(JsonTags.WORKFLOW_ID, getId()); + json.put(JsonTags.WORKFLOW_EXTERNAL_ID, getExternalId()); + json.put(JsonTags.WORKFLOW_PARENT_ID, getParentId()); + json.put(JsonTags.WORKFLOW_CONF, getConf()); + json.put(JsonTags.WORKFLOW_STATUS, getStatus().toString()); + json.put(JsonTags.WORKFLOW_LAST_MOD_TIME, JsonUtils.formatDateRfc822(getLastModifiedTime())); + json.put(JsonTags.WORKFLOW_CREATED_TIME, JsonUtils.formatDateRfc822(getCreatedTime())); + json.put(JsonTags.WORKFLOW_START_TIME, JsonUtils.formatDateRfc822(getStartTime())); + json.put(JsonTags.WORKFLOW_END_TIME, JsonUtils.formatDateRfc822(getEndTime())); + json.put(JsonTags.WORKFLOW_USER, getUser()); + json.put(JsonTags.WORKFLOW_GROUP, getGroup()); + json.put(JsonTags.WORKFLOW_RUN, (long) getRun()); + json.put(JsonTags.WORKFLOW_CONSOLE_URL, getConsoleUrl()); json.put(JsonTags.WORKFLOW_ACTIONS, JsonWorkflowAction.toJSONArray(actions)); - json.put(JsonTags.TO_STRING,toString()); + json.put(JsonTags.TO_STRING, toString()); return json; } public String getAppPath() { return appPath; } public void setAppPath(String appPath) { this.appPath = appPath; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setExternalId(String externalId) { this.externalId = externalId; } public String getExternalId() { return externalId; } public String getConf() { return conf; } public void setConf(String conf) { this.conf = conf; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Date getLastModifiedTime() { return lastModifiedTime; } public void setLastModifiedTime(Date lastModTime) { this.lastModifiedTime = lastModTime; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public int getRun() { return run; } public void setRun(int run) { this.run = run; } /** * Return the workflow job console URL. * * @return the workflow job console URL. */ public String getConsoleUrl() { return consoleUrl; } /** * Return the corresponding Action ID, if any. * * @return the coordinator Action Id. */ public String getParentId() { return parentId; } /** * Set coordinator action id * * @param parentId : coordinator action id */ public void setParentId(String parentId) { this.parentId = parentId; } /** * Set the workflow job console URL. * * @param consoleUrl the workflow job console URL. */ public void setConsoleUrl(String consoleUrl) { this.consoleUrl = consoleUrl; } @SuppressWarnings("unchecked") public List<WorkflowAction> getActions() { return (List) actions; } public void setActions(List<? extends JsonWorkflowAction> nodes) { this.actions = (nodes != null) ? nodes : new ArrayList<JsonWorkflowAction>(); } @Override public String toString() { return MessageFormat.format("Workflow id[{0}] status[{1}]", getId(), getStatus()); } /** * Convert a workflows list into a JSONArray. * * @param workflows workflows list. * @return the corresponding JSON array. */ @SuppressWarnings("unchecked") public static JSONArray toJSONArray(List<? extends JsonWorkflowJob> workflows) { JSONArray array = new JSONArray(); if (workflows != null) { for (JsonWorkflowJob node : workflows) { array.add(node.toJSONObject()); } } return array; } }
false
true
public JSONObject toJSONObject() { JSONObject json = new JSONObject(); json.put(JsonTags.WORKFLOW_APP_PATH, appPath); json.put(JsonTags.WORKFLOW_APP_NAME, appName); json.put(JsonTags.WORKFLOW_ID, id); json.put(JsonTags.WORKFLOW_EXTERNAL_ID, externalId); json.put(JsonTags.WORKFLOW_PARENT_ID, parentId); json.put(JsonTags.WORKFLOW_CONF, conf); json.put(JsonTags.WORKFLOW_STATUS, status.toString()); json.put(JsonTags.WORKFLOW_LAST_MOD_TIME, JsonUtils.formatDateRfc822(lastModifiedTime)); json.put(JsonTags.WORKFLOW_CREATED_TIME, JsonUtils.formatDateRfc822(createdTime)); json.put(JsonTags.WORKFLOW_START_TIME, JsonUtils.formatDateRfc822(startTime)); json.put(JsonTags.WORKFLOW_END_TIME, JsonUtils.formatDateRfc822(endTime)); json.put(JsonTags.WORKFLOW_USER, user); json.put(JsonTags.WORKFLOW_GROUP, group); json.put(JsonTags.WORKFLOW_RUN, (long) run); json.put(JsonTags.WORKFLOW_CONSOLE_URL, consoleUrl); json.put(JsonTags.WORKFLOW_ACTIONS, JsonWorkflowAction.toJSONArray(actions)); json.put(JsonTags.TO_STRING,toString()); return json; }
public JSONObject toJSONObject() { JSONObject json = new JSONObject(); json.put(JsonTags.WORKFLOW_APP_PATH, getAppPath()); json.put(JsonTags.WORKFLOW_APP_NAME, getAppName()); json.put(JsonTags.WORKFLOW_ID, getId()); json.put(JsonTags.WORKFLOW_EXTERNAL_ID, getExternalId()); json.put(JsonTags.WORKFLOW_PARENT_ID, getParentId()); json.put(JsonTags.WORKFLOW_CONF, getConf()); json.put(JsonTags.WORKFLOW_STATUS, getStatus().toString()); json.put(JsonTags.WORKFLOW_LAST_MOD_TIME, JsonUtils.formatDateRfc822(getLastModifiedTime())); json.put(JsonTags.WORKFLOW_CREATED_TIME, JsonUtils.formatDateRfc822(getCreatedTime())); json.put(JsonTags.WORKFLOW_START_TIME, JsonUtils.formatDateRfc822(getStartTime())); json.put(JsonTags.WORKFLOW_END_TIME, JsonUtils.formatDateRfc822(getEndTime())); json.put(JsonTags.WORKFLOW_USER, getUser()); json.put(JsonTags.WORKFLOW_GROUP, getGroup()); json.put(JsonTags.WORKFLOW_RUN, (long) getRun()); json.put(JsonTags.WORKFLOW_CONSOLE_URL, getConsoleUrl()); json.put(JsonTags.WORKFLOW_ACTIONS, JsonWorkflowAction.toJSONArray(actions)); json.put(JsonTags.TO_STRING, toString()); return json; }
diff --git a/cobertura/src/net/sourceforge/cobertura/instrument/CoberturaInstrumenter.java b/cobertura/src/net/sourceforge/cobertura/instrument/CoberturaInstrumenter.java index 39a4cdc..b67e543 100644 --- a/cobertura/src/net/sourceforge/cobertura/instrument/CoberturaInstrumenter.java +++ b/cobertura/src/net/sourceforge/cobertura/instrument/CoberturaInstrumenter.java @@ -1,302 +1,302 @@ /* * Cobertura - http://cobertura.sourceforge.net/ * * Cobertura 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. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument; 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.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.regex.Pattern; import net.sourceforge.cobertura.coveragedata.ProjectData; import net.sourceforge.cobertura.instrument.pass1.DetectDuplicatedCodeClassVisitor; import net.sourceforge.cobertura.instrument.pass1.DetectIgnoredCodeClassVisitor; import net.sourceforge.cobertura.instrument.pass2.BuildClassMapClassVisitor; import net.sourceforge.cobertura.instrument.pass3.InjectCodeClassInstrumenter; import net.sourceforge.cobertura.util.IOUtil; import org.apache.log4j.Logger; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; /** * Class that is responsible for the whole process of instrumentation of a single class. * * The class is instrumented in tree passes: * <ol> * <li>Read only: {@link DetectDuplicatedCodeClassVisitor} - we look for the same ASM code snippets * rendered in different places of destination code</li> * <li>Read only: {@link BuildClassMapClassVisitor} - finds all touch-points and other interesting * information that are in the class and store it in {@link ClassMap}. * <li>Real instrumentation: {@link InjectCodeClassInstrumenter}. Uses {#link ClassMap} to inject * code into the class</li> * </ol> * * @author [email protected] */ public class CoberturaInstrumenter { private static final Logger logger = Logger.getLogger(CoberturaInstrumenter.class); /** * During the instrumentation process we are feeling {@link ProjectData}, to generate from * it the *.ser file. * * We now (1.10+) don't need to generate the file (it is not necessery for reporting), but we still * do it for backward compatibility (for example maven-cobertura-plugin expects it). We should avoid * this some day. */ private ProjectData projectData; /** * The root directory for instrumented classes. If it is null, the instrumented classes are overwritten. */ private File destinationDirectory; /** * List of patterns to know that we don't want trace lines that are calls to some methods */ private Collection<Pattern> ignoreRegexes = new Vector<Pattern>(); /** * Methods annotated by this annotations will be ignored during coverage measurement */ private Set<String> ignoreMethodAnnotations = new HashSet<String>(); /** * If true: Getters, Setters and simple initialization will be ignored by coverage measurement */ private boolean ignoreTrivial; /** * Setting to true causes cobertura to use more strict threadsafe model that is significantly * slower, but guarantees that number of hits counted for each line will be precise in multithread-environment. * * The option does not change measured coverage. * * In implementation it means that AtomicIntegerArray will be used instead of int[]. */ private boolean threadsafeRigorous; /** * Analyzes and instruments class given by path. * * <p>Also the {@link #projectData} structure is filled with information about the found touch-points</p> * * @param file - path to class that should be instrumented * * @return instrumentation result structure or null in case of problems */ public InstrumentationResult instrumentClass(File file){ InputStream inputStream = null; try{ logger.debug("Working on file:" + file.getAbsolutePath()); inputStream = new FileInputStream(file); return instrumentClass(inputStream); }catch (Throwable t){ logger.warn("Unable to instrument file " + file.getAbsolutePath(),t); return null; }finally{ IOUtil.closeInputStream(inputStream); } } /** * Analyzes and instruments class given by inputStream * * <p>Also the {@link #projectData} structure is filled with information about the found touch-points</p> * * @param inputStream - source of class to instrument * * @return instrumentation result structure or null in case of problems */ public InstrumentationResult instrumentClass(InputStream inputStream) throws IOException{ ClassReader cr0 = new ClassReader(inputStream); ClassWriter cw0 = new ClassWriter(0); DetectIgnoredCodeClassVisitor detectIgnoredCv = new DetectIgnoredCodeClassVisitor(cw0, ignoreTrivial, ignoreMethodAnnotations); DetectDuplicatedCodeClassVisitor cv0=new DetectDuplicatedCodeClassVisitor(detectIgnoredCv); cr0.accept(cv0,0); ClassReader cr = new ClassReader(cw0.toByteArray()); ClassWriter cw = new ClassWriter(0); BuildClassMapClassVisitor cv = new BuildClassMapClassVisitor(cw, ignoreRegexes,cv0.getDuplicatesLinesCollector(), detectIgnoredCv.getIgnoredMethodNamesAndSignatures()); cr.accept(cv, 0); if(logger.isDebugEnabled()){ logger.debug("=============== Detected duplicated code ============="); Map<Integer, Map<Integer, Integer>> l=cv0.getDuplicatesLinesCollector(); for(Map.Entry<Integer, Map<Integer,Integer>> m:l.entrySet()){ if (m.getValue()!=null){ for(Map.Entry<Integer, Integer> pair:m.getValue().entrySet()){ logger.debug(cv.getClassMap().getClassName()+":"+m.getKey()+" "+pair.getKey()+"->"+pair.getValue()); } } } logger.debug("=============== End of detected duplicated code ======"); } //TODO(ptab): Don't like the idea, but we have to be compatible (hope to remove the line in future release) logger.debug("Migrating classmap in projectData to store in *.ser file: " + cv.getClassMap().getClassName()); - if (cv.shouldBeInstrumented()) { //Not instrumented classes should be not included into the report - cv.getClassMap().applyOnProjectData(projectData,cv.shouldBeInstrumented()); - } + // if (cv.shouldBeInstrumented()) { //Not instrumented classes should be not included into the report + cv.getClassMap().applyOnProjectData(projectData, cv.shouldBeInstrumented()); + // } if (cv.shouldBeInstrumented()){ /* * BuildClassMapClassInstrumenter and DetectDuplicatedCodeClassVisitor has not modificated bytecode, * so we can use any bytecode representation of that class. */ ClassReader cr2= new ClassReader(cw0.toByteArray()); ClassWriter cw2= new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cv.getClassMap().assignCounterIds(); logger.debug("Assigned "+ cv.getClassMap().getMaxCounterId()+" counters for class:"+cv.getClassMap().getClassName()); InjectCodeClassInstrumenter cv2 = new InjectCodeClassInstrumenter(cw2, ignoreRegexes, threadsafeRigorous, cv.getClassMap(), cv0.getDuplicatesLinesCollector(), detectIgnoredCv.getIgnoredMethodNamesAndSignatures()); cr2.accept(cv2, 0); return new InstrumentationResult(cv.getClassMap().getClassName(), cw2.toByteArray()); }else{ logger.debug("Class shouldn't be instrumented: "+cv.getClassMap().getClassName()); return null; } } /** * Analyzes and instruments class given by file. * * <p>If the {@link #destinationDirectory} is null, then the file is overwritten, * otherwise the class is stored into the {@link #destinationDirectory}</p> * * <p>Also the {@link #projectData} structure is filled with information about the found touch-points</p> * * @param file - source of class to instrument */ public void addInstrumentationToSingleClass(File file) { logger.debug("Instrumenting class " + file.getAbsolutePath()); InstrumentationResult instrumentationResult=instrumentClass(file); if (instrumentationResult!=null){ OutputStream outputStream = null; try{ // If destinationDirectory is null, then overwrite // the original, uninstrumented file. File outputFile=(destinationDirectory == null)?file :new File(destinationDirectory, instrumentationResult.className.replace('.', File.separatorChar)+ ".class"); logger.debug("Writing instrumented class into:"+outputFile.getAbsolutePath()); File parentFile = outputFile.getParentFile(); if (parentFile != null){ parentFile.mkdirs(); } outputStream = new FileOutputStream(outputFile); outputStream.write(instrumentationResult.content); }catch (Throwable t){ logger.warn("Unable to write instrumented file " + file.getAbsolutePath(),t); return; }finally{ outputStream = IOUtil.closeOutputStream(outputStream); } } } // ----------------- Getters and setters ------------------------------------- /** * Gets the root directory for instrumented classes. If it is null, the instrumented classes are overwritten. */ public File getDestinationDirectory() { return destinationDirectory; } /** *Sets the root directory for instrumented classes. If it is null, the instrumented classes are overwritten. */ public void setDestinationDirectory(File destinationDirectory) { this.destinationDirectory = destinationDirectory; } /** * Gets list of patterns to know that we don't want trace lines that are calls to some methods */ public Collection<Pattern> getIgnoreRegexes() { return ignoreRegexes; } /** * Sets list of patterns to know that we don't want trace lines that are calls to some methods */ public void setIgnoreRegexes(Collection<Pattern> ignoreRegexes) { this.ignoreRegexes = ignoreRegexes; } public void setIgnoreTrivial(boolean ignoreTrivial) { this.ignoreTrivial = ignoreTrivial; } public void setIgnoreMethodAnnotations(Set<String> ignoreMethodAnnotations) { this.ignoreMethodAnnotations = ignoreMethodAnnotations; } public void setThreadsafeRigorous(boolean threadsafeRigorous) { this.threadsafeRigorous = threadsafeRigorous; } /** * Sets {@link ProjectData} that will be filled with information about touch points inside instrumented classes * @param projectData */ public void setProjectData(ProjectData projectData) { this.projectData=projectData; } /** * Result of instrumentation is a pair of two fields: * <ul> * <li> {@link #content} - bytecode of the instrumented class * <li> {@link #className} - className of class being instrumented * </ul> */ public static class InstrumentationResult{ private String className; private byte[] content; public InstrumentationResult(String className,byte[] content) { this.className=className; this.content=content; } public String getClassName() { return className; } public byte[] getContent() { return content; } } }
true
true
public InstrumentationResult instrumentClass(InputStream inputStream) throws IOException{ ClassReader cr0 = new ClassReader(inputStream); ClassWriter cw0 = new ClassWriter(0); DetectIgnoredCodeClassVisitor detectIgnoredCv = new DetectIgnoredCodeClassVisitor(cw0, ignoreTrivial, ignoreMethodAnnotations); DetectDuplicatedCodeClassVisitor cv0=new DetectDuplicatedCodeClassVisitor(detectIgnoredCv); cr0.accept(cv0,0); ClassReader cr = new ClassReader(cw0.toByteArray()); ClassWriter cw = new ClassWriter(0); BuildClassMapClassVisitor cv = new BuildClassMapClassVisitor(cw, ignoreRegexes,cv0.getDuplicatesLinesCollector(), detectIgnoredCv.getIgnoredMethodNamesAndSignatures()); cr.accept(cv, 0); if(logger.isDebugEnabled()){ logger.debug("=============== Detected duplicated code ============="); Map<Integer, Map<Integer, Integer>> l=cv0.getDuplicatesLinesCollector(); for(Map.Entry<Integer, Map<Integer,Integer>> m:l.entrySet()){ if (m.getValue()!=null){ for(Map.Entry<Integer, Integer> pair:m.getValue().entrySet()){ logger.debug(cv.getClassMap().getClassName()+":"+m.getKey()+" "+pair.getKey()+"->"+pair.getValue()); } } } logger.debug("=============== End of detected duplicated code ======"); } //TODO(ptab): Don't like the idea, but we have to be compatible (hope to remove the line in future release) logger.debug("Migrating classmap in projectData to store in *.ser file: " + cv.getClassMap().getClassName()); if (cv.shouldBeInstrumented()) { //Not instrumented classes should be not included into the report cv.getClassMap().applyOnProjectData(projectData,cv.shouldBeInstrumented()); } if (cv.shouldBeInstrumented()){ /* * BuildClassMapClassInstrumenter and DetectDuplicatedCodeClassVisitor has not modificated bytecode, * so we can use any bytecode representation of that class. */ ClassReader cr2= new ClassReader(cw0.toByteArray()); ClassWriter cw2= new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cv.getClassMap().assignCounterIds(); logger.debug("Assigned "+ cv.getClassMap().getMaxCounterId()+" counters for class:"+cv.getClassMap().getClassName()); InjectCodeClassInstrumenter cv2 = new InjectCodeClassInstrumenter(cw2, ignoreRegexes, threadsafeRigorous, cv.getClassMap(), cv0.getDuplicatesLinesCollector(), detectIgnoredCv.getIgnoredMethodNamesAndSignatures()); cr2.accept(cv2, 0); return new InstrumentationResult(cv.getClassMap().getClassName(), cw2.toByteArray()); }else{ logger.debug("Class shouldn't be instrumented: "+cv.getClassMap().getClassName()); return null; } }
public InstrumentationResult instrumentClass(InputStream inputStream) throws IOException{ ClassReader cr0 = new ClassReader(inputStream); ClassWriter cw0 = new ClassWriter(0); DetectIgnoredCodeClassVisitor detectIgnoredCv = new DetectIgnoredCodeClassVisitor(cw0, ignoreTrivial, ignoreMethodAnnotations); DetectDuplicatedCodeClassVisitor cv0=new DetectDuplicatedCodeClassVisitor(detectIgnoredCv); cr0.accept(cv0,0); ClassReader cr = new ClassReader(cw0.toByteArray()); ClassWriter cw = new ClassWriter(0); BuildClassMapClassVisitor cv = new BuildClassMapClassVisitor(cw, ignoreRegexes,cv0.getDuplicatesLinesCollector(), detectIgnoredCv.getIgnoredMethodNamesAndSignatures()); cr.accept(cv, 0); if(logger.isDebugEnabled()){ logger.debug("=============== Detected duplicated code ============="); Map<Integer, Map<Integer, Integer>> l=cv0.getDuplicatesLinesCollector(); for(Map.Entry<Integer, Map<Integer,Integer>> m:l.entrySet()){ if (m.getValue()!=null){ for(Map.Entry<Integer, Integer> pair:m.getValue().entrySet()){ logger.debug(cv.getClassMap().getClassName()+":"+m.getKey()+" "+pair.getKey()+"->"+pair.getValue()); } } } logger.debug("=============== End of detected duplicated code ======"); } //TODO(ptab): Don't like the idea, but we have to be compatible (hope to remove the line in future release) logger.debug("Migrating classmap in projectData to store in *.ser file: " + cv.getClassMap().getClassName()); // if (cv.shouldBeInstrumented()) { //Not instrumented classes should be not included into the report cv.getClassMap().applyOnProjectData(projectData, cv.shouldBeInstrumented()); // } if (cv.shouldBeInstrumented()){ /* * BuildClassMapClassInstrumenter and DetectDuplicatedCodeClassVisitor has not modificated bytecode, * so we can use any bytecode representation of that class. */ ClassReader cr2= new ClassReader(cw0.toByteArray()); ClassWriter cw2= new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cv.getClassMap().assignCounterIds(); logger.debug("Assigned "+ cv.getClassMap().getMaxCounterId()+" counters for class:"+cv.getClassMap().getClassName()); InjectCodeClassInstrumenter cv2 = new InjectCodeClassInstrumenter(cw2, ignoreRegexes, threadsafeRigorous, cv.getClassMap(), cv0.getDuplicatesLinesCollector(), detectIgnoredCv.getIgnoredMethodNamesAndSignatures()); cr2.accept(cv2, 0); return new InstrumentationResult(cv.getClassMap().getClassName(), cw2.toByteArray()); }else{ logger.debug("Class shouldn't be instrumented: "+cv.getClassMap().getClassName()); return null; } }
diff --git a/src/com/android/nfc/NfcService.java b/src/com/android/nfc/NfcService.java index e3ecb03..bf18f42 100755 --- a/src/com/android/nfc/NfcService.java +++ b/src/com/android/nfc/NfcService.java @@ -1,2323 +1,2325 @@ /* * Copyright (C) 2010 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.nfc; import com.android.internal.nfc.LlcpServiceSocket; import com.android.internal.nfc.LlcpSocket; import com.android.nfc.mytag.MyTagClient; import com.android.nfc.mytag.MyTagServer; import android.app.Application; import android.app.StatusBarManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.nfc.ErrorCodes; import android.nfc.FormatException; import android.nfc.ILlcpConnectionlessSocket; import android.nfc.ILlcpServiceSocket; import android.nfc.ILlcpSocket; import android.nfc.INfcAdapter; import android.nfc.INfcTag; import android.nfc.IP2pInitiator; import android.nfc.IP2pTarget; import android.nfc.LlcpPacket; import android.nfc.NdefMessage; import android.nfc.NdefTag; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.os.ServiceManager; import android.util.Log; import java.util.HashMap; import java.util.LinkedList; import java.util.ListIterator; public class NfcService extends Application { static { System.loadLibrary("nfc_jni"); } public static final String SERVICE_NAME = "nfc"; private static final String TAG = "NfcService"; private static final String NFC_PERM = android.Manifest.permission.NFC; private static final String NFC_PERM_ERROR = "NFC permission required"; private static final String ADMIN_PERM = android.Manifest.permission.WRITE_SECURE_SETTINGS; private static final String ADMIN_PERM_ERROR = "WRITE_SECURE_SETTINGS permission required"; private static final String PREF = "NfcServicePrefs"; private static final String PREF_NFC_ON = "nfc_on"; private static final boolean NFC_ON_DEFAULT = true; private static final String PREF_SECURE_ELEMENT_ON = "secure_element_on"; private static final boolean SECURE_ELEMENT_ON_DEFAULT = false; private static final String PREF_SECURE_ELEMENT_ID = "secure_element_id"; private static final int SECURE_ELEMENT_ID_DEFAULT = 0; private static final String PREF_LLCP_LTO = "llcp_lto"; private static final int LLCP_LTO_DEFAULT = 150; private static final int LLCP_LTO_MAX = 255; /** Maximum Information Unit */ private static final String PREF_LLCP_MIU = "llcp_miu"; private static final int LLCP_MIU_DEFAULT = 128; private static final int LLCP_MIU_MAX = 2176; /** Well Known Service List */ private static final String PREF_LLCP_WKS = "llcp_wks"; private static final int LLCP_WKS_DEFAULT = 1; private static final int LLCP_WKS_MAX = 15; private static final String PREF_LLCP_OPT = "llcp_opt"; private static final int LLCP_OPT_DEFAULT = 0; private static final int LLCP_OPT_MAX = 3; private static final String PREF_DISCOVERY_A = "discovery_a"; private static final boolean DISCOVERY_A_DEFAULT = true; private static final String PREF_DISCOVERY_B = "discovery_b"; private static final boolean DISCOVERY_B_DEFAULT = true; private static final String PREF_DISCOVERY_F = "discovery_f"; private static final boolean DISCOVERY_F_DEFAULT = true; private static final String PREF_DISCOVERY_15693 = "discovery_15693"; private static final boolean DISCOVERY_15693_DEFAULT = true; private static final String PREF_DISCOVERY_NFCIP = "discovery_nfcip"; private static final boolean DISCOVERY_NFCIP_DEFAULT = true; /** NFC Reader Discovery mode for enableDiscovery() */ private static final int DISCOVERY_MODE_READER = 0; /** Card Emulation Discovery mode for enableDiscovery() */ private static final int DISCOVERY_MODE_CARD_EMULATION = 2; private static final int LLCP_SERVICE_SOCKET_TYPE = 0; private static final int LLCP_SOCKET_TYPE = 1; private static final int LLCP_CONNECTIONLESS_SOCKET_TYPE = 2; private static final int LLCP_SOCKET_NB_MAX = 5; // Maximum number of socket managed private static final int LLCP_RW_MAX_VALUE = 15; // Receive Window private static final int PROPERTY_LLCP_LTO = 0; private static final String PROPERTY_LLCP_LTO_VALUE = "llcp.lto"; private static final int PROPERTY_LLCP_MIU = 1; private static final String PROPERTY_LLCP_MIU_VALUE = "llcp.miu"; private static final int PROPERTY_LLCP_WKS = 2; private static final String PROPERTY_LLCP_WKS_VALUE = "llcp.wks"; private static final int PROPERTY_LLCP_OPT = 3; private static final String PROPERTY_LLCP_OPT_VALUE = "llcp.opt"; private static final int PROPERTY_NFC_DISCOVERY_A = 4; private static final String PROPERTY_NFC_DISCOVERY_A_VALUE = "discovery.iso14443A"; private static final int PROPERTY_NFC_DISCOVERY_B = 5; private static final String PROPERTY_NFC_DISCOVERY_B_VALUE = "discovery.iso14443B"; private static final int PROPERTY_NFC_DISCOVERY_F = 6; private static final String PROPERTY_NFC_DISCOVERY_F_VALUE = "discovery.felica"; private static final int PROPERTY_NFC_DISCOVERY_15693 = 7; private static final String PROPERTY_NFC_DISCOVERY_15693_VALUE = "discovery.iso15693"; private static final int PROPERTY_NFC_DISCOVERY_NFCIP = 8; private static final String PROPERTY_NFC_DISCOVERY_NFCIP_VALUE = "discovery.nfcip"; static final int MSG_NDEF_TAG = 0; static final int MSG_CARD_EMULATION = 1; static final int MSG_LLCP_LINK_ACTIVATION = 2; static final int MSG_LLCP_LINK_DEACTIVATED = 3; static final int MSG_TARGET_DESELECTED = 4; static final int MSG_SHOW_MY_TAG_ICON = 5; static final int MSG_HIDE_MY_TAG_ICON = 6; static final int MSG_MOCK_NDEF_TAG = 7; // TODO: none of these appear to be synchronized but are // read/written from different threads (notably Binder threads)... private final LinkedList<RegisteredSocket> mRegisteredSocketList = new LinkedList<RegisteredSocket>(); private int mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED; private int mGeneratedSocketHandle = 0; private int mNbSocketCreated = 0; private volatile boolean mIsNfcEnabled = false; private int mSelectedSeId = 0; private boolean mNfcSecureElementState; private boolean mOpenPending = false; // fields below are used in multiple threads and protected by synchronized(this) private final HashMap<Integer, Object> mObjectMap = new HashMap<Integer, Object>(); private final HashMap<Integer, Object> mSocketMap = new HashMap<Integer, Object>(); private int mTimeout = 0; private boolean mBootComplete = false; private boolean mScreenOn; // fields below are final after onCreate() private Context mContext; private NativeNfcManager mManager; private SharedPreferences mPrefs; private SharedPreferences.Editor mPrefsEditor; private MyTagServer mMyTagServer; private MyTagClient mMyTagClient; private static NfcService sService; public static NfcService getInstance() { return sService; } @Override public void onCreate() { super.onCreate(); Log.i(TAG, "Starting NFC service"); sService = this; mContext = this; mManager = new NativeNfcManager(mContext, this); mManager.initializeNativeStructure(); mMyTagServer = new MyTagServer(); mMyTagClient = new MyTagClient(this); // mMyTagServer.start(); mPrefs = mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE); mPrefsEditor = mPrefs.edit(); mIsNfcEnabled = false; // real preference read later mScreenOn = true; // assume screen is on during boot ServiceManager.addService(SERVICE_NAME, mNfcAdapter); IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED); filter.addAction(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION); filter.addAction(Intent.ACTION_BOOT_COMPLETED); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); mContext.registerReceiver(mReceiver, filter); Thread t = new Thread() { @Override public void run() { boolean nfc_on = mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT); if (nfc_on) { _enable(false); } } }; t.start(); } @Override public void onTerminate() { super.onTerminate(); // NFC application is persistent, it should not be destroyed by framework Log.wtf(TAG, "NFC service is under attack!"); } private final INfcAdapter.Stub mNfcAdapter = new INfcAdapter.Stub() { /** Protected by "this" */ // TODO read this from permanent storage at boot time NdefMessage mLocalMessage = null; public boolean enable() throws RemoteException { mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR); boolean isSuccess = false; boolean previouslyEnabled = isEnabled(); if (!previouslyEnabled) { reset(); isSuccess = _enable(previouslyEnabled); } return isSuccess; } public boolean disable() throws RemoteException { boolean isSuccess = false; mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR); boolean previouslyEnabled = isEnabled(); Log.d(TAG, "Disabling NFC. previous=" + previouslyEnabled); if (previouslyEnabled) { isSuccess = mManager.deinitialize(); Log.d(TAG, "NFC success of deinitialize = " + isSuccess); if (isSuccess) { mIsNfcEnabled = false; } } updateNfcOnSetting(previouslyEnabled); return isSuccess; } public int createLlcpConnectionlessSocket(int sap) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* Check SAP is not already used */ /* Check nb socket created */ if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) { /* Store the socket handle */ int sockeHandle = mGeneratedSocketHandle; if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) { NativeLlcpConnectionlessSocket socket; socket = mManager.doCreateLlcpConnectionlessSocket(sap); if (socket != null) { synchronized(NfcService.this) { /* Update the number of socket created */ mNbSocketCreated++; /* Add the socket into the socket map */ mSocketMap.put(sockeHandle, socket); } return sockeHandle; } else { /* * socket creation error - update the socket handle * generation */ mGeneratedSocketHandle -= 1; /* Get Error Status */ int errorStatus = mManager.doGetLastError(); switch (errorStatus) { case ErrorCodes.ERROR_BUFFER_TO_SMALL: return ErrorCodes.ERROR_BUFFER_TO_SMALL; case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES: return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES; default: return ErrorCodes.ERROR_SOCKET_CREATION; } } } else { /* Check SAP is not already used */ if (!CheckSocketSap(sap)) { return ErrorCodes.ERROR_SAP_USED; } NativeLlcpConnectionlessSocket socket = new NativeLlcpConnectionlessSocket(sap); synchronized(NfcService.this) { /* Add the socket into the socket map */ mSocketMap.put(sockeHandle, socket); /* Update the number of socket created */ mNbSocketCreated++; } /* Create new registered socket */ RegisteredSocket registeredSocket = new RegisteredSocket( LLCP_CONNECTIONLESS_SOCKET_TYPE, sockeHandle, sap); /* Put this socket into a list of registered socket */ mRegisteredSocketList.add(registeredSocket); } /* update socket handle generation */ mGeneratedSocketHandle++; return sockeHandle; } else { /* No socket available */ return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES; } } public int createLlcpServiceSocket(int sap, String sn, int miu, int rw, int linearBufferLength) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) { int sockeHandle = mGeneratedSocketHandle; if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) { NativeLlcpServiceSocket socket; socket = mManager.doCreateLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength); if (socket != null) { synchronized(NfcService.this) { /* Update the number of socket created */ mNbSocketCreated++; /* Add the socket into the socket map */ mSocketMap.put(sockeHandle, socket); } } else { /* socket creation error - update the socket handle counter */ mGeneratedSocketHandle -= 1; /* Get Error Status */ int errorStatus = mManager.doGetLastError(); switch (errorStatus) { case ErrorCodes.ERROR_BUFFER_TO_SMALL: return ErrorCodes.ERROR_BUFFER_TO_SMALL; case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES: return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES; default: return ErrorCodes.ERROR_SOCKET_CREATION; } } } else { /* Check SAP is not already used */ if (!CheckSocketSap(sap)) { return ErrorCodes.ERROR_SAP_USED; } /* Service Name */ if (!CheckSocketServiceName(sn)) { return ErrorCodes.ERROR_SERVICE_NAME_USED; } /* Check socket options */ if (!CheckSocketOptions(miu, rw, linearBufferLength)) { return ErrorCodes.ERROR_SOCKET_OPTIONS; } NativeLlcpServiceSocket socket = new NativeLlcpServiceSocket(sn); synchronized(NfcService.this) { /* Add the socket into the socket map */ mSocketMap.put(sockeHandle, socket); /* Update the number of socket created */ mNbSocketCreated++; } /* Create new registered socket */ RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SERVICE_SOCKET_TYPE, sockeHandle, sap, sn, miu, rw, linearBufferLength); /* Put this socket into a list of registered socket */ mRegisteredSocketList.add(registeredSocket); } /* update socket handle generation */ mGeneratedSocketHandle += 1; Log.d(TAG, "Llcp Service Socket Handle =" + sockeHandle); return sockeHandle; } else { /* No socket available */ return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES; } } public int createLlcpSocket(int sap, int miu, int rw, int linearBufferLength) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) { int sockeHandle = mGeneratedSocketHandle; if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) { NativeLlcpSocket socket; socket = mManager.doCreateLlcpSocket(sap, miu, rw, linearBufferLength); if (socket != null) { synchronized(NfcService.this) { /* Update the number of socket created */ mNbSocketCreated++; /* Add the socket into the socket map */ mSocketMap.put(sockeHandle, socket); } } else { /* * socket creation error - update the socket handle * generation */ mGeneratedSocketHandle -= 1; /* Get Error Status */ int errorStatus = mManager.doGetLastError(); switch (errorStatus) { case ErrorCodes.ERROR_BUFFER_TO_SMALL: return ErrorCodes.ERROR_BUFFER_TO_SMALL; case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES: return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES; default: return ErrorCodes.ERROR_SOCKET_CREATION; } } } else { /* Check SAP is not already used */ if (!CheckSocketSap(sap)) { return ErrorCodes.ERROR_SAP_USED; } /* Check Socket options */ if (!CheckSocketOptions(miu, rw, linearBufferLength)) { return ErrorCodes.ERROR_SOCKET_OPTIONS; } NativeLlcpSocket socket = new NativeLlcpSocket(sap, miu, rw); synchronized(NfcService.this) { /* Add the socket into the socket map */ mSocketMap.put(sockeHandle, socket); /* Update the number of socket created */ mNbSocketCreated++; } /* Create new registered socket */ RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SOCKET_TYPE, sockeHandle, sap, miu, rw, linearBufferLength); /* Put this socket into a list of registered socket */ mRegisteredSocketList.add(registeredSocket); } /* update socket handle generation */ mGeneratedSocketHandle++; return sockeHandle; } else { /* No socket available */ return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES; } } public int deselectSecureElement() throws RemoteException { mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR); // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } if (mSelectedSeId == 0) { return ErrorCodes.ERROR_NO_SE_CONNECTED; } mManager.doDeselectSecureElement(mSelectedSeId); mNfcSecureElementState = false; mSelectedSeId = 0; /* store preference */ mPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, false); mPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, 0); mPrefsEditor.apply(); return ErrorCodes.SUCCESS; } public ILlcpConnectionlessSocket getLlcpConnectionlessInterface() throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); return mLlcpConnectionlessSocketService; } public ILlcpSocket getLlcpInterface() throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); return mLlcpSocket; } public ILlcpServiceSocket getLlcpServiceInterface() throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); return mLlcpServerSocketService; } public INfcTag getNfcTagInterface() throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); return mNfcTagService; } public synchronized int getOpenTimeout() throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); return mTimeout; } public IP2pInitiator getP2pInitiatorInterface() throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); return mP2pInitiatorService; } public IP2pTarget getP2pTargetInterface() throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); return mP2pTargetService; } public String getProperties(String param) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); if (param == null) { return null; } if (param.equals(PROPERTY_LLCP_LTO_VALUE)) { return Integer.toString(mPrefs.getInt(PREF_LLCP_LTO, LLCP_LTO_DEFAULT)); } else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) { return Integer.toString(mPrefs.getInt(PREF_LLCP_MIU, LLCP_MIU_DEFAULT)); } else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) { return Integer.toString(mPrefs.getInt(PREF_LLCP_WKS, LLCP_WKS_DEFAULT)); } else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) { return Integer.toString(mPrefs.getInt(PREF_LLCP_OPT, LLCP_OPT_DEFAULT)); } else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) { return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_A, DISCOVERY_A_DEFAULT)); } else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) { return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_B, DISCOVERY_B_DEFAULT)); } else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) { return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_F, DISCOVERY_F_DEFAULT)); } else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) { return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_NFCIP, DISCOVERY_NFCIP_DEFAULT)); } else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) { return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_15693, DISCOVERY_15693_DEFAULT)); } else { return "Unknown property"; } } public int[] getSecureElementList() throws RemoteException { mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR); int[] list = null; if (mIsNfcEnabled == true) { list = mManager.doGetSecureElementList(); } return list; } public int getSelectedSecureElement() throws RemoteException { mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR); return mSelectedSeId; } public boolean isEnabled() throws RemoteException { return mIsNfcEnabled; } public void openTagConnection(Tag tag) throws RemoteException { // TODO: Remove obsolete code } public int selectSecureElement(int seId) throws RemoteException { mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR); // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } if (mSelectedSeId == seId) { return ErrorCodes.ERROR_SE_ALREADY_SELECTED; } if (mSelectedSeId != 0) { return ErrorCodes.ERROR_SE_CONNECTED; } mSelectedSeId = seId; mManager.doSelectSecureElement(mSelectedSeId); /* store */ mPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, true); mPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, mSelectedSeId); mPrefsEditor.apply(); mNfcSecureElementState = true; return ErrorCodes.SUCCESS; } public synchronized void setOpenTimeout(int timeout) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); mTimeout = timeout; } public int setProperties(String param, String value) throws RemoteException { mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR); if (isEnabled()) { return ErrorCodes.ERROR_NFC_ON; } int val; /* Check params validity */ if (param == null || value == null) { return ErrorCodes.ERROR_INVALID_PARAM; } if (param.equals(PROPERTY_LLCP_LTO_VALUE)) { val = Integer.parseInt(value); /* Check params */ if (val > LLCP_LTO_MAX) return ErrorCodes.ERROR_INVALID_PARAM; /* Store value */ mPrefsEditor.putInt(PREF_LLCP_LTO, val); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_LLCP_LTO, val); } else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) { val = Integer.parseInt(value); /* Check params */ if ((val < LLCP_MIU_DEFAULT) || (val > LLCP_MIU_MAX)) return ErrorCodes.ERROR_INVALID_PARAM; /* Store value */ mPrefsEditor.putInt(PREF_LLCP_MIU, val); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_LLCP_MIU, val); } else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) { val = Integer.parseInt(value); /* Check params */ if (val > LLCP_WKS_MAX) return ErrorCodes.ERROR_INVALID_PARAM; /* Store value */ mPrefsEditor.putInt(PREF_LLCP_WKS, val); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_LLCP_WKS, val); } else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) { val = Integer.parseInt(value); /* Check params */ if (val > LLCP_OPT_MAX) return ErrorCodes.ERROR_INVALID_PARAM; /* Store value */ mPrefsEditor.putInt(PREF_LLCP_OPT, val); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_LLCP_OPT, val); } else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) { boolean b = Boolean.parseBoolean(value); /* Store value */ mPrefsEditor.putBoolean(PREF_DISCOVERY_A, b); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A, b ? 1 : 0); } else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) { boolean b = Boolean.parseBoolean(value); /* Store value */ mPrefsEditor.putBoolean(PREF_DISCOVERY_B, b); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B, b ? 1 : 0); } else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) { boolean b = Boolean.parseBoolean(value); /* Store value */ mPrefsEditor.putBoolean(PREF_DISCOVERY_F, b); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F, b ? 1 : 0); } else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) { boolean b = Boolean.parseBoolean(value); /* Store value */ mPrefsEditor.putBoolean(PREF_DISCOVERY_15693, b); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693, b ? 1 : 0); } else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) { boolean b = Boolean.parseBoolean(value); /* Store value */ mPrefsEditor.putBoolean(PREF_DISCOVERY_NFCIP, b); mPrefsEditor.apply(); /* Update JNI */ mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP, b ? 1 : 0); } else { return ErrorCodes.ERROR_INVALID_PARAM; } return ErrorCodes.SUCCESS; } @Override public NdefMessage localGet() throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); synchronized (this) { return mLocalMessage; } } @Override public void localSet(NdefMessage message) throws RemoteException { mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR); synchronized (this) { mLocalMessage = message; // Send a message to the UI thread to show or hide the icon so the requests are // serialized and the icon can't get out of sync with reality. if (message != null) { sendMessage(MSG_SHOW_MY_TAG_ICON, null); } else { sendMessage(MSG_HIDE_MY_TAG_ICON, null); } } } }; private final ILlcpSocket mLlcpSocket = new ILlcpSocket.Stub() { private final int CONNECT_FLAG = 0x01; private final int CLOSE_FLAG = 0x02; private final int RECV_FLAG = 0x04; private final int SEND_FLAG = 0x08; private int concurrencyFlags; private Object sync; public int close(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) { isSuccess = socket.doClose(); if (isSuccess) { /* Remove the socket closed from the hmap */ RemoveSocket(nativeHandle); /* Update mNbSocketCreated */ mNbSocketCreated--; return ErrorCodes.SUCCESS; } else { return ErrorCodes.ERROR_IO; } } else { /* Remove the socket closed from the hmap */ RemoveSocket(nativeHandle); /* Remove registered socket from the list */ RemoveRegisteredSocket(nativeHandle); /* Update mNbSocketCreated */ mNbSocketCreated--; return ErrorCodes.SUCCESS; } } else { return ErrorCodes.ERROR_IO; } } public int connect(int nativeHandle, int sap) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { isSuccess = socket.doConnect(sap, socket.getConnectTimeout()); if (isSuccess) { return ErrorCodes.SUCCESS; } else { return ErrorCodes.ERROR_IO; } } else { return ErrorCodes.ERROR_IO; } } public int connectByName(int nativeHandle, String sn) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { isSuccess = socket.doConnectBy(sn, socket.getConnectTimeout()); if (isSuccess) { return ErrorCodes.SUCCESS; } else { return ErrorCodes.ERROR_IO; } } else { return ErrorCodes.ERROR_IO; } } public int getConnectTimeout(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { return socket.getConnectTimeout(); } else { return 0; } } public int getLocalSap(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { return socket.getSap(); } else { return 0; } } public int getLocalSocketMiu(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { return socket.getMiu(); } else { return 0; } } public int getLocalSocketRw(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { return socket.getRw(); } else { return 0; } } public int getRemoteSocketMiu(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { if (socket.doGetRemoteSocketMiu() != 0) { return socket.doGetRemoteSocketMiu(); } else { return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED; } } else { return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED; } } public int getRemoteSocketRw(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { if (socket.doGetRemoteSocketRw() != 0) { return socket.doGetRemoteSocketRw(); } else { return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED; } } else { return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED; } } public int receive(int nativeHandle, byte[] receiveBuffer) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; int receiveLength = 0; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { receiveLength = socket.doReceive(receiveBuffer); if (receiveLength != 0) { return receiveLength; } else { return ErrorCodes.ERROR_IO; } } else { return ErrorCodes.ERROR_IO; } } public int send(int nativeHandle, byte[] data) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { isSuccess = socket.doSend(data); if (isSuccess) { return ErrorCodes.SUCCESS; } else { return ErrorCodes.ERROR_IO; } } else { return ErrorCodes.ERROR_IO; } } public void setConnectTimeout(int nativeHandle, int timeout) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpSocket socket = null; /* find the socket in the hmap */ socket = (NativeLlcpSocket) findSocket(nativeHandle); if (socket != null) { socket.setConnectTimeout(timeout); } } }; private final ILlcpServiceSocket mLlcpServerSocketService = new ILlcpServiceSocket.Stub() { public int accept(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpServiceSocket socket = null; NativeLlcpSocket clientSocket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) { /* find the socket in the hmap */ socket = (NativeLlcpServiceSocket) findSocket(nativeHandle); if (socket != null) { clientSocket = socket.doAccept(socket.getAcceptTimeout(), socket.getMiu(), socket.getRw(), socket.getLinearBufferLength()); if (clientSocket != null) { /* Add the socket into the socket map */ synchronized(this) { mSocketMap.put(clientSocket.getHandle(), clientSocket); mNbSocketCreated++; } return clientSocket.getHandle(); } else { return ErrorCodes.ERROR_IO; } } else { return ErrorCodes.ERROR_IO; } } else { return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES; } } public void close(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpServiceSocket socket = null; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return; } /* find the socket in the hmap */ socket = (NativeLlcpServiceSocket) findSocket(nativeHandle); if (socket != null) { if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) { isSuccess = socket.doClose(); if (isSuccess) { /* Remove the socket closed from the hmap */ RemoveSocket(nativeHandle); /* Update mNbSocketCreated */ mNbSocketCreated--; } } else { /* Remove the socket closed from the hmap */ RemoveSocket(nativeHandle); /* Remove registered socket from the list */ RemoveRegisteredSocket(nativeHandle); /* Update mNbSocketCreated */ mNbSocketCreated--; } } } public int getAcceptTimeout(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpServiceSocket socket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpServiceSocket) findSocket(nativeHandle); if (socket != null) { return socket.getAcceptTimeout(); } else { return 0; } } public void setAcceptTimeout(int nativeHandle, int timeout) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpServiceSocket socket = null; /* find the socket in the hmap */ socket = (NativeLlcpServiceSocket) findSocket(nativeHandle); if (socket != null) { socket.setAcceptTimeout(timeout); } } }; private final ILlcpConnectionlessSocket mLlcpConnectionlessSocketService = new ILlcpConnectionlessSocket.Stub() { public void close(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpConnectionlessSocket socket = null; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return; } /* find the socket in the hmap */ socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle); if (socket != null) { if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) { isSuccess = socket.doClose(); if (isSuccess) { /* Remove the socket closed from the hmap */ RemoveSocket(nativeHandle); /* Update mNbSocketCreated */ mNbSocketCreated--; } } else { /* Remove the socket closed from the hmap */ RemoveSocket(nativeHandle); /* Remove registered socket from the list */ RemoveRegisteredSocket(nativeHandle); /* Update mNbSocketCreated */ mNbSocketCreated--; } } } public int getSap(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpConnectionlessSocket socket = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle); if (socket != null) { return socket.getSap(); } else { return 0; } } public LlcpPacket receiveFrom(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpConnectionlessSocket socket = null; LlcpPacket packet; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the socket in the hmap */ socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle); if (socket != null) { packet = socket.doReceiveFrom(socket.getLinkMiu()); if (packet != null) { return packet; } return null; } else { return null; } } public int sendTo(int nativeHandle, LlcpPacket packet) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeLlcpConnectionlessSocket socket = null; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the socket in the hmap */ socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle); if (socket != null) { isSuccess = socket.doSendTo(packet.getRemoteSap(), packet.getDataBuffer()); if (isSuccess) { return ErrorCodes.SUCCESS; } else { return ErrorCodes.ERROR_IO; } } else { return ErrorCodes.ERROR_IO; } } }; private final INfcTag mNfcTagService = new INfcTag.Stub() { public int close(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeNfcTag tag = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag != null) { /* Remove the device from the hmap */ unregisterObject(nativeHandle); tag.asyncDisconnect(); return ErrorCodes.SUCCESS; } /* Restart polling loop for notification */ maybeEnableDiscovery(); mOpenPending = false; return ErrorCodes.ERROR_DISCONNECT; } public int connect(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeNfcTag tag = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag == null) { return ErrorCodes.ERROR_DISCONNECT; } // TODO: register the tag as being locked rather than really connect return ErrorCodes.SUCCESS; } public String getType(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeNfcTag tag = null; String type; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag != null) { type = tag.getType(); return type; } return null; } public byte[] getUid(int nativeHandle) throws RemoteException { NativeNfcTag tag = null; byte[] uid; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag != null) { uid = tag.getUid(); return uid; } return null; } public boolean isPresent(int nativeHandle) throws RemoteException { NativeNfcTag tag = null; // Check if NFC is enabled if (!mIsNfcEnabled) { return false; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag == null) { return false; } return tag.presenceCheck(); } public boolean isNdef(int nativeHandle) throws RemoteException { NativeNfcTag tag = null; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return isSuccess; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag != null) { isSuccess = tag.checkNdef(); } return isSuccess; } public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeNfcTag tag = null; byte[] response; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag != null) { response = tag.transceive(data); return response; } return null; } public NdefMessage read(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeNfcTag tag; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag != null) { byte[] buf = tag.read(); if (buf == null) return null; /* Create an NdefMessage */ try { return new NdefMessage(buf); } catch (FormatException e) { return null; } } return null; } public int write(int nativeHandle, NdefMessage msg) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeNfcTag tag; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the tag in the hmap */ tag = (NativeNfcTag) findObject(nativeHandle); if (tag == null) { return ErrorCodes.ERROR_IO; } if (tag.write(msg.toByteArray())) { return ErrorCodes.SUCCESS; } else { return ErrorCodes.ERROR_IO; } } public int getLastError(int nativeHandle) throws RemoteException { // TODO Auto-generated method stub return 0; } public int getModeHint(int nativeHandle) throws RemoteException { // TODO Auto-generated method stub return 0; } public int makeReadOnly(int nativeHandle) throws RemoteException { // TODO Auto-generated method stub return 0; } }; private final IP2pInitiator mP2pInitiatorService = new IP2pInitiator.Stub() { public byte[] getGeneralBytes(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { byte[] buff = device.getGeneralBytes(); if (buff == null) return null; return buff; } return null; } public int getMode(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { return device.getMode(); } return ErrorCodes.ERROR_INVALID_PARAM; } public byte[] receive(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { byte[] buff = device.doReceive(); if (buff == null) return null; return buff; } /* Restart polling loop for notification */ maybeEnableDiscovery(); mOpenPending = false; return null; } public boolean send(int nativeHandle, byte[] data) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return isSuccess; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { isSuccess = device.doSend(data); } return isSuccess; } }; private final IP2pTarget mP2pTargetService = new IP2pTarget.Stub() { public int connect(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { if (device.doConnect()) { return ErrorCodes.SUCCESS; } } return ErrorCodes.ERROR_CONNECT; } public boolean disconnect(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; boolean isSuccess = false; // Check if NFC is enabled if (!mIsNfcEnabled) { return isSuccess; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { if (isSuccess = device.doDisconnect()) { mOpenPending = false; /* remove the device from the hmap */ unregisterObject(nativeHandle); /* Restart polling loop for notification */ maybeEnableDiscovery(); } } return isSuccess; } public byte[] getGeneralBytes(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { byte[] buff = device.getGeneralBytes(); if (buff == null) return null; return buff; } return null; } public int getMode(int nativeHandle) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; // Check if NFC is enabled if (!mIsNfcEnabled) { return ErrorCodes.ERROR_NOT_INITIALIZED; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { return device.getMode(); } return ErrorCodes.ERROR_INVALID_PARAM; } public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException { mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR); NativeP2pDevice device; // Check if NFC is enabled if (!mIsNfcEnabled) { return null; } /* find the device in the hmap */ device = (NativeP2pDevice) findObject(nativeHandle); if (device != null) { byte[] buff = device.doTransceive(data); if (buff == null) return null; return buff; } return null; } }; private boolean _enable(boolean oldEnabledState) { boolean isSuccess = mManager.initialize(); if (isSuccess) { applyProperties(); /* Check Secure Element setting */ mNfcSecureElementState = mPrefs.getBoolean(PREF_SECURE_ELEMENT_ON, SECURE_ELEMENT_ON_DEFAULT); if (mNfcSecureElementState) { int secureElementId = mPrefs.getInt(PREF_SECURE_ELEMENT_ID, SECURE_ELEMENT_ID_DEFAULT); int[] Se_list = mManager.doGetSecureElementList(); if (Se_list != null) { for (int i = 0; i < Se_list.length; i++) { if (Se_list[i] == secureElementId) { mManager.doSelectSecureElement(Se_list[i]); mSelectedSeId = Se_list[i]; break; } } } } mIsNfcEnabled = true; /* Start polling loop */ maybeEnableDiscovery(); } else { mIsNfcEnabled = false; } updateNfcOnSetting(oldEnabledState); return isSuccess; } /** Enable active tag discovery if screen is on and NFC is enabled */ private synchronized void maybeEnableDiscovery() { if (mScreenOn && mIsNfcEnabled) { mManager.enableDiscovery(DISCOVERY_MODE_READER); // mMyTagServer.start(); } } /** Disable active tag discovery if necessary */ private synchronized void maybeDisableDiscovery() { if (mIsNfcEnabled) { mManager.disableDiscovery(); // mMyTagServer.stop(); } } private void applyProperties() { mManager.doSetProperties(PROPERTY_LLCP_LTO, mPrefs.getInt(PREF_LLCP_LTO, LLCP_LTO_DEFAULT)); mManager.doSetProperties(PROPERTY_LLCP_MIU, mPrefs.getInt(PREF_LLCP_MIU, LLCP_MIU_DEFAULT)); mManager.doSetProperties(PROPERTY_LLCP_WKS, mPrefs.getInt(PREF_LLCP_WKS, LLCP_WKS_DEFAULT)); mManager.doSetProperties(PROPERTY_LLCP_OPT, mPrefs.getInt(PREF_LLCP_OPT, LLCP_OPT_DEFAULT)); mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A, mPrefs.getBoolean(PREF_DISCOVERY_A, DISCOVERY_A_DEFAULT) ? 1 : 0); mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B, mPrefs.getBoolean(PREF_DISCOVERY_B, DISCOVERY_B_DEFAULT) ? 1 : 0); mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F, mPrefs.getBoolean(PREF_DISCOVERY_F, DISCOVERY_F_DEFAULT) ? 1 : 0); mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693, mPrefs.getBoolean(PREF_DISCOVERY_15693, DISCOVERY_15693_DEFAULT) ? 1 : 0); mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP, mPrefs.getBoolean(PREF_DISCOVERY_NFCIP, DISCOVERY_NFCIP_DEFAULT) ? 1 : 0); } private void updateNfcOnSetting(boolean oldEnabledState) { int state; mPrefsEditor.putBoolean(PREF_NFC_ON, mIsNfcEnabled); mPrefsEditor.apply(); synchronized(this) { if (mBootComplete && oldEnabledState != mIsNfcEnabled) { Intent intent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGE); intent.putExtra(NfcAdapter.EXTRA_NEW_BOOLEAN_STATE, mIsNfcEnabled); mContext.sendBroadcast(intent); } } } // Reset all internals private synchronized void reset() { // TODO: none of these appear to be synchronized but are // read/written from different threads (notably Binder threads)... // Clear tables mObjectMap.clear(); mSocketMap.clear(); mRegisteredSocketList.clear(); // Reset variables mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED; mNbSocketCreated = 0; mIsNfcEnabled = false; mSelectedSeId = 0; mTimeout = 0; mOpenPending = false; } private synchronized Object findObject(int key) { Object device = null; device = mObjectMap.get(key); if (device == null) { Log.w(TAG, "Handle not found !"); } return device; } synchronized void registerTagObject(NativeNfcTag nativeTag) { mObjectMap.put(nativeTag.getHandle(), nativeTag); } synchronized void unregisterObject(int handle) { mObjectMap.remove(handle); } private synchronized Object findSocket(int key) { Object socket = null; socket = mSocketMap.get(key); return socket; } private void RemoveSocket(int key) { mSocketMap.remove(key); } private boolean CheckSocketSap(int sap) { /* List of sockets registered */ ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator(); while (it.hasNext()) { RegisteredSocket registeredSocket = it.next(); if (sap == registeredSocket.mSap) { /* SAP already used */ return false; } } return true; } private boolean CheckSocketOptions(int miu, int rw, int linearBufferlength) { if (rw > LLCP_RW_MAX_VALUE || miu < LLCP_MIU_DEFAULT || linearBufferlength < miu) { return false; } return true; } private boolean CheckSocketServiceName(String sn) { /* List of sockets registered */ ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator(); while (it.hasNext()) { RegisteredSocket registeredSocket = it.next(); if (sn.equals(registeredSocket.mServiceName)) { /* Service Name already used */ return false; } } return true; } private void RemoveRegisteredSocket(int nativeHandle) { /* check if sockets are registered */ ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator(); while (it.hasNext()) { RegisteredSocket registeredSocket = it.next(); if (registeredSocket.mHandle == nativeHandle) { /* remove the registered socket from the list */ it.remove(); Log.d(TAG, "socket removed"); } } } /* * RegisteredSocket class to store the creation request of socket until the * LLCP link in not activated */ private class RegisteredSocket { private final int mType; private final int mHandle; private final int mSap; private int mMiu; private int mRw; private String mServiceName; private int mlinearBufferLength; RegisteredSocket(int type, int handle, int sap, String sn, int miu, int rw, int linearBufferLength) { mType = type; mHandle = handle; mSap = sap; mServiceName = sn; mRw = rw; mMiu = miu; mlinearBufferLength = linearBufferLength; } RegisteredSocket(int type, int handle, int sap, int miu, int rw, int linearBufferLength) { mType = type; mHandle = handle; mSap = sap; mRw = rw; mMiu = miu; mlinearBufferLength = linearBufferLength; } RegisteredSocket(int type, int handle, int sap) { mType = type; mHandle = handle; mSap = sap; } } /** For use by code in this process */ public LlcpSocket createLlcpSocket(int sap, int miu, int rw, int linearBufferLength) { try { int handle = mNfcAdapter.createLlcpSocket(sap, miu, rw, linearBufferLength); return new LlcpSocket(mLlcpSocket, handle); } catch (RemoteException e) { // This will never happen since the code is calling into it's own process throw new IllegalStateException("unable to talk to myself", e); } } /** For use by code in this process */ public LlcpServiceSocket createLlcpServiceSocket(int sap, String sn, int miu, int rw, int linearBufferLength) { try { int handle = mNfcAdapter.createLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength); return new LlcpServiceSocket(mLlcpServerSocketService, mLlcpSocket, handle); } catch (RemoteException e) { // This will never happen since the code is calling into it's own process throw new IllegalStateException("unable to talk to myself", e); } } private void activateLlcpLink() { /* check if sockets are registered */ ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator(); Log.d(TAG, "Nb socket resgistered = " + mRegisteredSocketList.size()); while (it.hasNext()) { RegisteredSocket registeredSocket = it.next(); switch (registeredSocket.mType) { case LLCP_SERVICE_SOCKET_TYPE: Log.d(TAG, "Registered Llcp Service Socket"); NativeLlcpServiceSocket serviceSocket; serviceSocket = mManager.doCreateLlcpServiceSocket( registeredSocket.mSap, registeredSocket.mServiceName, registeredSocket.mMiu, registeredSocket.mRw, registeredSocket.mlinearBufferLength); if (serviceSocket != null) { /* Add the socket into the socket map */ synchronized(NfcService.this) { mSocketMap.put(registeredSocket.mHandle, serviceSocket); } } else { /* socket creation error - update the socket * handle counter */ mGeneratedSocketHandle -= 1; } break; case LLCP_SOCKET_TYPE: Log.d(TAG, "Registered Llcp Socket"); NativeLlcpSocket clientSocket; clientSocket = mManager.doCreateLlcpSocket(registeredSocket.mSap, registeredSocket.mMiu, registeredSocket.mRw, registeredSocket.mlinearBufferLength); if (clientSocket != null) { /* Add the socket into the socket map */ synchronized(NfcService.this) { mSocketMap.put(registeredSocket.mHandle, clientSocket); } } else { /* socket creation error - update the socket * handle counter */ mGeneratedSocketHandle -= 1; } break; case LLCP_CONNECTIONLESS_SOCKET_TYPE: Log.d(TAG, "Registered Llcp Connectionless Socket"); NativeLlcpConnectionlessSocket connectionlessSocket; connectionlessSocket = mManager.doCreateLlcpConnectionlessSocket( registeredSocket.mSap); if (connectionlessSocket != null) { /* Add the socket into the socket map */ synchronized(NfcService.this) { mSocketMap.put(registeredSocket.mHandle, connectionlessSocket); } } else { /* socket creation error - update the socket * handle counter */ mGeneratedSocketHandle -= 1; } break; } } /* Remove all registered socket from the list */ mRegisteredSocketList.clear(); /* Broadcast Intent Link LLCP activated */ Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED); LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED, NfcAdapter.LLCP_LINK_STATE_ACTIVATED); Log.d(TAG, "Broadcasting LLCP activation"); mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM); } public void sendMockNdefTag(NdefMessage msg) { NdefTag tag = NdefTag.createMockNdefTag(new byte[] { 0x00 }, new String[] { Tag.TARGET_OTHER }, null, null, new String[] { NdefTag.TARGET_OTHER }, new NdefMessage[][] { new NdefMessage[] { msg } }); sendMessage(MSG_MOCK_NDEF_TAG, tag); } void sendMessage(int what, Object obj) { Message msg = mHandler.obtainMessage(); msg.what = what; msg.obj = obj; mHandler.sendMessage(msg); } private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_MOCK_NDEF_TAG: { NdefTag tag = (NdefTag) msg.obj; Intent intent = buildNdefTagIntent(tag); Log.d(TAG, "mock NDEF tag, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found for mock tag"); } } case MSG_NDEF_TAG: Log.d(TAG, "Tag detected, notifying applications"); NativeNfcTag nativeTag = (NativeNfcTag) msg.obj; if (nativeTag.connect()) { if (nativeTag.checkNdef()) { byte[] buff = nativeTag.read(); if (buff != null) { NdefMessage[] msgNdef = new NdefMessage[1]; try { msgNdef[0] = new NdefMessage(buff); NdefTag tag = new NdefTag(nativeTag.getUid(), TagTarget.internalTypeToRawTargets(nativeTag.getType()), null, null, nativeTag.getHandle(), TagTarget.internalTypeToNdefTargets(nativeTag.getType()), new NdefMessage[][] {msgNdef}); Intent intent = buildNdefTagIntent(tag); Log.d(TAG, "NDEF tag found, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); + registerTagObject(nativeTag); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found, disconnecting"); nativeTag.asyncDisconnect(); } } catch (FormatException e) { Log.w(TAG, "Unable to create NDEF message object (tag empty or not well formated)"); nativeTag.asyncDisconnect(); } } else { Log.w(TAG, "Unable to read NDEF message (tag empty or not well formated)"); nativeTag.asyncDisconnect(); } } else { Intent intent = new Intent(); Tag tag = new Tag(nativeTag.getUid(), false, TagTarget.internalTypeToRawTargets(nativeTag.getType()), null, null, nativeTag.getHandle()); intent.setAction(NfcAdapter.ACTION_TAG_DISCOVERED); intent.putExtra(NfcAdapter.EXTRA_TAG, tag); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Log.d(TAG, "Non-NDEF tag found, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); + registerTagObject(nativeTag); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found, disconnecting"); nativeTag.asyncDisconnect(); } } } else { Log.w(TAG, "Failed to connect to tag"); nativeTag.asyncDisconnect(); } break; case MSG_CARD_EMULATION: Log.d(TAG, "Card Emulation message"); byte[] aid = (byte[]) msg.obj; /* Send broadcast ordered */ Intent TransactionIntent = new Intent(); TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED); TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid); Log.d(TAG, "Broadcasting Card Emulation event"); mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM); break; case MSG_LLCP_LINK_ACTIVATION: NativeP2pDevice device = (NativeP2pDevice) msg.obj; Log.d(TAG, "LLCP Activation message"); if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) { if (device.doConnect()) { /* Check Llcp compliancy */ if (mManager.doCheckLlcp()) { /* Activate Llcp Link */ if (mManager.doActivateLlcp()) { Log.d(TAG, "Initiator Activate LLCP OK"); /* Broadcast Intent Link LLCP activated */ Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent .setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION); LlcpLinkIntent.putExtra( mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA, NfcAdapter.LLCP_LINK_STATE_ACTIVATED); Log.d(TAG, "Broadcasting internal LLCP activation"); mContext.sendBroadcast(LlcpLinkIntent); } } else { device.doDisconnect(); } } } else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) { /* Check Llcp compliancy */ if (mManager.doCheckLlcp()) { /* Activate Llcp Link */ if (mManager.doActivateLlcp()) { Log.d(TAG, "Target Activate LLCP OK"); /* Broadcast Intent Link LLCP activated */ Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent .setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION); LlcpLinkIntent.putExtra(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA, NfcAdapter.LLCP_LINK_STATE_ACTIVATED); Log.d(TAG, "Broadcasting internal LLCP activation"); mContext.sendBroadcast(LlcpLinkIntent); } } } break; case MSG_LLCP_LINK_DEACTIVATED: /* Broadcast Intent Link LLCP activated */ Log.d(TAG, "LLCP Link Deactivated message"); Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED); LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED, NfcAdapter.LLCP_LINK_STATE_DEACTIVATED); Log.d(TAG, "Broadcasting LLCP deactivation"); mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM); break; case MSG_TARGET_DESELECTED: /* Broadcast Intent Target Deselected */ Log.d(TAG, "Target Deselected"); Intent TargetDeselectedIntent = new Intent(); TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION); Log.d(TAG, "Broadcasting Intent"); mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM); break; case MSG_SHOW_MY_TAG_ICON: { StatusBarManager sb = (StatusBarManager) getSystemService( Context.STATUS_BAR_SERVICE); sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0); break; } case MSG_HIDE_MY_TAG_ICON: { StatusBarManager sb = (StatusBarManager) getSystemService( Context.STATUS_BAR_SERVICE); sb.removeIcon("nfc"); break; } default: Log.e(TAG, "Unknown message received"); break; } } private Intent buildNdefTagIntent(NdefTag tag) { Intent intent = new Intent(); intent.setAction(NfcAdapter.ACTION_NDEF_TAG_DISCOVERED); intent.putExtra(NfcAdapter.EXTRA_TAG, tag); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } }; private class EnableDisableDiscoveryTask extends AsyncTask<Boolean, Void, Void> { protected Void doInBackground(Boolean... enable) { if (enable != null && enable.length > 0 && enable[0]) { maybeEnableDiscovery(); } else { maybeDisableDiscovery(); } return null; } } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED)) { Log.d(TAG, "LLCP_LINK_STATE_CHANGED"); mLlcpLinkState = intent.getIntExtra( NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED, NfcAdapter.LLCP_LINK_STATE_DEACTIVATED); if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_DEACTIVATED) { /* restart polling loop */ maybeEnableDiscovery(); } else if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) { activateLlcpLink(); } } else if (intent.getAction().equals( NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION)) { Log.d(TAG, "INERNAL_TARGET_DESELECTED_ACTION"); mOpenPending = false; /* Restart polling loop for notification */ maybeEnableDiscovery(); } else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { Log.i(TAG, "Boot complete"); synchronized(this) { mBootComplete = true; // now its safe to send the NFC state Intent sendIntent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGE); sendIntent.putExtra(NfcAdapter.EXTRA_NEW_BOOLEAN_STATE, mIsNfcEnabled); mContext.sendBroadcast(sendIntent); } } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { synchronized (NfcService.this) { mScreenOn = true; } // Perform discovery enable in thread to protect against ANR when the // NFC stack wedges. This is *not* the correct way to fix this issue - // configuration of the local NFC adapter should be very quick and should // be safe on the main thread, and the NFC stack should not wedge. new EnableDisableDiscoveryTask().execute(new Boolean(true)); } else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { synchronized (NfcService.this) { mScreenOn = false; } // Perform discovery disable in thread to protect against ANR when the // NFC stack wedges. This is *not* the correct way to fix this issue - // configuration of the local NFC adapter should be very quick and should // be safe on the main thread, and the NFC stack should not wedge. new EnableDisableDiscoveryTask().execute(new Boolean(false)); } } }; }
false
true
public void handleMessage(Message msg) { switch (msg.what) { case MSG_MOCK_NDEF_TAG: { NdefTag tag = (NdefTag) msg.obj; Intent intent = buildNdefTagIntent(tag); Log.d(TAG, "mock NDEF tag, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found for mock tag"); } } case MSG_NDEF_TAG: Log.d(TAG, "Tag detected, notifying applications"); NativeNfcTag nativeTag = (NativeNfcTag) msg.obj; if (nativeTag.connect()) { if (nativeTag.checkNdef()) { byte[] buff = nativeTag.read(); if (buff != null) { NdefMessage[] msgNdef = new NdefMessage[1]; try { msgNdef[0] = new NdefMessage(buff); NdefTag tag = new NdefTag(nativeTag.getUid(), TagTarget.internalTypeToRawTargets(nativeTag.getType()), null, null, nativeTag.getHandle(), TagTarget.internalTypeToNdefTargets(nativeTag.getType()), new NdefMessage[][] {msgNdef}); Intent intent = buildNdefTagIntent(tag); Log.d(TAG, "NDEF tag found, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found, disconnecting"); nativeTag.asyncDisconnect(); } } catch (FormatException e) { Log.w(TAG, "Unable to create NDEF message object (tag empty or not well formated)"); nativeTag.asyncDisconnect(); } } else { Log.w(TAG, "Unable to read NDEF message (tag empty or not well formated)"); nativeTag.asyncDisconnect(); } } else { Intent intent = new Intent(); Tag tag = new Tag(nativeTag.getUid(), false, TagTarget.internalTypeToRawTargets(nativeTag.getType()), null, null, nativeTag.getHandle()); intent.setAction(NfcAdapter.ACTION_TAG_DISCOVERED); intent.putExtra(NfcAdapter.EXTRA_TAG, tag); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Log.d(TAG, "Non-NDEF tag found, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found, disconnecting"); nativeTag.asyncDisconnect(); } } } else { Log.w(TAG, "Failed to connect to tag"); nativeTag.asyncDisconnect(); } break; case MSG_CARD_EMULATION: Log.d(TAG, "Card Emulation message"); byte[] aid = (byte[]) msg.obj; /* Send broadcast ordered */ Intent TransactionIntent = new Intent(); TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED); TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid); Log.d(TAG, "Broadcasting Card Emulation event"); mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM); break; case MSG_LLCP_LINK_ACTIVATION: NativeP2pDevice device = (NativeP2pDevice) msg.obj; Log.d(TAG, "LLCP Activation message"); if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) { if (device.doConnect()) { /* Check Llcp compliancy */ if (mManager.doCheckLlcp()) { /* Activate Llcp Link */ if (mManager.doActivateLlcp()) { Log.d(TAG, "Initiator Activate LLCP OK"); /* Broadcast Intent Link LLCP activated */ Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent .setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION); LlcpLinkIntent.putExtra( mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA, NfcAdapter.LLCP_LINK_STATE_ACTIVATED); Log.d(TAG, "Broadcasting internal LLCP activation"); mContext.sendBroadcast(LlcpLinkIntent); } } else { device.doDisconnect(); } } } else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) { /* Check Llcp compliancy */ if (mManager.doCheckLlcp()) { /* Activate Llcp Link */ if (mManager.doActivateLlcp()) { Log.d(TAG, "Target Activate LLCP OK"); /* Broadcast Intent Link LLCP activated */ Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent .setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION); LlcpLinkIntent.putExtra(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA, NfcAdapter.LLCP_LINK_STATE_ACTIVATED); Log.d(TAG, "Broadcasting internal LLCP activation"); mContext.sendBroadcast(LlcpLinkIntent); } } } break; case MSG_LLCP_LINK_DEACTIVATED: /* Broadcast Intent Link LLCP activated */ Log.d(TAG, "LLCP Link Deactivated message"); Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED); LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED, NfcAdapter.LLCP_LINK_STATE_DEACTIVATED); Log.d(TAG, "Broadcasting LLCP deactivation"); mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM); break; case MSG_TARGET_DESELECTED: /* Broadcast Intent Target Deselected */ Log.d(TAG, "Target Deselected"); Intent TargetDeselectedIntent = new Intent(); TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION); Log.d(TAG, "Broadcasting Intent"); mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM); break; case MSG_SHOW_MY_TAG_ICON: { StatusBarManager sb = (StatusBarManager) getSystemService( Context.STATUS_BAR_SERVICE); sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0); break; } case MSG_HIDE_MY_TAG_ICON: { StatusBarManager sb = (StatusBarManager) getSystemService( Context.STATUS_BAR_SERVICE); sb.removeIcon("nfc"); break; } default: Log.e(TAG, "Unknown message received"); break; } }
public void handleMessage(Message msg) { switch (msg.what) { case MSG_MOCK_NDEF_TAG: { NdefTag tag = (NdefTag) msg.obj; Intent intent = buildNdefTagIntent(tag); Log.d(TAG, "mock NDEF tag, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found for mock tag"); } } case MSG_NDEF_TAG: Log.d(TAG, "Tag detected, notifying applications"); NativeNfcTag nativeTag = (NativeNfcTag) msg.obj; if (nativeTag.connect()) { if (nativeTag.checkNdef()) { byte[] buff = nativeTag.read(); if (buff != null) { NdefMessage[] msgNdef = new NdefMessage[1]; try { msgNdef[0] = new NdefMessage(buff); NdefTag tag = new NdefTag(nativeTag.getUid(), TagTarget.internalTypeToRawTargets(nativeTag.getType()), null, null, nativeTag.getHandle(), TagTarget.internalTypeToNdefTargets(nativeTag.getType()), new NdefMessage[][] {msgNdef}); Intent intent = buildNdefTagIntent(tag); Log.d(TAG, "NDEF tag found, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); registerTagObject(nativeTag); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found, disconnecting"); nativeTag.asyncDisconnect(); } } catch (FormatException e) { Log.w(TAG, "Unable to create NDEF message object (tag empty or not well formated)"); nativeTag.asyncDisconnect(); } } else { Log.w(TAG, "Unable to read NDEF message (tag empty or not well formated)"); nativeTag.asyncDisconnect(); } } else { Intent intent = new Intent(); Tag tag = new Tag(nativeTag.getUid(), false, TagTarget.internalTypeToRawTargets(nativeTag.getType()), null, null, nativeTag.getHandle()); intent.setAction(NfcAdapter.ACTION_TAG_DISCOVERED); intent.putExtra(NfcAdapter.EXTRA_TAG, tag); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Log.d(TAG, "Non-NDEF tag found, starting corresponding activity"); Log.d(TAG, tag.toString()); try { mContext.startActivity(intent); registerTagObject(nativeTag); } catch (ActivityNotFoundException e) { Log.w(TAG, "No activity found, disconnecting"); nativeTag.asyncDisconnect(); } } } else { Log.w(TAG, "Failed to connect to tag"); nativeTag.asyncDisconnect(); } break; case MSG_CARD_EMULATION: Log.d(TAG, "Card Emulation message"); byte[] aid = (byte[]) msg.obj; /* Send broadcast ordered */ Intent TransactionIntent = new Intent(); TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED); TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid); Log.d(TAG, "Broadcasting Card Emulation event"); mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM); break; case MSG_LLCP_LINK_ACTIVATION: NativeP2pDevice device = (NativeP2pDevice) msg.obj; Log.d(TAG, "LLCP Activation message"); if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) { if (device.doConnect()) { /* Check Llcp compliancy */ if (mManager.doCheckLlcp()) { /* Activate Llcp Link */ if (mManager.doActivateLlcp()) { Log.d(TAG, "Initiator Activate LLCP OK"); /* Broadcast Intent Link LLCP activated */ Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent .setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION); LlcpLinkIntent.putExtra( mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA, NfcAdapter.LLCP_LINK_STATE_ACTIVATED); Log.d(TAG, "Broadcasting internal LLCP activation"); mContext.sendBroadcast(LlcpLinkIntent); } } else { device.doDisconnect(); } } } else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) { /* Check Llcp compliancy */ if (mManager.doCheckLlcp()) { /* Activate Llcp Link */ if (mManager.doActivateLlcp()) { Log.d(TAG, "Target Activate LLCP OK"); /* Broadcast Intent Link LLCP activated */ Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent .setAction(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_ACTION); LlcpLinkIntent.putExtra(mManager.INTERNAL_LLCP_LINK_STATE_CHANGED_EXTRA, NfcAdapter.LLCP_LINK_STATE_ACTIVATED); Log.d(TAG, "Broadcasting internal LLCP activation"); mContext.sendBroadcast(LlcpLinkIntent); } } } break; case MSG_LLCP_LINK_DEACTIVATED: /* Broadcast Intent Link LLCP activated */ Log.d(TAG, "LLCP Link Deactivated message"); Intent LlcpLinkIntent = new Intent(); LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED); LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED, NfcAdapter.LLCP_LINK_STATE_DEACTIVATED); Log.d(TAG, "Broadcasting LLCP deactivation"); mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM); break; case MSG_TARGET_DESELECTED: /* Broadcast Intent Target Deselected */ Log.d(TAG, "Target Deselected"); Intent TargetDeselectedIntent = new Intent(); TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION); Log.d(TAG, "Broadcasting Intent"); mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM); break; case MSG_SHOW_MY_TAG_ICON: { StatusBarManager sb = (StatusBarManager) getSystemService( Context.STATUS_BAR_SERVICE); sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0); break; } case MSG_HIDE_MY_TAG_ICON: { StatusBarManager sb = (StatusBarManager) getSystemService( Context.STATUS_BAR_SERVICE); sb.removeIcon("nfc"); break; } default: Log.e(TAG, "Unknown message received"); break; } }
diff --git a/combat/Test.java b/combat/Test.java index 863d40d..f9376ee 100644 --- a/combat/Test.java +++ b/combat/Test.java @@ -1,46 +1,46 @@ package combat; //Source file: /home/stu2/s22/DevB/classes/KeyDialog.java /** * @author DevC * @version $Id: Test.java,v 1.2 2012/04/08 03:50:18 DevA Exp $ * * KeyDialog allows users the option to map key commands to their liking * * Revision History: * $Log: Test.java,v $ * Revision 1.2 2012/04/08 03:50:18 DevA * Cleaned up the code to run with Java 1.6: removed unused imports, * fixed some UI focus issues (introduced by new focus "features" in Java since * our original implementation), and made the CommandInterpreter not a Singleton * * Revision 1.1 2000/05/09 14:05:46 DevC * Initial revision * * * * */ import javax.swing.*; public class Test { /** * Constructor * creates this dialog * * @param JFrame the frame of the game (which I am part of) */ public static void main( String[] argv ) { JFrame aframe = new JFrame(); - KeyDialog testd = new KeyDialog( aframe, new PlayerManager(0, null, null, null, null), new PlayerManager(0, null, null, null, null) ); + KeyDialog testd = new KeyDialog( aframe, new CommandInterpreter(new KeyBinding(), new KeyBinding())); aframe.setVisible(true); testd.setVisible(true); } }
true
true
public static void main( String[] argv ) { JFrame aframe = new JFrame(); KeyDialog testd = new KeyDialog( aframe, new PlayerManager(0, null, null, null, null), new PlayerManager(0, null, null, null, null) ); aframe.setVisible(true); testd.setVisible(true); }
public static void main( String[] argv ) { JFrame aframe = new JFrame(); KeyDialog testd = new KeyDialog( aframe, new CommandInterpreter(new KeyBinding(), new KeyBinding())); aframe.setVisible(true); testd.setVisible(true); }
diff --git a/chapter1/file-copy/src/main/java/camelinaction/FileCopier.java b/chapter1/file-copy/src/main/java/camelinaction/FileCopier.java index d8ea7c1..1822ced 100644 --- a/chapter1/file-copy/src/main/java/camelinaction/FileCopier.java +++ b/chapter1/file-copy/src/main/java/camelinaction/FileCopier.java @@ -1,56 +1,58 @@ /** * 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 camelinaction; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class FileCopier { public static void main(String args[]) throws Exception { File inboxDirectory = new File("data/inbox"); File outboxDirectory = new File("data/outbox"); outboxDirectory.mkdir(); File[] files = inboxDirectory.listFiles(); for (File source : files) { - File dest = new File( - outboxDirectory.getPath() - + File.separator - + source.getName()); - copyFile(source, dest); + if (source.isFile()) { + File dest = new File( + outboxDirectory.getPath() + + File.separator + + source.getName()); + copyFile(source, dest); + } } } private static void copyFile(File source, File dest) throws IOException { OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[(int) source.length()]; FileInputStream in = new FileInputStream(source); in.read(buffer); try { out.write(buffer); } finally { out.close(); in.close(); } } }
true
true
public static void main(String args[]) throws Exception { File inboxDirectory = new File("data/inbox"); File outboxDirectory = new File("data/outbox"); outboxDirectory.mkdir(); File[] files = inboxDirectory.listFiles(); for (File source : files) { File dest = new File( outboxDirectory.getPath() + File.separator + source.getName()); copyFile(source, dest); } }
public static void main(String args[]) throws Exception { File inboxDirectory = new File("data/inbox"); File outboxDirectory = new File("data/outbox"); outboxDirectory.mkdir(); File[] files = inboxDirectory.listFiles(); for (File source : files) { if (source.isFile()) { File dest = new File( outboxDirectory.getPath() + File.separator + source.getName()); copyFile(source, dest); } } }
diff --git a/src/Core/org/objectweb/proactive/ext/util/StubGenerator.java b/src/Core/org/objectweb/proactive/ext/util/StubGenerator.java index f8d0c2f8a..de0c1966b 100644 --- a/src/Core/org/objectweb/proactive/ext/util/StubGenerator.java +++ b/src/Core/org/objectweb/proactive/ext/util/StubGenerator.java @@ -1,283 +1,283 @@ /* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://www.inria.fr/oasis/ProActive/contacts.html * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.ext.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import javassist.ClassClassPath; import javassist.ClassPool; import org.objectweb.proactive.core.mop.JavassistByteCodeStubBuilder; import org.objectweb.proactive.core.mop.MOPClassLoader; import org.objectweb.proactive.core.mop.Utils; public class StubGenerator { public static void main(String[] args) { StubGenerator sg = new StubGenerator(args); sg.run(); } private File srcDir; private String pkg = ""; private File destDir; private String cl; private boolean verbose = false; public StubGenerator(String[] args) { ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(this.getClass())); int index = 0; while (index < args.length) { if (args[index].equals("-srcDir")) { srcDir = new File(args[index + 1]); index += 2; } else if (args[index].equals("-pkg")) { pkg = args[index + 1]; index += 2; } else if (args[index].equals("-destDir")) { destDir = new File(args[index + 1]); index += 2; } else if (args[index].equals("-class")) { cl = args[index + 1]; index += 2; } else if (args[index].equals("-verbose")) { verbose = true; index++; } else { usage(); System.exit(1); } } } public void usage() { System.out.println("Usage:"); System.out.println("\t-srcDir directory where to find source classes"); System.out.println("\t-destDir directory where to put generated stubs"); System.out.println("\t-pkg package name"); System.out.println("\t-class generate only a stub for this class"); System.out.println("\t-verbose enable verbose mode"); System.out.println(""); } public void logAndExit(String str) { System.err.println(str); System.exit(2); } public void run() { if (srcDir == null) { logAndExit("srcDir attribute is not set"); } if (!srcDir.exists()) { logAndExit("Invalid srcDir attribute: " + srcDir.toString() + " does not exist"); } if (!srcDir.isDirectory()) { logAndExit("Invalid srcDir attribute: " + srcDir.toString() + " is not a directory"); } if (pkg == null) { logAndExit("pkg attribute is not set"); } File pkgDir = new File(srcDir.toString() + File.separator + pkg.replace('.', File.separatorChar)); if (!pkgDir.exists()) { logAndExit("Invalid pkg attribute: " + pkgDir.toString() + " does not exist"); } if (destDir == null) { destDir = srcDir; } if (!destDir.isDirectory()) { logAndExit("Invalid dest attribute: " + destDir.toString() + " is not a directory"); } if (!destDir.isDirectory()) { logAndExit("Invalid src attribute: " + destDir.toString() + " is not a directory"); } List<File> files = new ArrayList<File>(); if (cl == null) { // Find all the classes in this package files.addAll(exploreDirectory(pkgDir)); } else { File file = new File(pkgDir + File.separator + cl + ".class"); if (!file.exists() || !file.isFile()) { logAndExit("Invalid pkg or class attribute: " + file.toString() + " does not exist"); } files.add(file); } PrintStream stderr = System.err; PrintStream mute = new PrintStream(new MuteOutputStream()); if (!verbose) { System.setErr(mute); } // ClassPool.releaseUnmodifiedClassFile = true; for (File file : files) { String str = file.toString().replaceFirst(srcDir.toString(), ""); try { if (!verbose) { System.setErr(mute); } StubGenerator.generateClass(str, destDir.toString() + File.separator); } catch (Throwable e) { - System.out.println("FAILED " + str); + System.out.println("Stub generation failed: " + str); } } if (!verbose) { System.setErr(stderr); } } private List<File> exploreDirectory(File dir) { List<File> files = new ArrayList<File>(); for (File file : dir.listFiles()) { if (file.isDirectory()) { files.addAll(exploreDirectory(file)); } if (!file.toString().endsWith(".class")) { continue; } files.add(file); } return files; } /** * @param arg * @param directoryName */ public static void generateClass(String arg, String directoryName) { String className = processClassName(arg); String fileName = null; String stubClassName; try { // Generates the bytecode for the class // ASM is now the default bytecode manipulator byte[] data; // if (MOPClassLoader.BYTE_CODE_MANIPULATOR.equals("ASM")) { // ASMBytecodeStubBuilder bsb = new // ASMBytecodeStubBuilder(className); // data = bsb.create(); // stubClassName = Utils.convertClassNameToStubClassName(className); // } else if (MOPClassLoader.BYTE_CODE_MANIPULATOR.equals("javassist")) { data = JavassistByteCodeStubBuilder.create(className, null); stubClassName = Utils.convertClassNameToStubClassName(className, null); } else { // that shouldn't happen, unless someone manually sets the // BYTE_CODE_MANIPULATOR static variable System.err.println( "byteCodeManipulator argument is optionnal. If specified, it can only be set to javassist (ASM is no longer supported)."); System.err.println( "Any other setting will result in the use of javassist, the default bytecode manipulator framework"); stubClassName = null; data = null; } char sep = File.separatorChar; fileName = directoryName + stubClassName.replace('.', sep) + ".class"; // And writes it to a file new File(fileName.substring(0, fileName.lastIndexOf(sep))).mkdirs(); // String fileName = directoryName + System.getProperty // ("file.separator") + File f = new File(fileName); FileOutputStream fos = new FileOutputStream(f); fos.write(data); fos.flush(); fos.close(); } catch (Exception e) { System.err.println("Cannot write file " + fileName); System.err.println("Reason is " + e); } } /** * Turn a file name into a class name if necessary. Remove the ending .class * and change all the '/' into '.' * * @param name */ protected static String processClassName(String name) { int i = name.indexOf(".class"); String tmp = name; if (i < 0) { return name; } tmp = name.substring(0, i); String tmp2 = tmp.replace(File.separatorChar, '.'); if (tmp2.indexOf('.') == 0) { return tmp2.substring(1); } return tmp2; } public class MuteOutputStream extends OutputStream { @Override public void write(int b) throws IOException { // Please shut up ! } } }
true
true
public void run() { if (srcDir == null) { logAndExit("srcDir attribute is not set"); } if (!srcDir.exists()) { logAndExit("Invalid srcDir attribute: " + srcDir.toString() + " does not exist"); } if (!srcDir.isDirectory()) { logAndExit("Invalid srcDir attribute: " + srcDir.toString() + " is not a directory"); } if (pkg == null) { logAndExit("pkg attribute is not set"); } File pkgDir = new File(srcDir.toString() + File.separator + pkg.replace('.', File.separatorChar)); if (!pkgDir.exists()) { logAndExit("Invalid pkg attribute: " + pkgDir.toString() + " does not exist"); } if (destDir == null) { destDir = srcDir; } if (!destDir.isDirectory()) { logAndExit("Invalid dest attribute: " + destDir.toString() + " is not a directory"); } if (!destDir.isDirectory()) { logAndExit("Invalid src attribute: " + destDir.toString() + " is not a directory"); } List<File> files = new ArrayList<File>(); if (cl == null) { // Find all the classes in this package files.addAll(exploreDirectory(pkgDir)); } else { File file = new File(pkgDir + File.separator + cl + ".class"); if (!file.exists() || !file.isFile()) { logAndExit("Invalid pkg or class attribute: " + file.toString() + " does not exist"); } files.add(file); } PrintStream stderr = System.err; PrintStream mute = new PrintStream(new MuteOutputStream()); if (!verbose) { System.setErr(mute); } // ClassPool.releaseUnmodifiedClassFile = true; for (File file : files) { String str = file.toString().replaceFirst(srcDir.toString(), ""); try { if (!verbose) { System.setErr(mute); } StubGenerator.generateClass(str, destDir.toString() + File.separator); } catch (Throwable e) { System.out.println("FAILED " + str); } } if (!verbose) { System.setErr(stderr); } }
public void run() { if (srcDir == null) { logAndExit("srcDir attribute is not set"); } if (!srcDir.exists()) { logAndExit("Invalid srcDir attribute: " + srcDir.toString() + " does not exist"); } if (!srcDir.isDirectory()) { logAndExit("Invalid srcDir attribute: " + srcDir.toString() + " is not a directory"); } if (pkg == null) { logAndExit("pkg attribute is not set"); } File pkgDir = new File(srcDir.toString() + File.separator + pkg.replace('.', File.separatorChar)); if (!pkgDir.exists()) { logAndExit("Invalid pkg attribute: " + pkgDir.toString() + " does not exist"); } if (destDir == null) { destDir = srcDir; } if (!destDir.isDirectory()) { logAndExit("Invalid dest attribute: " + destDir.toString() + " is not a directory"); } if (!destDir.isDirectory()) { logAndExit("Invalid src attribute: " + destDir.toString() + " is not a directory"); } List<File> files = new ArrayList<File>(); if (cl == null) { // Find all the classes in this package files.addAll(exploreDirectory(pkgDir)); } else { File file = new File(pkgDir + File.separator + cl + ".class"); if (!file.exists() || !file.isFile()) { logAndExit("Invalid pkg or class attribute: " + file.toString() + " does not exist"); } files.add(file); } PrintStream stderr = System.err; PrintStream mute = new PrintStream(new MuteOutputStream()); if (!verbose) { System.setErr(mute); } // ClassPool.releaseUnmodifiedClassFile = true; for (File file : files) { String str = file.toString().replaceFirst(srcDir.toString(), ""); try { if (!verbose) { System.setErr(mute); } StubGenerator.generateClass(str, destDir.toString() + File.separator); } catch (Throwable e) { System.out.println("Stub generation failed: " + str); } } if (!verbose) { System.setErr(stderr); } }
diff --git a/java/modules/transports/core/vfs/src/main/java/org/apache/synapse/transport/vfs/VFSUtils.java b/java/modules/transports/core/vfs/src/main/java/org/apache/synapse/transport/vfs/VFSUtils.java index d605e8e5c..55b3fdda1 100644 --- a/java/modules/transports/core/vfs/src/main/java/org/apache/synapse/transport/vfs/VFSUtils.java +++ b/java/modules/transports/core/vfs/src/main/java/org/apache/synapse/transport/vfs/VFSUtils.java @@ -1,186 +1,191 @@ /* * 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.synapse.transport.vfs; import org.apache.axis2.context.MessageContext; import org.apache.axis2.description.Parameter; import org.apache.axis2.transport.base.BaseUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.vfs.FileContent; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemException; import org.apache.commons.vfs.FileSystemManager; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Map; import java.util.Random; public class VFSUtils extends BaseUtils { private static final Log log = LogFactory.getLog(VFSUtils.class); /** * Get a String property from FileContent message * * @param message the File message * @param property property name * @return property value */ public static String getProperty(FileContent message, String property) { try { Object o = message.getAttributes().get(property); if (o instanceof String) { return (String) o; } } catch (FileSystemException ignored) {} return null; } public static String getFileName(MessageContext msgCtx, VFSOutTransportInfo vfsOutInfo) { String fileName = null; // first preference to a custom filename set on the current message context Map transportHeaders = (Map) msgCtx.getProperty(MessageContext.TRANSPORT_HEADERS); if (transportHeaders != null) { fileName = (String) transportHeaders.get(VFSConstants.REPLY_FILE_NAME); } // if not, does the service (in its service.xml) specify one? if (fileName == null) { Parameter param = msgCtx.getAxisService().getParameter(VFSConstants.REPLY_FILE_NAME); if (param != null) { fileName = (String) param.getValue(); } } // next check if the OutTransportInfo specifies one if (fileName == null) { fileName = vfsOutInfo.getOutFileName(); } // if none works.. use default if (fileName == null) { fileName = VFSConstants.DEFAULT_RESPONSE_FILE; } return fileName; } /** * Acquires a file item lock before processing the item, guaranteing that the file is not * processed while it is being uploaded and/or the item is not processed by two listeners * * @param fsManager used to resolve the processing file * @param fo representing the processign file item * @return boolean true if the lock has been acquired or false if not */ public static boolean acquireLock(FileSystemManager fsManager, FileObject fo) { // generate a random lock value to ensure that there are no two parties // processing the same file Random random = new Random(); byte[] lockValue = String.valueOf(random.nextLong()).getBytes(); try { // check whether there is an existing lock for this item, if so it is assumed // to be processed by an another listener (downloading) or a sender (uploading) // lock file is derived by attaching the ".lock" second extension to the file name - FileObject lockObject = fsManager.resolveFile(fo.getURL().toString() + ".lock"); + String fullPath = fo.getURL().toString(); + int pos = fullPath.indexOf("?"); + if (pos != -1) { + fullPath = fullPath.substring(0, pos); + } + FileObject lockObject = fsManager.resolveFile(fullPath + ".lock"); if (lockObject.exists()) { log.debug("There seems to be an external lock, aborting the processing of the file " + fo.getName() + ". This could possibly be due to some other party already " + "processing this file or the file is still being uploaded"); } else { // write a lock file before starting of the processing, to ensure that the // item is not processed by any other parties lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); stream.close(); } catch (IOException e) { lockObject.delete(); log.debug("Couldn't create the lock file before processing the file " - + fo.getName(), e); + + fullPath, e); return false; } finally { lockObject.close(); } // check whether the lock is in place and is it me who holds the lock. This is // required because it is possible to write the lock file symultaniously by // two processing parties. It checks whether the lock file content is the same // as the written random lock value. // NOTE: this may not be optimal but is sub optimal FileObject verifyingLockObject = fsManager.resolveFile( - fo.getURL().toString() + ".lock"); + fullPath + ".lock"); if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) { return true; } } } catch (FileSystemException fse) { log.debug("Cannot get the lock for the file : " + fo.getName() + " before processing"); } return false; } /** * Release a file item lock acquired either by the VFS listener or a sender * * @param fsManager which is used to resolve the processed file * @param fo representing the processed file */ public static void releaseLock(FileSystemManager fsManager, FileObject fo) { try { FileObject lockObject = fsManager.resolveFile(fo.getURL().toString() + ".lock"); if (lockObject.exists()) { lockObject.delete(); } } catch (FileSystemException e) { log.error("Couldn't release the lock for the file : " + fo.getName() + " after processing"); } } private static boolean verifyLock(byte[] lockValue, FileObject lockObject) { try { InputStream is = lockObject.getContent().getInputStream(); byte[] val = new byte[lockValue.length]; // noinspection ResultOfMethodCallIgnored is.read(val); if (Arrays.equals(lockValue, val) && is.read() == -1) { return true; } else { log.debug("The lock has been acquired by an another party"); } } catch (FileSystemException e) { log.debug("Couldn't verify the lock", e); return false; } catch (IOException e) { log.debug("Couldn't verify the lock", e); return false; } return false; } }
false
true
public static boolean acquireLock(FileSystemManager fsManager, FileObject fo) { // generate a random lock value to ensure that there are no two parties // processing the same file Random random = new Random(); byte[] lockValue = String.valueOf(random.nextLong()).getBytes(); try { // check whether there is an existing lock for this item, if so it is assumed // to be processed by an another listener (downloading) or a sender (uploading) // lock file is derived by attaching the ".lock" second extension to the file name FileObject lockObject = fsManager.resolveFile(fo.getURL().toString() + ".lock"); if (lockObject.exists()) { log.debug("There seems to be an external lock, aborting the processing of the file " + fo.getName() + ". This could possibly be due to some other party already " + "processing this file or the file is still being uploaded"); } else { // write a lock file before starting of the processing, to ensure that the // item is not processed by any other parties lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); stream.close(); } catch (IOException e) { lockObject.delete(); log.debug("Couldn't create the lock file before processing the file " + fo.getName(), e); return false; } finally { lockObject.close(); } // check whether the lock is in place and is it me who holds the lock. This is // required because it is possible to write the lock file symultaniously by // two processing parties. It checks whether the lock file content is the same // as the written random lock value. // NOTE: this may not be optimal but is sub optimal FileObject verifyingLockObject = fsManager.resolveFile( fo.getURL().toString() + ".lock"); if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) { return true; } } } catch (FileSystemException fse) { log.debug("Cannot get the lock for the file : " + fo.getName() + " before processing"); } return false; }
public static boolean acquireLock(FileSystemManager fsManager, FileObject fo) { // generate a random lock value to ensure that there are no two parties // processing the same file Random random = new Random(); byte[] lockValue = String.valueOf(random.nextLong()).getBytes(); try { // check whether there is an existing lock for this item, if so it is assumed // to be processed by an another listener (downloading) or a sender (uploading) // lock file is derived by attaching the ".lock" second extension to the file name String fullPath = fo.getURL().toString(); int pos = fullPath.indexOf("?"); if (pos != -1) { fullPath = fullPath.substring(0, pos); } FileObject lockObject = fsManager.resolveFile(fullPath + ".lock"); if (lockObject.exists()) { log.debug("There seems to be an external lock, aborting the processing of the file " + fo.getName() + ". This could possibly be due to some other party already " + "processing this file or the file is still being uploaded"); } else { // write a lock file before starting of the processing, to ensure that the // item is not processed by any other parties lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); stream.close(); } catch (IOException e) { lockObject.delete(); log.debug("Couldn't create the lock file before processing the file " + fullPath, e); return false; } finally { lockObject.close(); } // check whether the lock is in place and is it me who holds the lock. This is // required because it is possible to write the lock file symultaniously by // two processing parties. It checks whether the lock file content is the same // as the written random lock value. // NOTE: this may not be optimal but is sub optimal FileObject verifyingLockObject = fsManager.resolveFile( fullPath + ".lock"); if (verifyingLockObject.exists() && verifyLock(lockValue, verifyingLockObject)) { return true; } } } catch (FileSystemException fse) { log.debug("Cannot get the lock for the file : " + fo.getName() + " before processing"); } return false; }
diff --git a/management/src/main/java/aic12/project3/service/loadBalancing/BalancingAlgorithmKeepQueueConstantImpl_Thread.java b/management/src/main/java/aic12/project3/service/loadBalancing/BalancingAlgorithmKeepQueueConstantImpl_Thread.java index 66555fe..f9603d7 100644 --- a/management/src/main/java/aic12/project3/service/loadBalancing/BalancingAlgorithmKeepQueueConstantImpl_Thread.java +++ b/management/src/main/java/aic12/project3/service/loadBalancing/BalancingAlgorithmKeepQueueConstantImpl_Thread.java @@ -1,133 +1,133 @@ package aic12.project3.service.loadBalancing; import org.apache.log4j.Logger; import aic12.project3.service.requestManagement.RequestQueueReady; import aic12.project3.service.statistics.Statistics; import aic12.project3.service.util.FifoWithAverageCalculation; import aic12.project3.service.util.LoggerLevel; import aic12.project3.service.util.ManagementLogger; public class BalancingAlgorithmKeepQueueConstantImpl_Thread extends Thread { private boolean continueRunning = true; private Statistics statistics; private Logger log = Logger.getLogger(BalancingAlgorithmKeepQueueConstantImpl_Thread.class); private RequestQueueReady requestQReady; private IHighLevelNodeManager highLvlNodeMan; private ManagementLogger managementLogger; private String clazz = this.getClass().getName(); private long updateInterval = 5000; private FifoWithAverageCalculation fifo = new FifoWithAverageCalculation(100); private LoadBalancerTime loadBalancer; public BalancingAlgorithmKeepQueueConstantImpl_Thread( Statistics statistics, RequestQueueReady requestQReady, IHighLevelNodeManager highLvlNodeMan, ManagementLogger managementLogger, LoadBalancerTime loadBalancer) { super(); this.statistics = statistics; this.requestQReady = requestQReady; this.highLvlNodeMan = highLvlNodeMan; this.managementLogger = managementLogger; this.loadBalancer = loadBalancer; } @Override public void run() { // long _effectiveUpdateInterval = updateInterval; while(continueRunning ) { // long _updateStart = System.currentTimeMillis(); log.info("periodic balancing update RUN"); statistics.calculateStatistics(); log .info(statistics); int runningNodes = highLvlNodeMan.getRunningNodesCount(); int nodeStartupTime = highLvlNodeMan.getNodeStartupTime(); int nodeShutdownTime = highLvlNodeMan.getNodeShutdownTime(); double avgTweetProcessingDuration = statistics.getStatistics().getAverageTotalDurationPerTweet(); // long tweetsPerBalanceUpdateProcessedPerNode = (long) (_effectiveUpdateInterval / avgTweetProcessingDuration); // long tweetsPerBalanceUpdateProcessedTotal = tweetsPerBalanceUpdateProcessedPerNode * runningNodes; long numTweetsInQ = requestQReady.getNumberOfTweetsInQueue(); int desiredNodeCount = 0; if(numTweetsInQ != 0) { long expectedDuration = -1; if(runningNodes == 0) { expectedDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, 1); } else { expectedDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes); } fifo.add(expectedDuration); log.info("Status now:\n#tweetsInQ: " + numTweetsInQ + "\nrunningNodes: " + runningNodes + "\nnodeStartupTime: " + nodeStartupTime + "\nexpectedDuration: " + expectedDuration); long avgOverTime = fifo.calculateAverage(); long queueIncreaseToAvg = expectedDuration - avgOverTime; if(queueIncreaseToAvg > 0) { int nodesToAdd = 0; long newQDuration = -1; do { newQDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes + nodesToAdd) + nodeStartupTime; nodesToAdd++; log.info("nodesToAdd: " + nodesToAdd); } while(newQDuration > fifo.calculateAverage()); nodesToAdd--; // last run of loop was too much; desiredNodeCount = runningNodes + nodesToAdd; log.info("nodes to ADD: " + nodesToAdd); } else if(queueIncreaseToAvg < 0) { int nodesToStop = 0; long newQDuration = -1; do { - newQDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes - nodesToStop) + nodeShutdownTime; + newQDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes - nodesToStop); nodesToStop++; log.info("nodesToStop: " + nodesToStop); } while(newQDuration < fifo.calculateAverage()); nodesToStop--; // last run of loop was too much; desiredNodeCount = runningNodes - nodesToStop; log.info("nodes to STOP: " + nodesToStop); } if(desiredNodeCount < 1) { desiredNodeCount = 1; // we have work to do, can't stop everything now } } else { desiredNodeCount = 0; // no tweets in Queue } managementLogger.log(clazz, LoggerLevel.INFO, "desiredNodes calculated: * " + desiredNodeCount + " * setting in nodeManager"); log.info("expectedDuration: " + calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, desiredNodeCount)); highLvlNodeMan.runDesiredNumberOfNodes(desiredNodeCount, loadBalancer); log.info("periodic balancing update RUN ENDED - sleeping now"); try { Thread.sleep(updateInterval); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // _effectiveUpdateInterval = _updateStart - System.currentTimeMillis(); } } private long calculateExpDuration(long numTweetsInQ, double avgTweetProcessingDuration, int nodes) { if(nodes == 0) { return Long.MAX_VALUE; } return (long) (numTweetsInQ * avgTweetProcessingDuration) / nodes; } public void stopRunning() { continueRunning = false; } }
true
true
public void run() { // long _effectiveUpdateInterval = updateInterval; while(continueRunning ) { // long _updateStart = System.currentTimeMillis(); log.info("periodic balancing update RUN"); statistics.calculateStatistics(); log .info(statistics); int runningNodes = highLvlNodeMan.getRunningNodesCount(); int nodeStartupTime = highLvlNodeMan.getNodeStartupTime(); int nodeShutdownTime = highLvlNodeMan.getNodeShutdownTime(); double avgTweetProcessingDuration = statistics.getStatistics().getAverageTotalDurationPerTweet(); // long tweetsPerBalanceUpdateProcessedPerNode = (long) (_effectiveUpdateInterval / avgTweetProcessingDuration); // long tweetsPerBalanceUpdateProcessedTotal = tweetsPerBalanceUpdateProcessedPerNode * runningNodes; long numTweetsInQ = requestQReady.getNumberOfTweetsInQueue(); int desiredNodeCount = 0; if(numTweetsInQ != 0) { long expectedDuration = -1; if(runningNodes == 0) { expectedDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, 1); } else { expectedDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes); } fifo.add(expectedDuration); log.info("Status now:\n#tweetsInQ: " + numTweetsInQ + "\nrunningNodes: " + runningNodes + "\nnodeStartupTime: " + nodeStartupTime + "\nexpectedDuration: " + expectedDuration); long avgOverTime = fifo.calculateAverage(); long queueIncreaseToAvg = expectedDuration - avgOverTime; if(queueIncreaseToAvg > 0) { int nodesToAdd = 0; long newQDuration = -1; do { newQDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes + nodesToAdd) + nodeStartupTime; nodesToAdd++; log.info("nodesToAdd: " + nodesToAdd); } while(newQDuration > fifo.calculateAverage()); nodesToAdd--; // last run of loop was too much; desiredNodeCount = runningNodes + nodesToAdd; log.info("nodes to ADD: " + nodesToAdd); } else if(queueIncreaseToAvg < 0) { int nodesToStop = 0; long newQDuration = -1; do { newQDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes - nodesToStop) + nodeShutdownTime; nodesToStop++; log.info("nodesToStop: " + nodesToStop); } while(newQDuration < fifo.calculateAverage()); nodesToStop--; // last run of loop was too much; desiredNodeCount = runningNodes - nodesToStop; log.info("nodes to STOP: " + nodesToStop); } if(desiredNodeCount < 1) { desiredNodeCount = 1; // we have work to do, can't stop everything now } } else { desiredNodeCount = 0; // no tweets in Queue } managementLogger.log(clazz, LoggerLevel.INFO, "desiredNodes calculated: * " + desiredNodeCount + " * setting in nodeManager"); log.info("expectedDuration: " + calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, desiredNodeCount)); highLvlNodeMan.runDesiredNumberOfNodes(desiredNodeCount, loadBalancer); log.info("periodic balancing update RUN ENDED - sleeping now"); try { Thread.sleep(updateInterval); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // _effectiveUpdateInterval = _updateStart - System.currentTimeMillis(); } }
public void run() { // long _effectiveUpdateInterval = updateInterval; while(continueRunning ) { // long _updateStart = System.currentTimeMillis(); log.info("periodic balancing update RUN"); statistics.calculateStatistics(); log .info(statistics); int runningNodes = highLvlNodeMan.getRunningNodesCount(); int nodeStartupTime = highLvlNodeMan.getNodeStartupTime(); int nodeShutdownTime = highLvlNodeMan.getNodeShutdownTime(); double avgTweetProcessingDuration = statistics.getStatistics().getAverageTotalDurationPerTweet(); // long tweetsPerBalanceUpdateProcessedPerNode = (long) (_effectiveUpdateInterval / avgTweetProcessingDuration); // long tweetsPerBalanceUpdateProcessedTotal = tweetsPerBalanceUpdateProcessedPerNode * runningNodes; long numTweetsInQ = requestQReady.getNumberOfTweetsInQueue(); int desiredNodeCount = 0; if(numTweetsInQ != 0) { long expectedDuration = -1; if(runningNodes == 0) { expectedDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, 1); } else { expectedDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes); } fifo.add(expectedDuration); log.info("Status now:\n#tweetsInQ: " + numTweetsInQ + "\nrunningNodes: " + runningNodes + "\nnodeStartupTime: " + nodeStartupTime + "\nexpectedDuration: " + expectedDuration); long avgOverTime = fifo.calculateAverage(); long queueIncreaseToAvg = expectedDuration - avgOverTime; if(queueIncreaseToAvg > 0) { int nodesToAdd = 0; long newQDuration = -1; do { newQDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes + nodesToAdd) + nodeStartupTime; nodesToAdd++; log.info("nodesToAdd: " + nodesToAdd); } while(newQDuration > fifo.calculateAverage()); nodesToAdd--; // last run of loop was too much; desiredNodeCount = runningNodes + nodesToAdd; log.info("nodes to ADD: " + nodesToAdd); } else if(queueIncreaseToAvg < 0) { int nodesToStop = 0; long newQDuration = -1; do { newQDuration = calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, runningNodes - nodesToStop); nodesToStop++; log.info("nodesToStop: " + nodesToStop); } while(newQDuration < fifo.calculateAverage()); nodesToStop--; // last run of loop was too much; desiredNodeCount = runningNodes - nodesToStop; log.info("nodes to STOP: " + nodesToStop); } if(desiredNodeCount < 1) { desiredNodeCount = 1; // we have work to do, can't stop everything now } } else { desiredNodeCount = 0; // no tweets in Queue } managementLogger.log(clazz, LoggerLevel.INFO, "desiredNodes calculated: * " + desiredNodeCount + " * setting in nodeManager"); log.info("expectedDuration: " + calculateExpDuration(numTweetsInQ, avgTweetProcessingDuration, desiredNodeCount)); highLvlNodeMan.runDesiredNumberOfNodes(desiredNodeCount, loadBalancer); log.info("periodic balancing update RUN ENDED - sleeping now"); try { Thread.sleep(updateInterval); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // _effectiveUpdateInterval = _updateStart - System.currentTimeMillis(); } }
diff --git a/source/client/main/edu/wustl/cab2b/client/ui/mainframe/GlobalNavigationPanel.java b/source/client/main/edu/wustl/cab2b/client/ui/mainframe/GlobalNavigationPanel.java index 5b672474..2e045678 100644 --- a/source/client/main/edu/wustl/cab2b/client/ui/mainframe/GlobalNavigationPanel.java +++ b/source/client/main/edu/wustl/cab2b/client/ui/mainframe/GlobalNavigationPanel.java @@ -1,352 +1,352 @@ package edu.wustl.cab2b.client.ui.mainframe; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.util.Date; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JEditorPane; import org.jdesktop.swingx.HorizontalLayout; import org.jdesktop.swingx.JXFrame; import org.jdesktop.swingx.JXPanel; import edu.wustl.cab2b.client.ui.MainSearchPanel; import edu.wustl.cab2b.client.ui.RiverLayout; import edu.wustl.cab2b.client.ui.WindowUtilities; import edu.wustl.cab2b.client.ui.controls.Cab2bButton; import edu.wustl.cab2b.client.ui.controls.Cab2bHyperlink; import edu.wustl.cab2b.client.ui.controls.Cab2bLabel; import edu.wustl.cab2b.client.ui.controls.Cab2bPanel; import edu.wustl.cab2b.client.ui.controls.Cab2bStandardFonts; import edu.wustl.cab2b.client.ui.util.CommonUtils; import edu.wustl.common.util.logger.Logger; /** * This is a top level navigation panel, which is placed at the * top of the <code>MainFrame</code>. * * @author chetan_bh */ public class GlobalNavigationPanel extends Cab2bPanel implements ActionListener { /** * Background color of the panel. */ Color bgColor = new Color(58, 95, 205); //new Color(120,120,220); //58;95;205 /** * Foreground color of the panel. */ Color fgColor = new Color(255, 255, 255); // Color.WHITE /** * Label for the title of the application. */ Cab2bLabel titleLabel; /** Panel holding the title label. */ JXPanel titlePanel; JXPanel middlePanel; JXPanel topMiddlePanel; JXPanel tabsPanel; MainFrame mainFrame; /** * Label to show details of the logged in user to the application. */ Cab2bLabel loggedInUserLabel; /** * Button text to show in the navigation panel. */ String[] tabs = { "Home", "Search Data", "Experiment" }; /** * Button text to show in the navigation panel. */ String[] tabsImages = { "resources/images/home_tab.gif", "resources/images/searchdata_tab.gif", "resources/images/experiment_tab.gif" }; /** * Buttons to show in the navigation panel. */ JButton[] tabButtons = new Cab2bButton[tabs.length]; public Color navigationButtonBgColorSelected = new Color(221, 221, 221); public Color navigationButtonBgColorUnSelected = new Color(168, 168, 168); /** * Top level panel to hold all sub panels. */ JXPanel parentPanel; /** * <code>MainFrame</code> reference. */ JXFrame frame; public static MainSearchPanel mainSearchPanel = null; public GlobalNavigationPanel(JXFrame frame, MainFrame mainFrame) { this.mainFrame = mainFrame; this.frame = frame; this.setBackground(bgColor); this.setLayout(new RiverLayout(0, 0)); this.setPreferredSize(new Dimension(1024, 75)); this.setMaximumSize(new Dimension(1024, 75)); this.setMinimumSize(new Dimension(1024, 75)); initGUIWithGB(); } private void initGUIWithGB() { /* to this panel add top panel and bottom panel */ Cab2bPanel topPanel = new Cab2bPanel(); topPanel.setBackground(bgColor); topPanel.setPreferredSize(new Dimension(1024, 70)); topPanel.setMinimumSize(new Dimension(1024, 70)); topPanel.setMaximumSize(new Dimension(1024, 70)); GridBagConstraints gbc = new GridBagConstraints(); topPanel.setLayout(new GridBagLayout()); // 1 component Icon logoIcon = new ImageIcon("resources/images/b2b_logo.gif"); titleLabel = new Cab2bLabel(logoIcon); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(titleLabel, gbc); //this.add(titleLabel); // 2 component JXPanel extraSpaceFillerPanel1 = new Cab2bPanel(); extraSpaceFillerPanel1.setBackground(bgColor); extraSpaceFillerPanel1.setPreferredSize(new Dimension(60, 70)); extraSpaceFillerPanel1.setMinimumSize(new Dimension(60, 70)); extraSpaceFillerPanel1.setMaximumSize(new Dimension(60, 70)); gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 2; gbc.weightx = 0.50; gbc.fill = GridBagConstraints.BOTH; topPanel.add(extraSpaceFillerPanel1, gbc); //this.add("hfill vfill", extraSpaceFillerPanel1); // 3rd component topMiddlePanel = new Cab2bPanel(); topMiddlePanel.setPreferredSize(new Dimension(300, 37)); topMiddlePanel.setMinimumSize(new Dimension(300, 37)); topMiddlePanel.setMaximumSize(new Dimension(300, 37)); topMiddlePanel.setBackground(bgColor); // 4th component tabsPanel = new Cab2bPanel(); tabsPanel.setPreferredSize(new Dimension(300, 33)); tabsPanel.setMinimumSize(new Dimension(300, 33)); tabsPanel.setMaximumSize(new Dimension(300, 33)); tabsPanel.setBackground(bgColor); tabsPanel.setLayout(new HorizontalLayout(10)); for (int i = 0; i < tabs.length; i++) { String tabText = tabs[i]; String tabImageFileLocation = tabsImages[i]; ImageIcon imageIcon = new ImageIcon(tabImageFileLocation); //tabButtons[i] = new Cab2bButton(imageIcon); //tabButtons[i].setActionCommand(tabText); tabButtons[i] = new Cab2bButton(tabText, true, Cab2bStandardFonts.ARIAL_BOLD_12); tabButtons[i].setBorder(null); if (i != 0) { tabButtons[i].setBackground(navigationButtonBgColorUnSelected); //new Color(168, 168, 168) } else { tabButtons[i].setBackground(navigationButtonBgColorSelected); //new Color(220,220,240) } tabButtons[i].addActionListener(this); tabsPanel.add(tabButtons[i]); } gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 3; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(topMiddlePanel, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 3; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(tabsPanel, gbc); // 5th component JXPanel extraSpaceFillerPanel2 = new Cab2bPanel(); extraSpaceFillerPanel2.setBackground(bgColor); gbc.gridx = 7; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 2; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 0.50; topPanel.add(extraSpaceFillerPanel2, gbc); //this.add("hfill vfill", extraSpaceFillerPanel2); // 6th component, which is a cab2b banner image. Icon bannerIcon = new ImageIcon("resources/images/b2b_banner.gif"); Cab2bLabel bannerLabel = new Cab2bLabel(bannerIcon); gbc.gridx = 8; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(bannerLabel, gbc); Date date = new Date(); - loggedInUserLabel = new Cab2bLabel("<html>Robert Lloyd <br>" + loggedInUserLabel = new Cab2bLabel("<html><b>Robert Lloyd</b><br>" + DateFormat.getDateInstance(DateFormat.LONG).format(date).toString() + "<br><br></html>"); Cab2bHyperlink logOutHyperLink = new Cab2bHyperlink(Color.GRAY, Color.WHITE); logOutHyperLink.setText("Logout"); logOutHyperLink.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Logger.out.info("Clicked on logOut Link"); } }); Cab2bHyperlink mySettingHyperlInk = new Cab2bHyperlink(Color.GRAY, Color.WHITE); mySettingHyperlInk.setText("MySettings"); mySettingHyperlInk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Logger.out.info("Clicked on My-Settings Link"); } }); loggedInUserLabel.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); loggedInUserLabel.setForeground(fgColor); loggedInUserLabel.setBackground(bgColor); Cab2bPanel linkPanel = new Cab2bPanel(); linkPanel.add(logOutHyperLink); linkPanel.add(mySettingHyperlInk); linkPanel.setOpaque(false); Dimension prefSize = loggedInUserLabel.getPreferredSize(); loggedInUserLabel.setMaximumSize(prefSize); loggedInUserLabel.setMinimumSize(prefSize); gbc.gridx = 10; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(loggedInUserLabel, gbc); //this.add("hfill", loggedInUserLabel); gbc.gridx = 10; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; //gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(linkPanel, gbc); /* gbc.gridx = 11; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(mySettingHyperlInk,gbc);*/ JXPanel bottomBorderPanel = new Cab2bPanel(); bottomBorderPanel.setPreferredSize(new Dimension(1024, 5)); bottomBorderPanel.setMaximumSize(new Dimension(1024, 5)); bottomBorderPanel.setMinimumSize(new Dimension(1024, 5)); bottomBorderPanel.setBackground(navigationButtonBgColorSelected); this.add("hfill", topPanel); this.add("br hfill", bottomBorderPanel); } /** * Global navigation button's action listener. */ public void actionPerformed(ActionEvent e) { Logger.out.info("Global Nagigation Panel Button"); JButton button = (JButton) e.getSource(); for (int i = 0; i < tabButtons.length; i++) { if (tabButtons[i].getActionCommand().equals(button.getActionCommand())) { tabButtons[i].setBackground(navigationButtonBgColorSelected); if (tabButtons[i].getActionCommand().equals("Home")) { if (this.frame instanceof MainFrame) { MainFrame mainframePanel = (MainFrame) this.frame; mainframePanel.setHomeWelcomePanel(); Logger.out.info("Global Nagigation Panel Home Button"); } } else if (tabButtons[i].getActionCommand().equals("Search Data")) { GlobalNavigationPanel.mainSearchPanel = new MainSearchPanel(); Dimension relDimension = CommonUtils.getRelativeDimension(MainFrame.mainframeScreenDimesion, 0.90f, 0.85f); GlobalNavigationPanel.mainSearchPanel.setPreferredSize(relDimension); GlobalNavigationPanel.mainSearchPanel.setSize(relDimension); edu.wustl.cab2b.client.ui.util.CommonUtils.FrameReference = mainFrame; // Update the variable for latest screen dimension from the toolkit, this is to handle the situations were // Application is started and then screen resolution is changed, but the variable stiil holds old resolution size. MainFrame.mainframeScreenDimesion = Toolkit.getDefaultToolkit().getScreenSize(); Dimension dimension = MainFrame.mainframeScreenDimesion; WindowUtilities.showInDialog(mainFrame, GlobalNavigationPanel.mainSearchPanel, "Search Data", new Dimension((int)(dimension.width * 0.90), (int)(dimension.height * 0.85)), true, true); GlobalNavigationPanel.mainSearchPanel.getDataList().clear(); GlobalNavigationPanel.mainSearchPanel = null; } else if (tabButtons[i].getActionCommand().equals("Experiment")) { MainFrame mainframePanel = (MainFrame) this.frame; mainframePanel.setOpenExperimentWelcomePanel(); return; } } else { tabButtons[i].setBackground(navigationButtonBgColorUnSelected); } } this.updateUI(); this.repaint(); } /** * @param args */ public static void main(String[] args) { Logger.configure(""); GlobalNavigationPanel globalNavigationPanel = new GlobalNavigationPanel(new JXFrame(), new MainFrame()); //JFrame frame = WindowUtilities.openInJFrame(globalNavigationPanel, 1024, 70, "Global Navigation Panel"); JXFrame frame = WindowUtilities.showInFrame(globalNavigationPanel, "Global Navigation Panel"); //frame.getRootPaneExt().removeAll(); //frame.setResizable(false); //frame.setBackground(new Color(120,120,220)); } }
true
true
private void initGUIWithGB() { /* to this panel add top panel and bottom panel */ Cab2bPanel topPanel = new Cab2bPanel(); topPanel.setBackground(bgColor); topPanel.setPreferredSize(new Dimension(1024, 70)); topPanel.setMinimumSize(new Dimension(1024, 70)); topPanel.setMaximumSize(new Dimension(1024, 70)); GridBagConstraints gbc = new GridBagConstraints(); topPanel.setLayout(new GridBagLayout()); // 1 component Icon logoIcon = new ImageIcon("resources/images/b2b_logo.gif"); titleLabel = new Cab2bLabel(logoIcon); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(titleLabel, gbc); //this.add(titleLabel); // 2 component JXPanel extraSpaceFillerPanel1 = new Cab2bPanel(); extraSpaceFillerPanel1.setBackground(bgColor); extraSpaceFillerPanel1.setPreferredSize(new Dimension(60, 70)); extraSpaceFillerPanel1.setMinimumSize(new Dimension(60, 70)); extraSpaceFillerPanel1.setMaximumSize(new Dimension(60, 70)); gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 2; gbc.weightx = 0.50; gbc.fill = GridBagConstraints.BOTH; topPanel.add(extraSpaceFillerPanel1, gbc); //this.add("hfill vfill", extraSpaceFillerPanel1); // 3rd component topMiddlePanel = new Cab2bPanel(); topMiddlePanel.setPreferredSize(new Dimension(300, 37)); topMiddlePanel.setMinimumSize(new Dimension(300, 37)); topMiddlePanel.setMaximumSize(new Dimension(300, 37)); topMiddlePanel.setBackground(bgColor); // 4th component tabsPanel = new Cab2bPanel(); tabsPanel.setPreferredSize(new Dimension(300, 33)); tabsPanel.setMinimumSize(new Dimension(300, 33)); tabsPanel.setMaximumSize(new Dimension(300, 33)); tabsPanel.setBackground(bgColor); tabsPanel.setLayout(new HorizontalLayout(10)); for (int i = 0; i < tabs.length; i++) { String tabText = tabs[i]; String tabImageFileLocation = tabsImages[i]; ImageIcon imageIcon = new ImageIcon(tabImageFileLocation); //tabButtons[i] = new Cab2bButton(imageIcon); //tabButtons[i].setActionCommand(tabText); tabButtons[i] = new Cab2bButton(tabText, true, Cab2bStandardFonts.ARIAL_BOLD_12); tabButtons[i].setBorder(null); if (i != 0) { tabButtons[i].setBackground(navigationButtonBgColorUnSelected); //new Color(168, 168, 168) } else { tabButtons[i].setBackground(navigationButtonBgColorSelected); //new Color(220,220,240) } tabButtons[i].addActionListener(this); tabsPanel.add(tabButtons[i]); } gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 3; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(topMiddlePanel, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 3; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(tabsPanel, gbc); // 5th component JXPanel extraSpaceFillerPanel2 = new Cab2bPanel(); extraSpaceFillerPanel2.setBackground(bgColor); gbc.gridx = 7; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 2; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 0.50; topPanel.add(extraSpaceFillerPanel2, gbc); //this.add("hfill vfill", extraSpaceFillerPanel2); // 6th component, which is a cab2b banner image. Icon bannerIcon = new ImageIcon("resources/images/b2b_banner.gif"); Cab2bLabel bannerLabel = new Cab2bLabel(bannerIcon); gbc.gridx = 8; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(bannerLabel, gbc); Date date = new Date(); loggedInUserLabel = new Cab2bLabel("<html>Robert Lloyd <br>" + DateFormat.getDateInstance(DateFormat.LONG).format(date).toString() + "<br><br></html>"); Cab2bHyperlink logOutHyperLink = new Cab2bHyperlink(Color.GRAY, Color.WHITE); logOutHyperLink.setText("Logout"); logOutHyperLink.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Logger.out.info("Clicked on logOut Link"); } }); Cab2bHyperlink mySettingHyperlInk = new Cab2bHyperlink(Color.GRAY, Color.WHITE); mySettingHyperlInk.setText("MySettings"); mySettingHyperlInk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Logger.out.info("Clicked on My-Settings Link"); } }); loggedInUserLabel.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); loggedInUserLabel.setForeground(fgColor); loggedInUserLabel.setBackground(bgColor); Cab2bPanel linkPanel = new Cab2bPanel(); linkPanel.add(logOutHyperLink); linkPanel.add(mySettingHyperlInk); linkPanel.setOpaque(false); Dimension prefSize = loggedInUserLabel.getPreferredSize(); loggedInUserLabel.setMaximumSize(prefSize); loggedInUserLabel.setMinimumSize(prefSize); gbc.gridx = 10; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(loggedInUserLabel, gbc); //this.add("hfill", loggedInUserLabel); gbc.gridx = 10; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; //gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(linkPanel, gbc); /* gbc.gridx = 11; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(mySettingHyperlInk,gbc);*/ JXPanel bottomBorderPanel = new Cab2bPanel(); bottomBorderPanel.setPreferredSize(new Dimension(1024, 5)); bottomBorderPanel.setMaximumSize(new Dimension(1024, 5)); bottomBorderPanel.setMinimumSize(new Dimension(1024, 5)); bottomBorderPanel.setBackground(navigationButtonBgColorSelected); this.add("hfill", topPanel); this.add("br hfill", bottomBorderPanel); }
private void initGUIWithGB() { /* to this panel add top panel and bottom panel */ Cab2bPanel topPanel = new Cab2bPanel(); topPanel.setBackground(bgColor); topPanel.setPreferredSize(new Dimension(1024, 70)); topPanel.setMinimumSize(new Dimension(1024, 70)); topPanel.setMaximumSize(new Dimension(1024, 70)); GridBagConstraints gbc = new GridBagConstraints(); topPanel.setLayout(new GridBagLayout()); // 1 component Icon logoIcon = new ImageIcon("resources/images/b2b_logo.gif"); titleLabel = new Cab2bLabel(logoIcon); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(titleLabel, gbc); //this.add(titleLabel); // 2 component JXPanel extraSpaceFillerPanel1 = new Cab2bPanel(); extraSpaceFillerPanel1.setBackground(bgColor); extraSpaceFillerPanel1.setPreferredSize(new Dimension(60, 70)); extraSpaceFillerPanel1.setMinimumSize(new Dimension(60, 70)); extraSpaceFillerPanel1.setMaximumSize(new Dimension(60, 70)); gbc.gridx = 2; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 2; gbc.weightx = 0.50; gbc.fill = GridBagConstraints.BOTH; topPanel.add(extraSpaceFillerPanel1, gbc); //this.add("hfill vfill", extraSpaceFillerPanel1); // 3rd component topMiddlePanel = new Cab2bPanel(); topMiddlePanel.setPreferredSize(new Dimension(300, 37)); topMiddlePanel.setMinimumSize(new Dimension(300, 37)); topMiddlePanel.setMaximumSize(new Dimension(300, 37)); topMiddlePanel.setBackground(bgColor); // 4th component tabsPanel = new Cab2bPanel(); tabsPanel.setPreferredSize(new Dimension(300, 33)); tabsPanel.setMinimumSize(new Dimension(300, 33)); tabsPanel.setMaximumSize(new Dimension(300, 33)); tabsPanel.setBackground(bgColor); tabsPanel.setLayout(new HorizontalLayout(10)); for (int i = 0; i < tabs.length; i++) { String tabText = tabs[i]; String tabImageFileLocation = tabsImages[i]; ImageIcon imageIcon = new ImageIcon(tabImageFileLocation); //tabButtons[i] = new Cab2bButton(imageIcon); //tabButtons[i].setActionCommand(tabText); tabButtons[i] = new Cab2bButton(tabText, true, Cab2bStandardFonts.ARIAL_BOLD_12); tabButtons[i].setBorder(null); if (i != 0) { tabButtons[i].setBackground(navigationButtonBgColorUnSelected); //new Color(168, 168, 168) } else { tabButtons[i].setBackground(navigationButtonBgColorSelected); //new Color(220,220,240) } tabButtons[i].addActionListener(this); tabsPanel.add(tabButtons[i]); } gbc.gridx = 3; gbc.gridy = 0; gbc.gridwidth = 3; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(topMiddlePanel, gbc); gbc.gridx = 3; gbc.gridy = 1; gbc.gridwidth = 3; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(tabsPanel, gbc); // 5th component JXPanel extraSpaceFillerPanel2 = new Cab2bPanel(); extraSpaceFillerPanel2.setBackground(bgColor); gbc.gridx = 7; gbc.gridy = 0; gbc.gridwidth = 1; gbc.gridheight = 2; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 0.50; topPanel.add(extraSpaceFillerPanel2, gbc); //this.add("hfill vfill", extraSpaceFillerPanel2); // 6th component, which is a cab2b banner image. Icon bannerIcon = new ImageIcon("resources/images/b2b_banner.gif"); Cab2bLabel bannerLabel = new Cab2bLabel(bannerIcon); gbc.gridx = 8; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(bannerLabel, gbc); Date date = new Date(); loggedInUserLabel = new Cab2bLabel("<html><b>Robert Lloyd</b><br>" + DateFormat.getDateInstance(DateFormat.LONG).format(date).toString() + "<br><br></html>"); Cab2bHyperlink logOutHyperLink = new Cab2bHyperlink(Color.GRAY, Color.WHITE); logOutHyperLink.setText("Logout"); logOutHyperLink.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Logger.out.info("Clicked on logOut Link"); } }); Cab2bHyperlink mySettingHyperlInk = new Cab2bHyperlink(Color.GRAY, Color.WHITE); mySettingHyperlInk.setText("MySettings"); mySettingHyperlInk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Logger.out.info("Clicked on My-Settings Link"); } }); loggedInUserLabel.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); loggedInUserLabel.setForeground(fgColor); loggedInUserLabel.setBackground(bgColor); Cab2bPanel linkPanel = new Cab2bPanel(); linkPanel.add(logOutHyperLink); linkPanel.add(mySettingHyperlInk); linkPanel.setOpaque(false); Dimension prefSize = loggedInUserLabel.getPreferredSize(); loggedInUserLabel.setMaximumSize(prefSize); loggedInUserLabel.setMinimumSize(prefSize); gbc.gridx = 10; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(loggedInUserLabel, gbc); //this.add("hfill", loggedInUserLabel); gbc.gridx = 10; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; //gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(linkPanel, gbc); /* gbc.gridx = 11; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.fill = GridBagConstraints.VERTICAL; topPanel.add(mySettingHyperlInk,gbc);*/ JXPanel bottomBorderPanel = new Cab2bPanel(); bottomBorderPanel.setPreferredSize(new Dimension(1024, 5)); bottomBorderPanel.setMaximumSize(new Dimension(1024, 5)); bottomBorderPanel.setMinimumSize(new Dimension(1024, 5)); bottomBorderPanel.setBackground(navigationButtonBgColorSelected); this.add("hfill", topPanel); this.add("br hfill", bottomBorderPanel); }
diff --git a/plugins/com.aptana.ide.filesystem.ftp/src/com/aptana/ide/filesystem/ftp/FTPConnectionPoint.java b/plugins/com.aptana.ide.filesystem.ftp/src/com/aptana/ide/filesystem/ftp/FTPConnectionPoint.java index 3c30d56e..5392f2bb 100644 --- a/plugins/com.aptana.ide.filesystem.ftp/src/com/aptana/ide/filesystem/ftp/FTPConnectionPoint.java +++ b/plugins/com.aptana.ide.filesystem.ftp/src/com/aptana/ide/filesystem/ftp/FTPConnectionPoint.java @@ -1,408 +1,411 @@ /** * This file Copyright (c) 2005-2010 Aptana, Inc. This program is * dual-licensed under both the Aptana Public License and the GNU General * Public license. You may elect to use one or the other of these licenses. * * This program is distributed in the hope that it will be useful, but * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or * NONINFRINGEMENT. Redistribution, except as permitted by whichever of * the GPL or APL you select, is prohibited. * * 1. For the GPL license (GPL), you can redistribute and/or modify this * program under the terms of the GNU General Public License, * Version 3, as published by the Free Software Foundation. You should * have received a copy of the GNU General Public License, Version 3 along * with this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Aptana provides a special exception to allow redistribution of this file * with certain other free and open source software ("FOSS") code and certain additional terms * pursuant to Section 7 of the GPL. You may view the exception and these * terms on the web at http://www.aptana.com/legal/gpl/. * * 2. For the Aptana Public License (APL), this program and the * accompanying materials are made available under the terms of the APL * v1.0 which accompanies this distribution, and is available at * http://www.aptana.com/legal/apl/. * * You may view the GPL, Aptana's exception and additional terms, and the * APL in the file titled license.html at the root of the corresponding * plugin containing this source file. * * Any modifications to this file must keep this entire header intact. */ package com.aptana.ide.filesystem.ftp; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import com.aptana.ide.core.StringUtils; import com.aptana.ide.core.epl.IMemento; import com.aptana.ide.core.io.ConnectionContext; import com.aptana.ide.core.io.ConnectionPoint; import com.aptana.ide.core.io.CoreIOPlugin; import com.aptana.ide.core.io.IConnectionPoint15Constants; import com.aptana.ide.core.io.vfs.IConnectionFileManager; /** * @author Max Stepanov * */ public class FTPConnectionPoint extends ConnectionPoint implements IBaseFTPConnectionPoint { public static final String TYPE = TYPE_FTP; private static final String ELEMENT_HOST = "host"; //$NON-NLS-1$ private static final String ELEMENT_PORT = "port"; //$NON-NLS-1$ private static final String ELEMENT_PATH = "path"; //$NON-NLS-1$ private static final String ELEMENT_LOGIN = "login"; //$NON-NLS-1$ private static final String ELEMENT_PASSIVE = "passive"; //$NON-NLS-1$ private static final String ELEMENT_TRANSFER_TYPE = "transferType"; //$NON-NLS-1$ private static final String ELEMENT_ENCODING = "encoding"; //$NON-NLS-1$ private static final String ELEMENT_TIMEZONE = "timezone"; //$NON-NLS-1$ protected String host; protected int port = IFTPConstants.FTP_PORT_DEFAULT; protected IPath path = Path.ROOT; protected String login = StringUtils.EMPTY; protected char[] password; protected boolean passiveMode = true; protected String transferType = IFTPConstants.TRANSFER_TYPE_BINARY; protected String encoding = IFTPConstants.ENCODING_DEFAULT; protected String timezone = null; protected IFTPConnectionFileManager connectionFileManager; /** * Default constructor */ public FTPConnectionPoint() { super(TYPE); } /* (non-Javadoc) * @see com.aptana.ide.core.io.ConnectionPoint#loadState(com.aptana.ide.core.io.epl.IMemento) */ @Override protected void loadState(IMemento memento) { super.loadState(memento); IMemento child = memento.getChild(ELEMENT_HOST); if (child != null) { host = child.getTextData(); } child = memento.getChild(ELEMENT_PORT); if (child != null) { try { port = Integer.parseInt(child.getTextData()); } catch (NumberFormatException e) { } } child = memento.getChild(ELEMENT_PATH); if (child != null) { - path = Path.fromPortableString(child.getTextData()); + String text = child.getTextData(); + if (text != null) { + path = Path.fromPortableString(text); + } } child = memento.getChild(ELEMENT_LOGIN); if (child != null) { login = child.getTextData(); } child = memento.getChild(ELEMENT_PASSIVE); if (child != null) { passiveMode = Boolean.parseBoolean(child.getTextData()); } child = memento.getChild(ELEMENT_TRANSFER_TYPE); if (child != null) { transferType = child.getTextData(); } child = memento.getChild(ELEMENT_ENCODING); if (child != null) { encoding = child.getTextData(); } child = memento.getChild(ELEMENT_TIMEZONE); if (child != null) { timezone = child.getTextData(); } } /* (non-Javadoc) * @see com.aptana.ide.core.io.ConnectionPoint#saveState(com.aptana.ide.core.io.epl.IMemento) */ @Override protected void saveState(IMemento memento) { super.saveState(memento); memento.createChild(ELEMENT_HOST).putTextData(host); if (IFTPConstants.FTP_PORT_DEFAULT != port) { memento.createChild(ELEMENT_PORT).putTextData(Integer.toString(port)); } if (!Path.ROOT.equals(path)) { memento.createChild(ELEMENT_PATH).putTextData(path.toPortableString()); } if (login.length() != 0) { memento.createChild(ELEMENT_LOGIN).putTextData(login); } memento.createChild(ELEMENT_PASSIVE).putTextData(Boolean.toString(passiveMode)); if (!IFTPConstants.TRANSFER_TYPE_AUTO.equals(transferType)) { memento.createChild(ELEMENT_TRANSFER_TYPE).putTextData(transferType); } if (!IFTPConstants.ENCODING_DEFAULT.equals(encoding)) { memento.createChild(ELEMENT_ENCODING).putTextData(encoding); } if (timezone != null && timezone.length() != 0) { memento.createChild(ELEMENT_TIMEZONE).putTextData(timezone); } } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#getHost() */ public String getHost() { return host; } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#setHost(java.lang.String) */ public void setHost(String host) { this.host = host; notifyChanged(); resetConnectionFileManager(); } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#getPort() */ public int getPort() { return port; } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#setPort(int) */ public void setPort(int port) { this.port = port; notifyChanged(); resetConnectionFileManager(); } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#getPath() */ public IPath getPath() { return path; } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#setPath(org.eclipse.core.runtime.IPath) */ public void setPath(IPath path) { if (path == null || path.isEmpty()) { path = Path.ROOT; } this.path = path; notifyChanged(); resetConnectionFileManager(); } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#getLogin() */ public String getLogin() { return login; } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#setLogin(java.lang.String) */ public void setLogin(String login) { this.login = login; notifyChanged(); resetConnectionFileManager(); } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#getPassword() */ public char[] getPassword() { return password; } /* (non-Javadoc) * @see com.aptana.ide.core.ftp.IBaseRemoteConnectionPoint#setPassword(char[]) */ public void setPassword(char[] password) { this.password = password; notifyChanged(); resetConnectionFileManager(); } /** * @return the passiveMode */ public boolean isPassiveMode() { return passiveMode; } /** * @param passiveMode the passiveMode to set */ public void setPassiveMode(boolean passiveMode) { this.passiveMode = passiveMode; notifyChanged(); resetConnectionFileManager(); } /** * @return the transferType */ public String getTransferType() { return transferType; } /** * @param transferType the transferType to set */ public void setTransferType(String transferType) { this.transferType = transferType; notifyChanged(); resetConnectionFileManager(); } /** * @return the encoding */ public String getEncoding() { return encoding; } /** * @param encoding the encoding to set */ public void setEncoding(String encoding) { this.encoding = encoding; notifyChanged(); resetConnectionFileManager(); } /** * @return the timezone */ public String getTimezone() { return timezone; } /** * @param timezone the timezone to set */ public void setTimezone(String timezone) { this.timezone = timezone; notifyChanged(); resetConnectionFileManager(); } /* (non-Javadoc) * @see com.aptana.ide.core.io.ConnectionPoint#connect(boolean, org.eclipse.core.runtime.IProgressMonitor) */ @Override public void connect(boolean force, IProgressMonitor monitor) throws CoreException { if (!force && isConnected()) { return; } ConnectionContext context = CoreIOPlugin.getConnectionContext(this); if (context != null) { CoreIOPlugin.setConnectionContext(connectionFileManager, context); } getConnectionFileManager().connect(monitor); } /* (non-Javadoc) * @see com.aptana.ide.core.io.ConnectionPoint#disconnect(org.eclipse.core.runtime.IProgressMonitor) */ @Override public void disconnect(IProgressMonitor monitor) throws CoreException { if (isConnected()) { getConnectionFileManager().disconnect(monitor); } } /* (non-Javadoc) * @see com.aptana.ide.core.io.ConnectionPoint#isConnected() */ @Override public boolean isConnected() { return connectionFileManager != null && connectionFileManager.isConnected(); } /* (non-Javadoc) * @see com.aptana.ide.core.io.ConnectionPoint#canDisconnect() */ @Override public boolean canDisconnect() { return isConnected() && true; } /* (non-Javadoc) * @see org.eclipse.core.runtime.PlatformObject#getAdapter(java.lang.Class) */ @SuppressWarnings("unchecked") @Override public Object getAdapter(Class adapter) { if (IConnectionFileManager.class == adapter) { return getConnectionFileManager(); } return super.getAdapter(adapter); } private synchronized void resetConnectionFileManager() { connectionFileManager = null; } protected synchronized IConnectionFileManager getConnectionFileManager() { if (connectionFileManager == null) { // find contributed first connectionFileManager = (IFTPConnectionFileManager) super.getAdapter(IFTPConnectionFileManager.class); if (connectionFileManager == null && Platform.getAdapterManager().hasAdapter(this, IFTPConnectionFileManager.class.getName())) { connectionFileManager = (IFTPConnectionFileManager) Platform.getAdapterManager().loadAdapter(this, IFTPConnectionFileManager.class.getName()); } if (connectionFileManager == null) { connectionFileManager = new FTPConnectionFileManager(); } ConnectionContext context = CoreIOPlugin.getConnectionContext(this); if (context != null) { CoreIOPlugin.setConnectionContext(connectionFileManager, context); } connectionFileManager.init(host, port, path, login, password, passiveMode, transferType, encoding, timezone); } return connectionFileManager; } @Override public boolean load15Data(String data) { String[] items = data.split(IConnectionPoint15Constants.DELIMITER); if (items.length < 7) { return false; } setName(items[0]); setHost(items[1]); if (items[2] == null || items[2].equals("")) { //$NON-NLS-1$ setPath(Path.ROOT); } else { setPath(new Path(items[2])); } setLogin(items[3]); setPassword(items[4].toCharArray()); setPassiveMode(items[5].equals(Boolean.TRUE.toString())); setId(items[6]); if (items.length >= 10) { setPort(Integer.parseInt(items[9])); } return true; } }
true
true
protected void loadState(IMemento memento) { super.loadState(memento); IMemento child = memento.getChild(ELEMENT_HOST); if (child != null) { host = child.getTextData(); } child = memento.getChild(ELEMENT_PORT); if (child != null) { try { port = Integer.parseInt(child.getTextData()); } catch (NumberFormatException e) { } } child = memento.getChild(ELEMENT_PATH); if (child != null) { path = Path.fromPortableString(child.getTextData()); } child = memento.getChild(ELEMENT_LOGIN); if (child != null) { login = child.getTextData(); } child = memento.getChild(ELEMENT_PASSIVE); if (child != null) { passiveMode = Boolean.parseBoolean(child.getTextData()); } child = memento.getChild(ELEMENT_TRANSFER_TYPE); if (child != null) { transferType = child.getTextData(); } child = memento.getChild(ELEMENT_ENCODING); if (child != null) { encoding = child.getTextData(); } child = memento.getChild(ELEMENT_TIMEZONE); if (child != null) { timezone = child.getTextData(); } }
protected void loadState(IMemento memento) { super.loadState(memento); IMemento child = memento.getChild(ELEMENT_HOST); if (child != null) { host = child.getTextData(); } child = memento.getChild(ELEMENT_PORT); if (child != null) { try { port = Integer.parseInt(child.getTextData()); } catch (NumberFormatException e) { } } child = memento.getChild(ELEMENT_PATH); if (child != null) { String text = child.getTextData(); if (text != null) { path = Path.fromPortableString(text); } } child = memento.getChild(ELEMENT_LOGIN); if (child != null) { login = child.getTextData(); } child = memento.getChild(ELEMENT_PASSIVE); if (child != null) { passiveMode = Boolean.parseBoolean(child.getTextData()); } child = memento.getChild(ELEMENT_TRANSFER_TYPE); if (child != null) { transferType = child.getTextData(); } child = memento.getChild(ELEMENT_ENCODING); if (child != null) { encoding = child.getTextData(); } child = memento.getChild(ELEMENT_TIMEZONE); if (child != null) { timezone = child.getTextData(); } }
diff --git a/src/main/java/uk/co/revthefox/foxbot/Utils.java b/src/main/java/uk/co/revthefox/foxbot/Utils.java index 584fea5..4ecc1ce 100644 --- a/src/main/java/uk/co/revthefox/foxbot/Utils.java +++ b/src/main/java/uk/co/revthefox/foxbot/Utils.java @@ -1,70 +1,70 @@ package uk.co.revthefox.foxbot; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.Response; import org.pircbotx.Colors; import org.pircbotx.User; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utils { private FoxBot foxbot; public Utils(FoxBot foxbot) { this.foxbot = foxbot; } public String parseChatUrl(String stringToParse, User sender) { try { AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder().setUserAgent("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36").build(); AsyncHttpClient client = new AsyncHttpClient(cf); Future<Response> future = client.prepareGet(stringToParse).setFollowRedirects(true).execute(); Response response = future.get(); String output = response.getResponseBody("UTF-8"); URLConnection conn = new URL(stringToParse).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36"); - String size = (conn.getContentLengthLong() / 1024) + "kb"; + String size = (response.getResponseBodyAsBytes().length / 1024) + "kb"; String content_type = conn.getContentType().contains(";") ? conn.getContentType().split(";")[0] : conn.getContentType(); if (response.getStatusCode() != 200 && response.getStatusCode() != 302 && response.getStatusCode() != 301) { return String.format("(%s's URL) %sError: %s%s %s ", sender.getNick(), Colors.RED, Colors.NORMAL, response.getStatusCode(), response.getStatusText()); } if (!content_type.contains("html")) { return "(" + sender.getNick() + "'s URL)" + Colors.GREEN + "Content Type: " + Colors.NORMAL + content_type + Colors.GREEN + " Size:" + Colors.NORMAL + (conn.getContentLengthLong() / 1024) + "kb"; } Pattern p = Pattern.compile("<title>.+</title>"); Matcher m; String title = "Error?"; for (String line : output.split("\n")) { m = p.matcher(line); if (m.find()) { title = line.split("<title>")[1].split("</title>")[0]; } } return String.format("(%s's URL) " + Colors.GREEN + "Title: " + Colors.NORMAL + "%s " + Colors.GREEN + "Content type: " + Colors.NORMAL + "%s " + Colors.GREEN + "Size: " + Colors.NORMAL + "%s", sender.getNick(), title, content_type, size); } catch (Exception ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } return "null"; } }
true
true
public String parseChatUrl(String stringToParse, User sender) { try { AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder().setUserAgent("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36").build(); AsyncHttpClient client = new AsyncHttpClient(cf); Future<Response> future = client.prepareGet(stringToParse).setFollowRedirects(true).execute(); Response response = future.get(); String output = response.getResponseBody("UTF-8"); URLConnection conn = new URL(stringToParse).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36"); String size = (conn.getContentLengthLong() / 1024) + "kb"; String content_type = conn.getContentType().contains(";") ? conn.getContentType().split(";")[0] : conn.getContentType(); if (response.getStatusCode() != 200 && response.getStatusCode() != 302 && response.getStatusCode() != 301) { return String.format("(%s's URL) %sError: %s%s %s ", sender.getNick(), Colors.RED, Colors.NORMAL, response.getStatusCode(), response.getStatusText()); } if (!content_type.contains("html")) { return "(" + sender.getNick() + "'s URL)" + Colors.GREEN + "Content Type: " + Colors.NORMAL + content_type + Colors.GREEN + " Size:" + Colors.NORMAL + (conn.getContentLengthLong() / 1024) + "kb"; } Pattern p = Pattern.compile("<title>.+</title>"); Matcher m; String title = "Error?"; for (String line : output.split("\n")) { m = p.matcher(line); if (m.find()) { title = line.split("<title>")[1].split("</title>")[0]; } } return String.format("(%s's URL) " + Colors.GREEN + "Title: " + Colors.NORMAL + "%s " + Colors.GREEN + "Content type: " + Colors.NORMAL + "%s " + Colors.GREEN + "Size: " + Colors.NORMAL + "%s", sender.getNick(), title, content_type, size); } catch (Exception ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } return "null"; }
public String parseChatUrl(String stringToParse, User sender) { try { AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder().setUserAgent("Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36").build(); AsyncHttpClient client = new AsyncHttpClient(cf); Future<Response> future = client.prepareGet(stringToParse).setFollowRedirects(true).execute(); Response response = future.get(); String output = response.getResponseBody("UTF-8"); URLConnection conn = new URL(stringToParse).openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36"); String size = (response.getResponseBodyAsBytes().length / 1024) + "kb"; String content_type = conn.getContentType().contains(";") ? conn.getContentType().split(";")[0] : conn.getContentType(); if (response.getStatusCode() != 200 && response.getStatusCode() != 302 && response.getStatusCode() != 301) { return String.format("(%s's URL) %sError: %s%s %s ", sender.getNick(), Colors.RED, Colors.NORMAL, response.getStatusCode(), response.getStatusText()); } if (!content_type.contains("html")) { return "(" + sender.getNick() + "'s URL)" + Colors.GREEN + "Content Type: " + Colors.NORMAL + content_type + Colors.GREEN + " Size:" + Colors.NORMAL + (conn.getContentLengthLong() / 1024) + "kb"; } Pattern p = Pattern.compile("<title>.+</title>"); Matcher m; String title = "Error?"; for (String line : output.split("\n")) { m = p.matcher(line); if (m.find()) { title = line.split("<title>")[1].split("</title>")[0]; } } return String.format("(%s's URL) " + Colors.GREEN + "Title: " + Colors.NORMAL + "%s " + Colors.GREEN + "Content type: " + Colors.NORMAL + "%s " + Colors.GREEN + "Size: " + Colors.NORMAL + "%s", sender.getNick(), title, content_type, size); } catch (Exception ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } return "null"; }
diff --git a/src/hu/harmakhis/shisha/charts/PlayerChart.java b/src/hu/harmakhis/shisha/charts/PlayerChart.java index ca0a678..1476f1a 100644 --- a/src/hu/harmakhis/shisha/charts/PlayerChart.java +++ b/src/hu/harmakhis/shisha/charts/PlayerChart.java @@ -1,124 +1,122 @@ /** * Copyright (C) 2009, 2010 SC 4ViewSoft SRL * * 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 hu.harmakhis.shisha.charts; import hu.harmakhis.shisha.entities.Player; import hu.harmakhis.shisha.entities.Session; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import org.achartengine.ChartFactory; import org.achartengine.chart.PointStyle; import org.achartengine.renderer.XYMultipleSeriesRenderer; import org.achartengine.renderer.XYSeriesRenderer; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Paint.Align; /** * Average temperature demo chart. */ public class PlayerChart extends AbstractChart { private Session s; /** * Returns the chart name. * * @return the chart name */ public String getName() { return "Player chart"; } /** * Returns the chart description. * * @return the chart description */ public String getDesc() { return ""; } public void setSession(Session sess) { s = sess; } /** * Executes the chart demo. * * @param context * the context * @return the built intent */ public Intent execute(Context context) { List<Player> players = s.getPlayers(); String[] titles = new String[players.size()]; int i = 0; for (Player p : players) { titles[i++] = p.getName(); } ; double maxValue = 0; List<double[]> x = new ArrayList<double[]>(); List<double[]> values = new ArrayList<double[]>(); int[] colors = new int[players.size()]; PointStyle[] styles = new PointStyle[players.size()]; Random r = new Random(555555); for (i = 0; i < titles.length; i++) { colors[i] = Color.rgb(r.nextInt(255), r.nextInt(255), r.nextInt(255)); styles[i] = PointStyle.CIRCLE; Player p = players.get(i); Map<Integer, Long> history = p.getHistory(); double[] playerstat = new double[history.size()]; double[] timing = new double[history.size()]; int u = 0; for (Integer time : history.keySet()) { timing[u] = time; double value = history.get(time).doubleValue(); playerstat[u] = value / 1000; if (playerstat[u] > maxValue) { maxValue = playerstat[u]; } u++; } x.add(timing); values.add(playerstat); } XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles); int length = renderer.getSeriesRendererCount(); for (i = 0; i < length; i++) { ((XYSeriesRenderer) renderer.getSeriesRendererAt(i)) .setFillPoints(true); } - setChartSettings(renderer, "Shisha using times", "Round", + setChartSettings(renderer, "Shisha usage times", "Round", "Time (sec)", 0.5, s.getRounds() + 0.5, 0, maxValue, Color.LTGRAY, Color.LTGRAY); renderer.setXLabels(12); renderer.setYLabels(10); renderer.setShowGrid(true); renderer.setXLabelsAlign(Align.RIGHT); renderer.setYLabelsAlign(Align.RIGHT); - //renderer.setPanLimits(new double[] { -10, 20, -10, 40 }); - //renderer.setZoomLimits(new double[] { -10, 20, -10, 40 }); Intent intent = ChartFactory.getLineChartIntent(context, buildDataset( - titles, x, values), renderer, "Shisha using times"); + titles, x, values), renderer, "Shisha usage times"); return intent; } }
false
true
public Intent execute(Context context) { List<Player> players = s.getPlayers(); String[] titles = new String[players.size()]; int i = 0; for (Player p : players) { titles[i++] = p.getName(); } ; double maxValue = 0; List<double[]> x = new ArrayList<double[]>(); List<double[]> values = new ArrayList<double[]>(); int[] colors = new int[players.size()]; PointStyle[] styles = new PointStyle[players.size()]; Random r = new Random(555555); for (i = 0; i < titles.length; i++) { colors[i] = Color.rgb(r.nextInt(255), r.nextInt(255), r.nextInt(255)); styles[i] = PointStyle.CIRCLE; Player p = players.get(i); Map<Integer, Long> history = p.getHistory(); double[] playerstat = new double[history.size()]; double[] timing = new double[history.size()]; int u = 0; for (Integer time : history.keySet()) { timing[u] = time; double value = history.get(time).doubleValue(); playerstat[u] = value / 1000; if (playerstat[u] > maxValue) { maxValue = playerstat[u]; } u++; } x.add(timing); values.add(playerstat); } XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles); int length = renderer.getSeriesRendererCount(); for (i = 0; i < length; i++) { ((XYSeriesRenderer) renderer.getSeriesRendererAt(i)) .setFillPoints(true); } setChartSettings(renderer, "Shisha using times", "Round", "Time (sec)", 0.5, s.getRounds() + 0.5, 0, maxValue, Color.LTGRAY, Color.LTGRAY); renderer.setXLabels(12); renderer.setYLabels(10); renderer.setShowGrid(true); renderer.setXLabelsAlign(Align.RIGHT); renderer.setYLabelsAlign(Align.RIGHT); //renderer.setPanLimits(new double[] { -10, 20, -10, 40 }); //renderer.setZoomLimits(new double[] { -10, 20, -10, 40 }); Intent intent = ChartFactory.getLineChartIntent(context, buildDataset( titles, x, values), renderer, "Shisha using times"); return intent; }
public Intent execute(Context context) { List<Player> players = s.getPlayers(); String[] titles = new String[players.size()]; int i = 0; for (Player p : players) { titles[i++] = p.getName(); } ; double maxValue = 0; List<double[]> x = new ArrayList<double[]>(); List<double[]> values = new ArrayList<double[]>(); int[] colors = new int[players.size()]; PointStyle[] styles = new PointStyle[players.size()]; Random r = new Random(555555); for (i = 0; i < titles.length; i++) { colors[i] = Color.rgb(r.nextInt(255), r.nextInt(255), r.nextInt(255)); styles[i] = PointStyle.CIRCLE; Player p = players.get(i); Map<Integer, Long> history = p.getHistory(); double[] playerstat = new double[history.size()]; double[] timing = new double[history.size()]; int u = 0; for (Integer time : history.keySet()) { timing[u] = time; double value = history.get(time).doubleValue(); playerstat[u] = value / 1000; if (playerstat[u] > maxValue) { maxValue = playerstat[u]; } u++; } x.add(timing); values.add(playerstat); } XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles); int length = renderer.getSeriesRendererCount(); for (i = 0; i < length; i++) { ((XYSeriesRenderer) renderer.getSeriesRendererAt(i)) .setFillPoints(true); } setChartSettings(renderer, "Shisha usage times", "Round", "Time (sec)", 0.5, s.getRounds() + 0.5, 0, maxValue, Color.LTGRAY, Color.LTGRAY); renderer.setXLabels(12); renderer.setYLabels(10); renderer.setShowGrid(true); renderer.setXLabelsAlign(Align.RIGHT); renderer.setYLabelsAlign(Align.RIGHT); Intent intent = ChartFactory.getLineChartIntent(context, buildDataset( titles, x, values), renderer, "Shisha usage times"); return intent; }
diff --git a/src/trollhoehle/gamejam/magnets/Management.java b/src/trollhoehle/gamejam/magnets/Management.java index 11e1d56..3f11deb 100644 --- a/src/trollhoehle/gamejam/magnets/Management.java +++ b/src/trollhoehle/gamejam/magnets/Management.java @@ -1,224 +1,224 @@ package trollhoehle.gamejam.magnets; import trollhoehle.gamejam.magnets.Player; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.openal.Audio; import org.newdawn.slick.openal.AudioLoader; public class Management extends BasicGame { /** * All Entities but the Players and the ring */ private ArrayList<Entity> entities; private Core core; private Ring ring; private ArrayList<Player> players; public Management() { super("Fucking magnets - How do they work?"); this.entities = new ArrayList<Entity>(); this.players = new ArrayList<Player>(); } /** * @param args * @throws SlickException */ public static void main(String[] args) throws SlickException { Management management = new Management(); AppGameContainer app = new AppGameContainer(management); GlobalSettings.setManagement(management); app.setDisplayMode(720, 720, false); app.setTargetFrameRate(60); app.start(); } /** * Sets the speed of all objects to a desired value. * * @param currentSpeed */ public void changeCurrentSpeed(float currentSpeed) { this.core.setSpeedMultiplier(currentSpeed); this.ring.setSpeedMultiplier(currentSpeed); for (Entity e : this.entities) { e.setSpeedMultiplier(currentSpeed); } for (Player p : this.players) { p.setSpeedMultiplier(currentSpeed); } } public void render(GameContainer gc, Graphics arg1) throws SlickException { for (Entity e : this.entities) { e.draw(); } ring.draw(); core.draw(); for (Player p : this.players) { p.draw(arg1); } } @Override public void init(GameContainer gc) throws SlickException { this.ring = new Ring(gc.getWidth() / 2, gc.getHeight() / 2, gc.getWidth() / 2); this.core = new Core(gc.getWidth(), gc.getHeight()); gc.getInput().addKeyListener(new MagnetKeyListener(this.players)); try { GlobalSettings.initSound(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } GlobalSettings.getNyanLoop().playAsMusic(1.0f, 1.0f, true); } @Override public void update(GameContainer gc, int delta) throws SlickException { Input input = gc.getInput(); ArrayList<Obstacle> newObstacles = new ArrayList<Obstacle>(); // RING newObstacles.addAll(this.ring.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0.08f)); // CORE newObstacles.addAll(this.core.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0.08f)); // PLAYERS for (int i = 0; i < this.players.size(); i++) { float attract = 0; Player p = this.players.get(i); // KEY STROKES: if (input.isKeyDown(p.getButton())) { attract = 0.3f; p.setImg(new Image("res/images/magnet_active.png")); // TODO: Particles! } else { p.setImg(new Image("res/images/magnet_inactive.png")); // TODO: Particles! } // NEW POSITION newObstacles.addAll(p.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, attract)); // COLLISION for (int j = i + 1; j < this.players.size(); j++) { Player pc = this.players.get(j); if (p.getShape().intersects(pc.getShape())) { p.collision(pc); pc.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } for (int j = 0; j < this.entities.size(); j++) { Entity ec = this.entities.get(j); if (p.getShape().intersects(ec.getShape())) { p.collision(ec); ec.collision(p); if (!(ec instanceof Powerup)) { GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } } if (!p.getShape().intersects(this.ring.getShape())) { p.collision(this.ring); this.ring.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } if (p.getShape().intersects(this.core.getShape())) { p.collision(this.core); this.core.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } // OTHER ENTITES for (int i = 0; i < this.entities.size(); i++) { Entity e = this.entities.get(i); // NEW POSITION - newObstacles = e.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0); + newObstacles.addAll(e.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0)); // COLLISION for (int j = i + 1; j < this.entities.size(); j++) { Entity ec = this.entities.get(j); if (e.getShape().intersects(ec.getShape())) { e.collision(ec); ec.collision(e); } } if (!e.getShape().intersects(this.ring.getShape())) { e.collision(ring); ring.collision(e); } if (e.getShape().intersects(this.core.getShape())) { e.collision(core); core.collision(e); } } // KILL DEAD PHYSICAL ENTITIES for (int i = 0; i < this.players.size(); i++) { if (this.players.get(i).getHp() <= 0 && this.players.get(i).getHp() != -100) { GlobalSettings.getExplosion().playAsSoundEffect(1.0f, 1.0f, false); this.players.remove(i); } } for (int i = 0; i < this.entities.size(); i++) { if (this.entities.get(i) instanceof PhysicalEntity) { if (((PhysicalEntity) this.entities.get(i)).getHp() <= 0 && ((PhysicalEntity) this.entities.get(i)).getHp() != -100) { this.entities.remove(i); } } } // TODO: particles(?) // ADD ALL NEW STUFF TO ENTITIES entities.addAll(newObstacles); } }
true
true
public void update(GameContainer gc, int delta) throws SlickException { Input input = gc.getInput(); ArrayList<Obstacle> newObstacles = new ArrayList<Obstacle>(); // RING newObstacles.addAll(this.ring.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0.08f)); // CORE newObstacles.addAll(this.core.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0.08f)); // PLAYERS for (int i = 0; i < this.players.size(); i++) { float attract = 0; Player p = this.players.get(i); // KEY STROKES: if (input.isKeyDown(p.getButton())) { attract = 0.3f; p.setImg(new Image("res/images/magnet_active.png")); // TODO: Particles! } else { p.setImg(new Image("res/images/magnet_inactive.png")); // TODO: Particles! } // NEW POSITION newObstacles.addAll(p.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, attract)); // COLLISION for (int j = i + 1; j < this.players.size(); j++) { Player pc = this.players.get(j); if (p.getShape().intersects(pc.getShape())) { p.collision(pc); pc.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } for (int j = 0; j < this.entities.size(); j++) { Entity ec = this.entities.get(j); if (p.getShape().intersects(ec.getShape())) { p.collision(ec); ec.collision(p); if (!(ec instanceof Powerup)) { GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } } if (!p.getShape().intersects(this.ring.getShape())) { p.collision(this.ring); this.ring.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } if (p.getShape().intersects(this.core.getShape())) { p.collision(this.core); this.core.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } // OTHER ENTITES for (int i = 0; i < this.entities.size(); i++) { Entity e = this.entities.get(i); // NEW POSITION newObstacles = e.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0); // COLLISION for (int j = i + 1; j < this.entities.size(); j++) { Entity ec = this.entities.get(j); if (e.getShape().intersects(ec.getShape())) { e.collision(ec); ec.collision(e); } } if (!e.getShape().intersects(this.ring.getShape())) { e.collision(ring); ring.collision(e); } if (e.getShape().intersects(this.core.getShape())) { e.collision(core); core.collision(e); } } // KILL DEAD PHYSICAL ENTITIES for (int i = 0; i < this.players.size(); i++) { if (this.players.get(i).getHp() <= 0 && this.players.get(i).getHp() != -100) { GlobalSettings.getExplosion().playAsSoundEffect(1.0f, 1.0f, false); this.players.remove(i); } } for (int i = 0; i < this.entities.size(); i++) { if (this.entities.get(i) instanceof PhysicalEntity) { if (((PhysicalEntity) this.entities.get(i)).getHp() <= 0 && ((PhysicalEntity) this.entities.get(i)).getHp() != -100) { this.entities.remove(i); } } } // TODO: particles(?) // ADD ALL NEW STUFF TO ENTITIES entities.addAll(newObstacles); }
public void update(GameContainer gc, int delta) throws SlickException { Input input = gc.getInput(); ArrayList<Obstacle> newObstacles = new ArrayList<Obstacle>(); // RING newObstacles.addAll(this.ring.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0.08f)); // CORE newObstacles.addAll(this.core.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0.08f)); // PLAYERS for (int i = 0; i < this.players.size(); i++) { float attract = 0; Player p = this.players.get(i); // KEY STROKES: if (input.isKeyDown(p.getButton())) { attract = 0.3f; p.setImg(new Image("res/images/magnet_active.png")); // TODO: Particles! } else { p.setImg(new Image("res/images/magnet_inactive.png")); // TODO: Particles! } // NEW POSITION newObstacles.addAll(p.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, attract)); // COLLISION for (int j = i + 1; j < this.players.size(); j++) { Player pc = this.players.get(j); if (p.getShape().intersects(pc.getShape())) { p.collision(pc); pc.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } for (int j = 0; j < this.entities.size(); j++) { Entity ec = this.entities.get(j); if (p.getShape().intersects(ec.getShape())) { p.collision(ec); ec.collision(p); if (!(ec instanceof Powerup)) { GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } } if (!p.getShape().intersects(this.ring.getShape())) { p.collision(this.ring); this.ring.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } if (p.getShape().intersects(this.core.getShape())) { p.collision(this.core); this.core.collision(p); GlobalSettings.getPing().playAsSoundEffect(1.0f, 1.0f, false); } } // OTHER ENTITES for (int i = 0; i < this.entities.size(); i++) { Entity e = this.entities.get(i); // NEW POSITION newObstacles.addAll(e.update(delta, gc.getWidth() / 2, gc.getHeight() / 2, 0)); // COLLISION for (int j = i + 1; j < this.entities.size(); j++) { Entity ec = this.entities.get(j); if (e.getShape().intersects(ec.getShape())) { e.collision(ec); ec.collision(e); } } if (!e.getShape().intersects(this.ring.getShape())) { e.collision(ring); ring.collision(e); } if (e.getShape().intersects(this.core.getShape())) { e.collision(core); core.collision(e); } } // KILL DEAD PHYSICAL ENTITIES for (int i = 0; i < this.players.size(); i++) { if (this.players.get(i).getHp() <= 0 && this.players.get(i).getHp() != -100) { GlobalSettings.getExplosion().playAsSoundEffect(1.0f, 1.0f, false); this.players.remove(i); } } for (int i = 0; i < this.entities.size(); i++) { if (this.entities.get(i) instanceof PhysicalEntity) { if (((PhysicalEntity) this.entities.get(i)).getHp() <= 0 && ((PhysicalEntity) this.entities.get(i)).getHp() != -100) { this.entities.remove(i); } } } // TODO: particles(?) // ADD ALL NEW STUFF TO ENTITIES entities.addAll(newObstacles); }
diff --git a/dspace/src/org/dspace/storage/rdbms/TableRow.java b/dspace/src/org/dspace/storage/rdbms/TableRow.java index 35c824733..21233329f 100644 --- a/dspace/src/org/dspace/storage/rdbms/TableRow.java +++ b/dspace/src/org/dspace/storage/rdbms/TableRow.java @@ -1,456 +1,456 @@ /* * TableRow.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002, Hewlett-Packard Company and Massachusetts * Institute of Technology. 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 the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * 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 * HOLDERS 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.dspace.storage.rdbms; import java.sql.*; import java.util.*; /** * Represents a database row. * * @author Peter Breton * @version $Revision$ */ public class TableRow { /** Marker object to indicate NULLs. */ private static final Object NULL_OBJECT = new Object(); /** The name of the database table containing this row */ private String table; /** * A map of column names to column values. * The key of the map is a String, the column name; * the value is an Object, either an Integer, Boolean, Date, or String. * If the value is NULL_OBJECT, then the column was NULL. */ private Map data = new HashMap(); /** * Constructor * * @param table The name of the database table containing this row. * @param columns A list of column names. Each member of the * List is a String. After construction, the list of columns * is fixed; attempting to access a column not in the list * will cause an IllegalArgumentException to be thrown. */ public TableRow(String table, List columns) { this.table = table; nullColumns(columns); } /** * Return the name of the table containing this row, or null if * this row is not associated with a database table. * * @return The name of the table containing this row */ public String getTable() { return table; } /** * Return true if this row contains a column with this name. * * @param column The column name (case-insensitive) * @return True if this row contains a column with this name. */ public boolean hasColumn (String column) { return data.get(canonicalize(column)) != null; } /** * Return true if the column is an SQL NULL. * * @param column The column name (case-insensitive) * @return True if the column is an SQL NULL */ public boolean isColumnNull(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); return data.get(canonicalize(column)) == NULL_OBJECT; } /** * Return the integer value of column. * * If the column's type is not an integer, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return The integer value of the column, or -1 if the column * is an SQL null. */ public int getIntColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return -1; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Integer)) - throw new IllegalArgumentException("Value is not an integer"); + throw new IllegalArgumentException("Value for " + column + " is not an integer"); return ((Integer) value).intValue(); } /** * Return the long value of column. * * If the column's type is not an long, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return The long value of the column, or -1 if the column * is an SQL null. */ public long getLongColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return -1; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Long)) throw new IllegalArgumentException("Value is not an long"); return ((Long) value).longValue(); } /** * Return the String value of column. * * If the column's type is not a String, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return The String value of the column, or null if the column * is an SQL null. */ public String getStringColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return null; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof String)) throw new IllegalArgumentException("Value is not an string"); return (String) value; } /** * Return the boolean value of column. * * If the column's type is not a boolean, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return The boolean value of the column, or false if the column * is an SQL null. */ public boolean getBooleanColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return false; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Boolean)) throw new IllegalArgumentException("Value is not a boolean"); return ((Boolean) value).booleanValue(); } /** * Return the date value of column. * * If the column's type is not a date, or the column does not * exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @return - The date value of the column, or null if the column * is an SQL null. */ public java.util.Date getDateColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return null; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof java.util.Date)) throw new IllegalArgumentException("Value is not a Date"); return (java.util.Date) value; } /** * Set column to an SQL NULL. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) */ public void setColumnNull(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); setColumnNullInternal(canonicalize(column)); } /** * Set column to the boolean b. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param b The boolean value */ public void setColumn(String column, boolean b) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); data.put(canonicalize(column), b ? Boolean.TRUE : Boolean.FALSE); } /** * Set column to the String s. * If s is null, the column is set to null. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param s The String value */ public void setColumn(String column, String s) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); data.put(canonicalize(column), s == null ? NULL_OBJECT : s); } /** * Set column to the integer i. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param i The integer value */ public void setColumn(String column, int i) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); data.put(canonicalize(column), new Integer(i)); } /** * Set column to the long l. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param l The long value */ public void setColumn(String column, long l) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); data.put(canonicalize(column), new Long(l)); } /** * Set column to the date d. If the date is null, the column is * set to NULL as well. * * If the column does not exist, an IllegalArgumentException is thrown. * * @param column The column name (case-insensitive) * @param d The date value */ public void setColumn(String column, java.util.Date d) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); if (d == null) { setColumnNull(canonicalize(column)); return; } data.put(canonicalize(column), d); } //////////////////////////////////////// // Utility methods //////////////////////////////////////// /** * Return a String representation of this object. */ public String toString() { final String NEWLINE = System.getProperty("line.separator"); StringBuffer result = new StringBuffer(table).append(NEWLINE); for (Iterator iterator = data.keySet().iterator(); iterator.hasNext(); ) { String column = (String) iterator.next(); result .append("\t") .append(column) .append(" = ") .append(isColumnNull(column) ? "NULL" : data.get(column)) .append(NEWLINE) ; } return result.toString(); } /** * Return a hash code for this object. */ public int hashCode() { return toString().hashCode(); } /** * Return true if this object equals obj, false otherwise. */ public boolean equals(Object obj) { if (! (obj instanceof TableRow)) return false; return data.equals(((TableRow) obj).data); } /** * Return the canonical name for column. * * @param column The name of the column. * @return The canonical name of the column. */ static String canonicalize(String column) { return column.toLowerCase(); } /** * Set columns to null. * * @param columns - A list of the columns to set to null. * Each element of the list is a String. */ private void nullColumns(List columns) { for (Iterator iterator = columns.iterator(); iterator.hasNext(); ) { setColumnNullInternal((String) iterator.next()); } } /** * Internal method to set column to null. * The public method ensures that column actually exists. */ private void setColumnNullInternal(String column) { data.put(canonicalize(column), NULL_OBJECT); } }
true
true
public int getIntColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return -1; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Integer)) throw new IllegalArgumentException("Value is not an integer"); return ((Integer) value).intValue(); }
public int getIntColumn(String column) { if (! hasColumn(column)) throw new IllegalArgumentException("No such column " + column); String name = canonicalize(column); if (isColumnNull(name)) return -1; Object value = data.get(name); if (value == null) throw new IllegalArgumentException("Column " + column + " not present"); if (!(value instanceof Integer)) throw new IllegalArgumentException("Value for " + column + " is not an integer"); return ((Integer) value).intValue(); }
diff --git a/Android/OpenMenu/src/com/net/rmopenmenu/LoadList.java b/Android/OpenMenu/src/com/net/rmopenmenu/LoadList.java index 4bf5f7d..6f41ee0 100644 --- a/Android/OpenMenu/src/com/net/rmopenmenu/LoadList.java +++ b/Android/OpenMenu/src/com/net/rmopenmenu/LoadList.java @@ -1,193 +1,193 @@ package com.net.rmopenmenu; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.widget.TabHost; import com.google.android.maps.GeoPoint; import com.net.rmopenmenu.SearchActivity.TabsAdapter; public class LoadList extends AsyncTask<String, Integer, Bundle> { private Context context; private boolean menu; private Activity activity; TabHost mTabHost; ViewPager mViewPager; TabsAdapter mTabsAdapter; public LoadList(Context context, boolean menu, Activity activity) { this.context = context; this.menu = menu; this.activity = activity; } @Override protected Bundle doInBackground(String... params) { return load(params[0]); } protected void onProgressUpdate(Integer... progress) { } protected void onPostExecute(Bundle b) { mTabHost = (TabHost)activity.findViewById(android.R.id.tabhost); mTabHost.setup(); mViewPager = (ViewPager)activity.findViewById(R.id.pager); mTabsAdapter = new TabsAdapter((FragmentActivity)activity, mTabHost, mViewPager); mTabsAdapter.addTab(mTabHost.newTabSpec("list").setIndicator("List"), SearchList.class, b); mTabsAdapter.addTab(mTabHost.newTabSpec("map").setIndicator("Map"), MapFragment.class, b); if (SearchActivity.savedInstanceState != null) { mTabHost.setCurrentTabByTag(SearchActivity.savedInstanceState.getString("tab")); } } public Bundle load(String query) { SQLiteDatabase db = new Database(context).getReadableDatabase(); ArrayList<Integer> item_ids = new ArrayList<Integer>(); ArrayList<String> restaurant_names = new ArrayList<String>(); ArrayList<Integer> restaurant_lats = new ArrayList<Integer>(); ArrayList<Integer> restaurant_lons = new ArrayList<Integer>(); ArrayList<String> restaurant_distances = new ArrayList<String>(); ArrayList<String> item_names = new ArrayList<String>(); ArrayList<String> item_prices = new ArrayList<String>(); ArrayList<String> item_descriptions = new ArrayList<String>(); ArrayList<Integer> item_vegs = new ArrayList<Integer>(); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); GeoPoint myLoc = new GeoPoint(prefs.getInt("lat", 47662150), prefs.getInt("lon", -122313237)); if (menu) { Cursor cursor = db.query("items", null, "name LIKE '%" + query + "%'", null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { item_ids.add(cursor.getInt(cursor.getColumnIndex("iid"))); item_names.add(cursor.getString(cursor.getColumnIndex("name"))); item_descriptions.add(cursor.getString(cursor.getColumnIndex("description"))); String price = cursor.getString(cursor.getColumnIndex("price")); if (price.equals("0.00")) { price = "Unknown Price"; } item_prices.add(price); item_vegs.add(cursor.getInt(cursor.getColumnIndex("veg"))); cursor.moveToNext(); } for (int i = 0; i < item_ids.size(); i++) { cursor = db.query("restaurants_items", null, "iid = " + item_ids.get(i), null, null, null, null); cursor.moveToFirst(); int rid = cursor.getInt(cursor.getColumnIndex("rid")); cursor = db.query("restaurants", null, "rid = " + rid, null, null, null, null); cursor.moveToFirst(); restaurant_names.add(cursor.getString(cursor.getColumnIndex("name"))); restaurant_lats.add(cursor.getInt(cursor.getColumnIndex("lat"))); restaurant_lons.add(cursor.getInt(cursor.getColumnIndex("lon"))); double distance = MapFragment.distanceBetween(myLoc, new GeoPoint(cursor.getInt(cursor.getColumnIndex("lat")), cursor.getInt(cursor.getColumnIndex("lon")))); restaurant_distances.add(String.format("%.1f", distance)); } } else { Cursor cursor = db.query("restaurants", null, "name LIKE '%" + query + "%'", null, null, null, null); cursor.moveToFirst(); int rid = cursor.getInt(cursor.getColumnIndex("rid")); String restaurant_name = cursor.getString(cursor.getColumnIndex("name")); int restaurant_lat = cursor.getInt(cursor.getColumnIndex("lat")); int restaurant_lon = cursor.getInt(cursor.getColumnIndex("lon")); double distance = MapFragment.distanceBetween(myLoc, new GeoPoint(restaurant_lat, restaurant_lon)); cursor = db.query("restaurants_items", null, "rid = " + rid, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { item_ids.add(cursor.getInt(cursor.getColumnIndex("iid"))); cursor.moveToNext(); } for (int i = 0; i < item_ids.size(); i++) { cursor = db.query("items", null, "iid = " + item_ids.get(i), null, null, null, null); cursor.moveToFirst(); restaurant_names.add(restaurant_name); restaurant_lats.add(restaurant_lat); restaurant_lons.add(restaurant_lon); restaurant_distances.add(String.format("%.1f", distance)); item_names.add(cursor.getString(cursor.getColumnIndex("name"))); String price = cursor.getString(cursor.getColumnIndex("price")); if (price.equals("0.00")) { price = "Unknown Price"; } item_prices.add(price); item_descriptions.add(cursor.getString(cursor.getColumnIndex("description"))); item_vegs.add(cursor.getInt(cursor.getColumnIndex("veg"))); } } - db.close(); + if (db != null) db.close(); Bundle b = new Bundle(); b.putString("query", query); b.putBoolean("menu", menu); b.putIntegerArrayList("item_ids", item_ids); b.putStringArrayList("restaurant_names", restaurant_names); b.putIntegerArrayList("restaurant_lats", restaurant_lats); b.putIntegerArrayList("restaurant_lons", restaurant_lons); b.putStringArrayList("restaurant_distances", restaurant_distances); b.putStringArrayList("item_names", item_names); b.putStringArrayList("item_prices", item_prices); b.putStringArrayList("item_descriptions", item_descriptions); b.putIntegerArrayList("item_vegs", item_vegs); ArrayList<Item> item_list = new ArrayList<Item>(); for (int i = 0; i < item_ids.size(); i++) { boolean mSort = (menu? prefs.getBoolean("sortPrice", false) : true); Item item = new Item(item_ids.get(i), restaurant_names.get(i), restaurant_lats.get(i), restaurant_lons.get(i), restaurant_distances.get(i), item_names.get(i), item_prices.get(i), item_descriptions.get(i), item_vegs.get(i), mSort); item_list.add(item); } Collections.sort(item_list); ArrayList<String> combined = new ArrayList<String>(); String thisName = ""; for (Iterator<Item> i = item_list.iterator(); i.hasNext();) { Item item = i.next(); if (!item.restaurant_name.equals(thisName)) { combined.add((combined.size() == 0? "" : "\n\n") + item.restaurant_name + "\n" + item.restaurant_distance + " mi.\n\n"); } combined.add(item.item_name + (item.item_description.equals("") ? "" : "\n" + item.item_description) + (item.item_price.equals("Unknown Price")? "" : "\n$" + item.item_price) + "\n" + (item.item_veg == 1? "We think this IS a vegetarian item" : "We think this is NOT a vegetarian item")); thisName = item.restaurant_name; } b.putStringArrayList("combined", combined); return b; } }
true
true
public Bundle load(String query) { SQLiteDatabase db = new Database(context).getReadableDatabase(); ArrayList<Integer> item_ids = new ArrayList<Integer>(); ArrayList<String> restaurant_names = new ArrayList<String>(); ArrayList<Integer> restaurant_lats = new ArrayList<Integer>(); ArrayList<Integer> restaurant_lons = new ArrayList<Integer>(); ArrayList<String> restaurant_distances = new ArrayList<String>(); ArrayList<String> item_names = new ArrayList<String>(); ArrayList<String> item_prices = new ArrayList<String>(); ArrayList<String> item_descriptions = new ArrayList<String>(); ArrayList<Integer> item_vegs = new ArrayList<Integer>(); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); GeoPoint myLoc = new GeoPoint(prefs.getInt("lat", 47662150), prefs.getInt("lon", -122313237)); if (menu) { Cursor cursor = db.query("items", null, "name LIKE '%" + query + "%'", null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { item_ids.add(cursor.getInt(cursor.getColumnIndex("iid"))); item_names.add(cursor.getString(cursor.getColumnIndex("name"))); item_descriptions.add(cursor.getString(cursor.getColumnIndex("description"))); String price = cursor.getString(cursor.getColumnIndex("price")); if (price.equals("0.00")) { price = "Unknown Price"; } item_prices.add(price); item_vegs.add(cursor.getInt(cursor.getColumnIndex("veg"))); cursor.moveToNext(); } for (int i = 0; i < item_ids.size(); i++) { cursor = db.query("restaurants_items", null, "iid = " + item_ids.get(i), null, null, null, null); cursor.moveToFirst(); int rid = cursor.getInt(cursor.getColumnIndex("rid")); cursor = db.query("restaurants", null, "rid = " + rid, null, null, null, null); cursor.moveToFirst(); restaurant_names.add(cursor.getString(cursor.getColumnIndex("name"))); restaurant_lats.add(cursor.getInt(cursor.getColumnIndex("lat"))); restaurant_lons.add(cursor.getInt(cursor.getColumnIndex("lon"))); double distance = MapFragment.distanceBetween(myLoc, new GeoPoint(cursor.getInt(cursor.getColumnIndex("lat")), cursor.getInt(cursor.getColumnIndex("lon")))); restaurant_distances.add(String.format("%.1f", distance)); } } else { Cursor cursor = db.query("restaurants", null, "name LIKE '%" + query + "%'", null, null, null, null); cursor.moveToFirst(); int rid = cursor.getInt(cursor.getColumnIndex("rid")); String restaurant_name = cursor.getString(cursor.getColumnIndex("name")); int restaurant_lat = cursor.getInt(cursor.getColumnIndex("lat")); int restaurant_lon = cursor.getInt(cursor.getColumnIndex("lon")); double distance = MapFragment.distanceBetween(myLoc, new GeoPoint(restaurant_lat, restaurant_lon)); cursor = db.query("restaurants_items", null, "rid = " + rid, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { item_ids.add(cursor.getInt(cursor.getColumnIndex("iid"))); cursor.moveToNext(); } for (int i = 0; i < item_ids.size(); i++) { cursor = db.query("items", null, "iid = " + item_ids.get(i), null, null, null, null); cursor.moveToFirst(); restaurant_names.add(restaurant_name); restaurant_lats.add(restaurant_lat); restaurant_lons.add(restaurant_lon); restaurant_distances.add(String.format("%.1f", distance)); item_names.add(cursor.getString(cursor.getColumnIndex("name"))); String price = cursor.getString(cursor.getColumnIndex("price")); if (price.equals("0.00")) { price = "Unknown Price"; } item_prices.add(price); item_descriptions.add(cursor.getString(cursor.getColumnIndex("description"))); item_vegs.add(cursor.getInt(cursor.getColumnIndex("veg"))); } } db.close(); Bundle b = new Bundle(); b.putString("query", query); b.putBoolean("menu", menu); b.putIntegerArrayList("item_ids", item_ids); b.putStringArrayList("restaurant_names", restaurant_names); b.putIntegerArrayList("restaurant_lats", restaurant_lats); b.putIntegerArrayList("restaurant_lons", restaurant_lons); b.putStringArrayList("restaurant_distances", restaurant_distances); b.putStringArrayList("item_names", item_names); b.putStringArrayList("item_prices", item_prices); b.putStringArrayList("item_descriptions", item_descriptions); b.putIntegerArrayList("item_vegs", item_vegs); ArrayList<Item> item_list = new ArrayList<Item>(); for (int i = 0; i < item_ids.size(); i++) { boolean mSort = (menu? prefs.getBoolean("sortPrice", false) : true); Item item = new Item(item_ids.get(i), restaurant_names.get(i), restaurant_lats.get(i), restaurant_lons.get(i), restaurant_distances.get(i), item_names.get(i), item_prices.get(i), item_descriptions.get(i), item_vegs.get(i), mSort); item_list.add(item); } Collections.sort(item_list); ArrayList<String> combined = new ArrayList<String>(); String thisName = ""; for (Iterator<Item> i = item_list.iterator(); i.hasNext();) { Item item = i.next(); if (!item.restaurant_name.equals(thisName)) { combined.add((combined.size() == 0? "" : "\n\n") + item.restaurant_name + "\n" + item.restaurant_distance + " mi.\n\n"); } combined.add(item.item_name + (item.item_description.equals("") ? "" : "\n" + item.item_description) + (item.item_price.equals("Unknown Price")? "" : "\n$" + item.item_price) + "\n" + (item.item_veg == 1? "We think this IS a vegetarian item" : "We think this is NOT a vegetarian item")); thisName = item.restaurant_name; } b.putStringArrayList("combined", combined); return b; }
public Bundle load(String query) { SQLiteDatabase db = new Database(context).getReadableDatabase(); ArrayList<Integer> item_ids = new ArrayList<Integer>(); ArrayList<String> restaurant_names = new ArrayList<String>(); ArrayList<Integer> restaurant_lats = new ArrayList<Integer>(); ArrayList<Integer> restaurant_lons = new ArrayList<Integer>(); ArrayList<String> restaurant_distances = new ArrayList<String>(); ArrayList<String> item_names = new ArrayList<String>(); ArrayList<String> item_prices = new ArrayList<String>(); ArrayList<String> item_descriptions = new ArrayList<String>(); ArrayList<Integer> item_vegs = new ArrayList<Integer>(); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); GeoPoint myLoc = new GeoPoint(prefs.getInt("lat", 47662150), prefs.getInt("lon", -122313237)); if (menu) { Cursor cursor = db.query("items", null, "name LIKE '%" + query + "%'", null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { item_ids.add(cursor.getInt(cursor.getColumnIndex("iid"))); item_names.add(cursor.getString(cursor.getColumnIndex("name"))); item_descriptions.add(cursor.getString(cursor.getColumnIndex("description"))); String price = cursor.getString(cursor.getColumnIndex("price")); if (price.equals("0.00")) { price = "Unknown Price"; } item_prices.add(price); item_vegs.add(cursor.getInt(cursor.getColumnIndex("veg"))); cursor.moveToNext(); } for (int i = 0; i < item_ids.size(); i++) { cursor = db.query("restaurants_items", null, "iid = " + item_ids.get(i), null, null, null, null); cursor.moveToFirst(); int rid = cursor.getInt(cursor.getColumnIndex("rid")); cursor = db.query("restaurants", null, "rid = " + rid, null, null, null, null); cursor.moveToFirst(); restaurant_names.add(cursor.getString(cursor.getColumnIndex("name"))); restaurant_lats.add(cursor.getInt(cursor.getColumnIndex("lat"))); restaurant_lons.add(cursor.getInt(cursor.getColumnIndex("lon"))); double distance = MapFragment.distanceBetween(myLoc, new GeoPoint(cursor.getInt(cursor.getColumnIndex("lat")), cursor.getInt(cursor.getColumnIndex("lon")))); restaurant_distances.add(String.format("%.1f", distance)); } } else { Cursor cursor = db.query("restaurants", null, "name LIKE '%" + query + "%'", null, null, null, null); cursor.moveToFirst(); int rid = cursor.getInt(cursor.getColumnIndex("rid")); String restaurant_name = cursor.getString(cursor.getColumnIndex("name")); int restaurant_lat = cursor.getInt(cursor.getColumnIndex("lat")); int restaurant_lon = cursor.getInt(cursor.getColumnIndex("lon")); double distance = MapFragment.distanceBetween(myLoc, new GeoPoint(restaurant_lat, restaurant_lon)); cursor = db.query("restaurants_items", null, "rid = " + rid, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { item_ids.add(cursor.getInt(cursor.getColumnIndex("iid"))); cursor.moveToNext(); } for (int i = 0; i < item_ids.size(); i++) { cursor = db.query("items", null, "iid = " + item_ids.get(i), null, null, null, null); cursor.moveToFirst(); restaurant_names.add(restaurant_name); restaurant_lats.add(restaurant_lat); restaurant_lons.add(restaurant_lon); restaurant_distances.add(String.format("%.1f", distance)); item_names.add(cursor.getString(cursor.getColumnIndex("name"))); String price = cursor.getString(cursor.getColumnIndex("price")); if (price.equals("0.00")) { price = "Unknown Price"; } item_prices.add(price); item_descriptions.add(cursor.getString(cursor.getColumnIndex("description"))); item_vegs.add(cursor.getInt(cursor.getColumnIndex("veg"))); } } if (db != null) db.close(); Bundle b = new Bundle(); b.putString("query", query); b.putBoolean("menu", menu); b.putIntegerArrayList("item_ids", item_ids); b.putStringArrayList("restaurant_names", restaurant_names); b.putIntegerArrayList("restaurant_lats", restaurant_lats); b.putIntegerArrayList("restaurant_lons", restaurant_lons); b.putStringArrayList("restaurant_distances", restaurant_distances); b.putStringArrayList("item_names", item_names); b.putStringArrayList("item_prices", item_prices); b.putStringArrayList("item_descriptions", item_descriptions); b.putIntegerArrayList("item_vegs", item_vegs); ArrayList<Item> item_list = new ArrayList<Item>(); for (int i = 0; i < item_ids.size(); i++) { boolean mSort = (menu? prefs.getBoolean("sortPrice", false) : true); Item item = new Item(item_ids.get(i), restaurant_names.get(i), restaurant_lats.get(i), restaurant_lons.get(i), restaurant_distances.get(i), item_names.get(i), item_prices.get(i), item_descriptions.get(i), item_vegs.get(i), mSort); item_list.add(item); } Collections.sort(item_list); ArrayList<String> combined = new ArrayList<String>(); String thisName = ""; for (Iterator<Item> i = item_list.iterator(); i.hasNext();) { Item item = i.next(); if (!item.restaurant_name.equals(thisName)) { combined.add((combined.size() == 0? "" : "\n\n") + item.restaurant_name + "\n" + item.restaurant_distance + " mi.\n\n"); } combined.add(item.item_name + (item.item_description.equals("") ? "" : "\n" + item.item_description) + (item.item_price.equals("Unknown Price")? "" : "\n$" + item.item_price) + "\n" + (item.item_veg == 1? "We think this IS a vegetarian item" : "We think this is NOT a vegetarian item")); thisName = item.restaurant_name; } b.putStringArrayList("combined", combined); return b; }
diff --git a/Common/src/main/java/au/gov/ga/worldwind/common/view/rotate/FreeRotateOrbitViewInputHandler.java b/Common/src/main/java/au/gov/ga/worldwind/common/view/rotate/FreeRotateOrbitViewInputHandler.java index adb79824..2381e402 100644 --- a/Common/src/main/java/au/gov/ga/worldwind/common/view/rotate/FreeRotateOrbitViewInputHandler.java +++ b/Common/src/main/java/au/gov/ga/worldwind/common/view/rotate/FreeRotateOrbitViewInputHandler.java @@ -1,131 +1,131 @@ /******************************************************************************* * Copyright 2012 Geoscience Australia * * 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 au.gov.ga.worldwind.common.view.rotate; import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.awt.ViewInputAttributes.ActionAttributes; import gov.nasa.worldwind.awt.ViewInputAttributes.DeviceAttributes; import gov.nasa.worldwind.geom.Angle; import gov.nasa.worldwind.geom.Matrix; import gov.nasa.worldwind.geom.Position; import gov.nasa.worldwind.geom.Vec4; import gov.nasa.worldwind.globes.Globe; import gov.nasa.worldwind.util.Logging; import gov.nasa.worldwind.view.ViewUtil; import gov.nasa.worldwind.view.orbit.BasicOrbitView; import gov.nasa.worldwind.view.orbit.OrbitView; import gov.nasa.worldwind.view.orbit.OrbitViewInputHandler; import au.gov.ga.worldwind.common.view.transform.TransformView; /** * {@link OrbitViewInputHandler} subclass that adds support for free rotation of * the globe (without it being fixed around the north-south axis). * * @author Michael de Hoog ([email protected]) */ public class FreeRotateOrbitViewInputHandler extends OrbitViewInputHandler { /** * Rotate the globe by an amount in a given direction. * * @param direction * Direction to rotate * @param amount * Amount to rotate * @param deviceAttributes * @param actionAttributes */ public void onRotateFree(Angle direction, Angle amount, DeviceAttributes deviceAttributes, ActionAttributes actionAttributes) { if (!(getView() instanceof OrbitView)) { String message = "View must be an instance of OrbitView"; Logging.logger().severe(message); throw new IllegalStateException(message); } amount = Angle.fromDegrees(amount.degrees * getScaleValueHorizTransRel(deviceAttributes, actionAttributes)); OrbitView view = (OrbitView) getView(); //if this view hasn't been applied yet, its globe will be null if (view.getGlobe() == null) { return; } //backup the pitch (set it later so it isn't changed by this method) Angle pitch = view.getPitch(); //get the eye point and normalize it Vec4 centerPoint = view.getCenterPoint(); Vec4 centerPointNormalized = centerPoint.normalize3(); //find the current left vector Matrix modelview = view.getModelviewMatrix(); Matrix modelviewInv = modelview.getInverse(); Vec4 left = Vec4.UNIT_X.transformBy4(modelviewInv); //rotate the left vector around the forward vector Matrix translationRotation = Matrix.fromAxisAngle(direction, centerPointNormalized); Vec4 leftRotated = left.transformBy4(translationRotation); //calculate the new eye point by rotating it around the rotated left vector Matrix rotation = Matrix.fromAxisAngle(amount, leftRotated); Vec4 newCenterPoint = centerPoint.transformBy4(rotation); //calculate the new eye position Position newCenterPosition = view.getGlobe().computePositionFromPoint(newCenterPoint); view.setCenterPosition(newCenterPosition); //compute the new heading if (view instanceof TransformView) { modelview = ((TransformView) view).getPretransformedModelViewMatrix(); } Matrix newModelview = modelview.multiply(rotation); Angle newHeading = calculateHeading(view, newModelview); view.setHeading(newHeading); view.setPitch(pitch); if (view instanceof BasicOrbitView) { - ((BasicOrbitView) view).setViewOutOfFocus(true); + ((BasicOrbitView) view).computeAndSetViewCenter(); } view.firePropertyChange(AVKey.VIEW, null, view); } protected Angle calculateHeading(OrbitView view, Matrix modelview) { Globe globe = view.getGlobe(); Position center = view.getCenterPosition(); Vec4 centerPoint = globe.computePointFromPosition(center); Vec4 normal = globe.computeSurfaceNormalAtLocation(center.getLatitude(), center.getLongitude()); Vec4 lookAtPoint = centerPoint.subtract3(normal); Vec4 north = globe.computeNorthPointingTangentAtLocation(center.getLatitude(), center.getLongitude()); Matrix centerTransform = Matrix.fromViewLookAt(centerPoint, lookAtPoint, north); Matrix centerTransformInv = centerTransform.getInverse(); if (centerTransformInv == null) { String message = Logging.getMessage("generic.NoninvertibleMatrix"); Logging.logger().severe(message); throw new IllegalStateException(message); } Matrix hpzTransform = modelview.multiply(centerTransformInv); return ViewUtil.computeHeading(hpzTransform); } }
true
true
public void onRotateFree(Angle direction, Angle amount, DeviceAttributes deviceAttributes, ActionAttributes actionAttributes) { if (!(getView() instanceof OrbitView)) { String message = "View must be an instance of OrbitView"; Logging.logger().severe(message); throw new IllegalStateException(message); } amount = Angle.fromDegrees(amount.degrees * getScaleValueHorizTransRel(deviceAttributes, actionAttributes)); OrbitView view = (OrbitView) getView(); //if this view hasn't been applied yet, its globe will be null if (view.getGlobe() == null) { return; } //backup the pitch (set it later so it isn't changed by this method) Angle pitch = view.getPitch(); //get the eye point and normalize it Vec4 centerPoint = view.getCenterPoint(); Vec4 centerPointNormalized = centerPoint.normalize3(); //find the current left vector Matrix modelview = view.getModelviewMatrix(); Matrix modelviewInv = modelview.getInverse(); Vec4 left = Vec4.UNIT_X.transformBy4(modelviewInv); //rotate the left vector around the forward vector Matrix translationRotation = Matrix.fromAxisAngle(direction, centerPointNormalized); Vec4 leftRotated = left.transformBy4(translationRotation); //calculate the new eye point by rotating it around the rotated left vector Matrix rotation = Matrix.fromAxisAngle(amount, leftRotated); Vec4 newCenterPoint = centerPoint.transformBy4(rotation); //calculate the new eye position Position newCenterPosition = view.getGlobe().computePositionFromPoint(newCenterPoint); view.setCenterPosition(newCenterPosition); //compute the new heading if (view instanceof TransformView) { modelview = ((TransformView) view).getPretransformedModelViewMatrix(); } Matrix newModelview = modelview.multiply(rotation); Angle newHeading = calculateHeading(view, newModelview); view.setHeading(newHeading); view.setPitch(pitch); if (view instanceof BasicOrbitView) { ((BasicOrbitView) view).setViewOutOfFocus(true); } view.firePropertyChange(AVKey.VIEW, null, view); }
public void onRotateFree(Angle direction, Angle amount, DeviceAttributes deviceAttributes, ActionAttributes actionAttributes) { if (!(getView() instanceof OrbitView)) { String message = "View must be an instance of OrbitView"; Logging.logger().severe(message); throw new IllegalStateException(message); } amount = Angle.fromDegrees(amount.degrees * getScaleValueHorizTransRel(deviceAttributes, actionAttributes)); OrbitView view = (OrbitView) getView(); //if this view hasn't been applied yet, its globe will be null if (view.getGlobe() == null) { return; } //backup the pitch (set it later so it isn't changed by this method) Angle pitch = view.getPitch(); //get the eye point and normalize it Vec4 centerPoint = view.getCenterPoint(); Vec4 centerPointNormalized = centerPoint.normalize3(); //find the current left vector Matrix modelview = view.getModelviewMatrix(); Matrix modelviewInv = modelview.getInverse(); Vec4 left = Vec4.UNIT_X.transformBy4(modelviewInv); //rotate the left vector around the forward vector Matrix translationRotation = Matrix.fromAxisAngle(direction, centerPointNormalized); Vec4 leftRotated = left.transformBy4(translationRotation); //calculate the new eye point by rotating it around the rotated left vector Matrix rotation = Matrix.fromAxisAngle(amount, leftRotated); Vec4 newCenterPoint = centerPoint.transformBy4(rotation); //calculate the new eye position Position newCenterPosition = view.getGlobe().computePositionFromPoint(newCenterPoint); view.setCenterPosition(newCenterPosition); //compute the new heading if (view instanceof TransformView) { modelview = ((TransformView) view).getPretransformedModelViewMatrix(); } Matrix newModelview = modelview.multiply(rotation); Angle newHeading = calculateHeading(view, newModelview); view.setHeading(newHeading); view.setPitch(pitch); if (view instanceof BasicOrbitView) { ((BasicOrbitView) view).computeAndSetViewCenter(); } view.firePropertyChange(AVKey.VIEW, null, view); }
diff --git a/rio-services/cybernode/cybernode-service/src/main/java/org/rioproject/cybernode/CybernodeImpl.java b/rio-services/cybernode/cybernode-service/src/main/java/org/rioproject/cybernode/CybernodeImpl.java index 03660166..16769cab 100644 --- a/rio-services/cybernode/cybernode-service/src/main/java/org/rioproject/cybernode/CybernodeImpl.java +++ b/rio-services/cybernode/cybernode-service/src/main/java/org/rioproject/cybernode/CybernodeImpl.java @@ -1,1500 +1,1500 @@ /* * Copyright to the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rioproject.cybernode; import com.sun.jini.config.Config; import com.sun.jini.reliableLog.LogHandler; import com.sun.jini.start.LifeCycle; import net.jini.config.Configuration; import net.jini.config.ConfigurationException; import net.jini.core.entry.Entry; import net.jini.core.event.UnknownEventException; import net.jini.core.lookup.ServiceID; import net.jini.discovery.LookupDiscovery; import net.jini.export.Exporter; import net.jini.id.Uuid; import net.jini.io.MarshalledInstance; import net.jini.lookup.entry.ServiceInfo; import net.jini.lookup.entry.StatusType; import net.jini.lookup.ui.AdminUI; import net.jini.security.BasicProxyPreparer; import net.jini.security.ProxyPreparer; import net.jini.security.TrustVerifier; import net.jini.security.proxytrust.ServerProxyTrust; import org.rioproject.RioVersion; import org.rioproject.config.Constants; import org.rioproject.core.jsb.DiscardManager; import org.rioproject.core.jsb.ServiceBeanContext; import org.rioproject.core.jsb.ServiceBeanManager; import org.rioproject.deploy.*; import org.rioproject.entry.BasicStatus; import org.rioproject.entry.UIDescriptorFactory; import org.rioproject.event.EventDescriptor; import org.rioproject.jmx.JMXUtil; import org.rioproject.jmx.MBeanServerFactory; import org.rioproject.jsb.JSBManager; import org.rioproject.jsb.ServiceBeanActivation; import org.rioproject.jsb.ServiceBeanActivation.LifeCycleManager; import org.rioproject.jsb.ServiceBeanAdapter; import org.rioproject.net.HostUtil; import org.rioproject.opstring.*; import org.rioproject.resources.client.DiscoveryManagementPool; import org.rioproject.resources.persistence.PersistentStore; import org.rioproject.resources.persistence.SnapshotHandler; import org.rioproject.resources.util.ThrowableUtil; import org.rioproject.serviceui.UIComponentFactory; import org.rioproject.sla.SLA; import org.rioproject.sla.SLAThresholdEvent; import org.rioproject.system.ComputeResource; import org.rioproject.system.ComputeResourceUtilization; import org.rioproject.system.SystemCapabilities; import org.rioproject.system.capability.PlatformCapability; import org.rioproject.system.measurable.MeasurableCapability; import org.rioproject.util.BannerProvider; import org.rioproject.util.BannerProviderImpl; import org.rioproject.util.RioManifest; import org.rioproject.util.TimeUtil; import org.rioproject.watch.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.management.*; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.rmi.AccessException; import java.rmi.AlreadyBoundException; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.text.NumberFormat; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; /** * Implementation of a Cybernode * * @link {org.rioproject.jmx.ThreadDeadlockMonitor#ID} * * @author Dennis Reedy */ @SuppressWarnings("unused") public class CybernodeImpl extends ServiceBeanAdapter implements Cybernode, ServiceBeanContainerListener, CybernodeImplMBean, ServerProxyTrust { /** Component name we use to find items in the Configuration */ private static final String RIO_CONFIG_COMPONENT = "org.rioproject"; /** Component name we use to find items in the Configuration */ private static final String CONFIG_COMPONENT = RIO_CONFIG_COMPONENT+".cybernode"; /** Default Exporter attribute */ private static final String DEFAULT_EXPORTER = "defaultExporter"; /** Logger name */ private static final String LOGGER = CybernodeImpl.class.getName(); /** Cybernode logger. */ private static final Logger logger = LoggerFactory.getLogger(LOGGER); /** Cybernode logger. */ private static final Logger loaderLogger = LoggerFactory.getLogger(LOGGER+".loader"); /**The component name for accessing the service's configuration */ private static String configComponent = CONFIG_COMPONENT; /** Instance of a ServiceBeanContainer */ private ServiceBeanContainer container; /** If the Cybernode has been configured an an instantiation resource, and * the Cybernode removes itself as an asset, this property determines whether * instantiated services should be terminated upon unregistration */ private boolean serviceTerminationOnUnregister=true; /** default maximum service limit */ private int serviceLimit=500; /** Service consumer responsible for Provision Monitor discovery and registration */ private ServiceConsumer svcConsumer=null; /** Flag indicating the Cybernode is in shutdown sequence */ private final AtomicBoolean shutdownSequence= new AtomicBoolean(false); /** Collection of services that are in the process of instantiation */ private final List<ServiceProvisionEvent> inProcess = new ArrayList<ServiceProvisionEvent>(); /** Log format version */ private static final int LOG_VERSION = 1; /** PersistentStore to save state */ //PersistentStore store; /** ThreadPool for SLAThresholdEvent processing */ private Executor thresholdTaskPool; private ComputeResourcePolicyHandler computeResourcePolicyHandler; /** This flag indicates whether the Cybernode has been configured to install * external software defined by ServiceBean instances */ private boolean provisionEnabled=true; /** The ServiceStatementManager defines the semantics of reading/writing * ServiceStatement instances */ private ServiceStatementManager serviceStatementManager; /** The Timer to use for scheduling a ServiceRecord update task */ private Timer taskTimer; /** The Configuration for the Service */ private Configuration config; /** ProxyPreparer for the OperationalStringMonitor */ private ProxyPreparer operationalStringManagerPreparer; private LifeCycle lifeCycle; /** Flag to indicate if the Cybernode is enlisted */ private boolean enlisted=false; private ServiceRecordUpdateTask serviceRecordUpdateTask; private int registryPort; private String instantiatorID; /** * Create a Cybernode */ public CybernodeImpl() { super(); } /** * Create a Cybernode launched from the ServiceStarter framework * * @param configArgs Configuration arguments * @param lifeCycle The LifeCycle object that started the Cybernode * * @throws Exception if bootstrapping fails */ public CybernodeImpl(String[] configArgs, LifeCycle lifeCycle) throws Exception { super(); this.lifeCycle = lifeCycle; bootstrap(configArgs); } @Override public void destroy() { super.destroy(); } /** * Override destroy to ensure that any JSBs are shutdown as well */ public void destroy(boolean force) { if(shutdownSequence.get()) return; synchronized(CybernodeImpl.class) { if(serviceRecordUpdateTask!=null) serviceRecordUpdateTask.cancel(); shutdownSequence.set(true); if(computeResourcePolicyHandler!=null) { computeResourcePolicyHandler.terminate(); } /* Shutdown the ComputeResource */ if(computeResource!=null) computeResource.shutdown(); /* Stop the consumer */ if(svcConsumer != null) svcConsumer.destroy(); } svcConsumer = null; /* Destroy the container */ if(container != null) container.terminate(); /* If we have a store, destroy it */ if(snapshotter!=null) snapshotter.interrupt(); if(store!=null) { try { store.destroy(); } catch(Exception e) { logger.error("While destroying persistent store", e); } } logger.info("{}: destroy() notification", context.getServiceElement().getName()); /* Stop the timer */ if(taskTimer!=null) taskTimer.cancel(); try { unadvertise(); } catch (IOException e) { logger.warn("While unadvertising", e); } stop(force); /* Terminate the ServiceStatementManager */ if(serviceStatementManager!=null) serviceStatementManager.terminate(); /* Close down all WatchDataSource instances, unexporting them from * the runtime */ destroyWatches(); /* Unregister all PlatformCapability instances */ if(computeResource!=null) { PlatformCapability[] pCaps = computeResource.getPlatformCapabilities(); for (PlatformCapability pCap : pCaps) { try { ObjectName objectName = getObjectName(pCap); MBeanServerFactory.getMBeanServer().unregisterMBean(objectName); } catch (Exception e) { Throwable cause = ThrowableUtil.getRootCause(e); logger.warn("Unregistering PlatformCapability [{}], Exception: {}", pCap.getName(), cause.getClass().getName()); } } } /* Terminate the DiscoveryManagementPool */ DiscoveryManagementPool discoPool = DiscoveryManagementPool.getInstance(); if(discoPool!=null) discoPool.terminate(); /* Tell the utility that started the Cybernode we are going away */ ServiceBeanManager serviceBeanManager = context.getServiceBeanManager(); if(serviceBeanManager!=null) { DiscardManager discardMgr = serviceBeanManager.getDiscardManager(); if(discardMgr!=null) { discardMgr.discard(); } } else { if(lifeCycle!=null) { lifeCycle.unregister(this); } } container = null; } /** * Override parent's method to return <code>TrustVerifier</code> which can * be used to verify that the given proxy to this service can be trusted * * @return TrustVerifier The TrustVerifier used to verify the proxy * */ public TrustVerifier getProxyVerifier() { return (new CybernodeProxy.Verifier(getExportedProxy())); } /** * @see org.rioproject.deploy.ServiceBeanInstantiator#getServiceStatements */ public ServiceStatement[] getServiceStatements() { return(serviceStatementManager.get()); } /** * @see org.rioproject.deploy.ServiceBeanInstantiator#getServiceRecords */ public ServiceRecord[] getServiceRecords(int filter) { Set<ServiceRecord> recordSet = new HashSet<ServiceRecord>(); ServiceStatement[] statements = serviceStatementManager.get(); for (ServiceStatement statement : statements) { ServiceRecord[] records = statement.getServiceRecords(getUuid(), filter); recordSet.addAll(Arrays.asList(records)); } if(logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); int i=1; for(ServiceRecord record : recordSet) { if(sb.length()>0) { sb.append("\n"); } sb.append(String.format("%2d. %-40s instance:%-3d %s", i++, CybernodeLogUtil.simpleLogName(record.getServiceElement()), record.getServiceElement().getServiceBeanConfig().getInstanceID(), record.getServiceID().toString())); } String newLine = recordSet.isEmpty()?"":"\n"; String type = filter==ServiceRecord.ACTIVE_SERVICE_RECORD?"ACTIVE_SERVICE_RECORD":"INACTIVE_SERVICE_RECORD"; logger.debug("Returning ({}) {} ServiceRecords{}{}", recordSet.size(), type, newLine, sb.toString()); } return(recordSet.toArray(new ServiceRecord[recordSet.size()])); } /** * @see org.rioproject.deploy.ServiceBeanInstantiator#getServiceStatement */ public ServiceStatement getServiceStatement(ServiceElement elem) { if(elem==null) throw new IllegalArgumentException("ServiceElement is null"); return serviceStatementManager.get(elem); } /** * @see org.rioproject.deploy.ServiceBeanInstantiator#getServiceBeanInstances */ public ServiceBeanInstance[] getServiceBeanInstances(ServiceElement element) { ServiceBeanInstance[] sbi = container.getServiceBeanInstances(element); if(logger.isTraceEnabled()) logger.trace("ServiceBeanInstance count for [{}] = {}", element.getName(), sbi.length); return (sbi); } /** * @see org.rioproject.deploy.ServiceBeanInstantiator#update */ public void update(ServiceElement[] sElements, OperationalStringManager opStringMgr) throws RemoteException { OperationalStringManager preparedOpStringMgr = (OperationalStringManager)operationalStringManagerPreparer.prepareProxy(opStringMgr); if(logger.isTraceEnabled()) logger.trace("Prepared OperationalStringManager proxy: {}", preparedOpStringMgr.toString()); container.update(sElements, preparedOpStringMgr); } /** * @see org.rioproject.deploy.ServiceBeanInstantiator#getName() */ public String getName() { return instantiatorID; } /** * Implemented to support interface contract. The CybernodeProxy returns * the result of this method without a backend invocation. For completeness * this method will return the Uuid as well * * @see org.rioproject.deploy.ServiceBeanInstantiator#getInstantiatorUuid() */ public Uuid getInstantiatorUuid() { return(getUuid()); } public InetAddress getInetAddress() { return getComputeResource().getAddress(); } /** * Notification that a ServiceBean has been instantiated * * @param serviceRecord The ServiceRecord */ public void serviceInstantiated(ServiceRecord serviceRecord) { ServiceStatement statement = serviceStatementManager.get(serviceRecord.getServiceElement()); if(statement==null) { /* ServiceStatement not found, create one */ statement = new ServiceStatement(serviceRecord.getServiceElement()); } statement.putServiceRecord(getUuid(), serviceRecord); serviceStatementManager.record(statement); //setChanged(StatusType.NORMAL); if(loaderLogger.isInfoEnabled()) { int instantiatedServiceCount = getInstantiatedServiceCount(); ServiceElement service = serviceRecord.getServiceElement(); logger.info("Instantiated {}, {}, total services active: {}", CybernodeLogUtil.logName(service), CybernodeLogUtil.discoveryInfo(service), instantiatedServiceCount); } } /** * Notification that a ServiceBean has been discarded * * @param serviceRecord The ServiceRecord */ public void serviceDiscarded(ServiceRecord serviceRecord) { if(serviceRecord==null) logger.warn("ServiceRecord is null when discarding ServiceBean"); else { ServiceStatement statement = serviceStatementManager.get(serviceRecord.getServiceElement()); if(statement!=null) { if(serviceRecord.getType()!=ServiceRecord.INACTIVE_SERVICE_RECORD) { serviceRecord.setType(ServiceRecord.INACTIVE_SERVICE_RECORD); logger.warn("Fixing ServiceRecord for {}, notified as being discarded, but has ServiceRecord.ACTIVE_SERVICE_RECORD", CybernodeLogUtil.logName(serviceRecord.getServiceElement())); } statement.putServiceRecord(getUuid(), serviceRecord); serviceStatementManager.record(statement); if(loaderLogger.isInfoEnabled()) { int instantiatedServiceCount = getInstantiatedServiceCount(); loaderLogger.info("Discarded {}, total services active: {}", CybernodeLogUtil.logName(serviceRecord.getServiceElement()), instantiatedServiceCount); } } else { loaderLogger.warn("ServiceStatement is null when discarding ServiceBean {}", CybernodeLogUtil.logName(serviceRecord.getServiceElement())); } //setChanged(StatusType.NORMAL); } } private int getInstantiatedServiceCount() { int instantiatedServiceCount = 0; ServiceRecord[] records = container.getServiceRecords(); for (ServiceRecord record : records) { if (record.getType() == ServiceRecord.ACTIVE_SERVICE_RECORD) instantiatedServiceCount++; } return instantiatedServiceCount; } /* * Get the ServiceBeanContext and bootstrap the Cybernode */ private void bootstrap(String[] configArgs) throws Exception { context = ServiceBeanActivation.getServiceBeanContext(getConfigComponent(), "Cybernode", configArgs, getClass().getClassLoader()); BannerProvider bannerProvider = (BannerProvider)context.getConfiguration().getEntry(getConfigComponent(), "bannerProvider", BannerProvider.class, new BannerProviderImpl()); logger.info(bannerProvider.getBanner(context.getServiceElement().getName())); try { start(context); LifeCycleManager lMgr = (LifeCycleManager)context. getServiceBeanManager().getDiscardManager(); lMgr.register(getServiceProxy(), context); } catch(Exception e) { logger.error("Register to LifeCycleManager", e); throw e; } } /** * Get the component name to use for accessing the services configuration * properties * * @return The component name */ public static String getConfigComponent() { return(configComponent); } /** * Set the component name to use for accessing the services configuration * properties * * @param comp The component name */ protected void setConfigComponent(String comp) { if(comp!=null) configComponent = comp; } /** * Override ServiceBeanAdapter createProxy to return a Cybernode Proxy */ @Override protected Object createProxy() { Cybernode cybernode = (Cybernode)getExportedProxy(); if(cybernode==null) { logger.error("Could not get the exported proxy for the Cybernode, " + "returning null. The Cybernode will not be able to " + "accept remote inbound communications"); return null; } Object proxy = CybernodeProxy.getInstance(cybernode, getUuid()); /* Get the registry port */ String sPort = System.getProperty(Constants.REGISTRY_PORT, "0"); registryPort = Integer.parseInt(sPort); String name = context.getServiceBeanConfig().getName(); if(registryPort!=0) { try { String address = HostUtil.getHostAddressFromProperty(Constants.RMI_HOST_ADDRESS); Registry registry = LocateRegistry.getRegistry(address, registryPort); try { registry.bind(name, (Remote)proxy); logger.debug("Bound to RMI Registry on port={}", registryPort); } catch(AlreadyBoundException e) { /*ignore */ } } catch(AccessException e) { logger.warn("Binding "+name+" to RMI Registry", e); } catch(RemoteException e) { logger.warn("Binding "+name+" to RMI Registry", e); } catch (java.net.UnknownHostException e) { logger.warn("Unknown host address locating RMI Registry", e); } } else { if(logger.isDebugEnabled()) logger.debug("RMI Registry property not set, unable to bind {}", name); } /* * Set the MarshalledInstance into the ServiceBeanManager */ try { MarshalledInstance mi = new MarshalledInstance(proxy); ((JSBManager)context.getServiceBeanManager()).setMarshalledInstance(mi); } catch (IOException e) { logger.warn("Unable to create MarshalledInstance for Cybernode proxy, non-fatal error, continuing ...", e); } return(proxy); } /** * Override parent's getAdmin to return custom service admin * * @return A CybernodeAdminProxy instance */ public Object getAdmin() { Object adminProxy = null; try { if(admin == null) { Exporter adminExporter = getAdminExporter(); if (contextMgr != null) admin = new CybernodeAdminImpl(this, adminExporter, contextMgr.getContextAttributeLogHandler()); else admin = new CybernodeAdminImpl(this, adminExporter); } admin.setServiceBeanContext(getServiceBeanContext()); ((CybernodeAdminImpl)admin).setRegistryPort(registryPort); adminProxy = admin.getServiceAdmin(); } catch (Throwable t) { logger.error("Getting CybernodeAdminImpl", t); } return (adminProxy); } /** * @see org.rioproject.core.jsb.ServiceBean#initialize */ public void initialize(ServiceBeanContext context) throws Exception { /* * Create the instantiatorID. This will be used as the name set in the proxy, and used to track * registrations and updates in the ProvisionMonitor */ StringBuilder instantiatorIDBuilder = new StringBuilder(); instantiatorIDBuilder.append(context.getServiceElement().getName()).append("-"); String name = ManagementFactory.getRuntimeMXBean().getName(); String pid = name; int ndx = name.indexOf("@"); if(ndx>=1) { pid = name.substring(0, ndx); } instantiatorIDBuilder.append(pid).append("@"); instantiatorIDBuilder.append(HostUtil.getHostAddressFromProperty(Constants.RMI_HOST_ADDRESS)); instantiatorID = instantiatorIDBuilder.toString(); /* * Determine if a log directory has been provided. If so, create a * PersistentStore */ String logDirName = (String)context.getConfiguration().getEntry(CONFIG_COMPONENT, "logDirectory", String.class, null); if(logDirName!=null) { /* LogHandler required when dealing with the ReliableLog */ CybernodeLogHandler logHandler = new CybernodeLogHandler(); store = new PersistentStore(logDirName, logHandler, logHandler); if(logger.isDebugEnabled()) logger.debug("Cybernode: using absolute logdir path [{}]", store.getStoreLocation()); store.snapshot(); super.initialize(context, store); } else { super.initialize(context); } /* Get the Configuration */ config = context.getConfiguration(); try { Exporter defaultExporter = (Exporter)config.getEntry(RIO_CONFIG_COMPONENT, DEFAULT_EXPORTER, Exporter.class); logger.trace("{} has been set as the defaultExporter", defaultExporter); } catch(Exception e) { logger.error("The {}.{} attribute must be set", RIO_CONFIG_COMPONENT, DEFAULT_EXPORTER); throw e; } /* Set up thread deadlock detection. This seems a little clumsy to use * the WatchInjector and could probably be improved. This does make the * most use of the wiring for forked service monitoring. */ long threadDeadlockCheck = (Long)config.getEntry(CONFIG_COMPONENT, "threadDeadlockCheck", long.class, (long)5000); if(threadDeadlockCheck>=1000) { WatchDescriptor threadDeadlockDescriptor = ThreadDeadlockMonitor.getWatchDescriptor(); threadDeadlockDescriptor.setPeriod(threadDeadlockCheck); Method getThreadDeadlockCalculable = ThreadDeadlockMonitor.class.getMethod("getThreadDeadlockCalculable"); ThreadDeadlockMonitor threadDeadlockMonitor = new ThreadDeadlockMonitor(); threadDeadlockMonitor.setThreadMXBean(ManagementFactory.getThreadMXBean()); WatchInjector watchInjector = new WatchInjector(this, context); ThresholdWatch watch = (ThresholdWatch)watchInjector.inject(threadDeadlockDescriptor, threadDeadlockMonitor, getThreadDeadlockCalculable); watch.setThresholdValues(new ThresholdValues(0, 1)); watch.addThresholdListener(new DeadlockedThreadPolicyHandler()); } else { logger.info("Thread deadlock monitoring has been disabled. The " + "configured thread deadlock check time was " + "[{}]. To enable thread deadlock monitoring, the thread deadlock check " + "time must be >= 1000 milliseconds.", threadDeadlockCheck); } try { serviceLimit = Config.getIntEntry(config, getConfigComponent(), "serviceLimit", 500, 0, Integer.MAX_VALUE); } catch(Exception e) { logger.warn("Exception getting serviceLimit, default to 500"); } /* Get the ProxyPreparer for passed in OperationalStringManager * instances */ operationalStringManagerPreparer = (ProxyPreparer)config.getEntry(getConfigComponent(), "operationalStringManagerPreparer", ProxyPreparer.class, new BasicProxyPreparer()); /* Check for JMXConnection */ addAttributes(JMXUtil.getJMXConnectionEntries(config)); /* Add service UIs programmatically */ addAttributes(getServiceUIs()); /* Get the security policy to apply to loading services */ String serviceSecurityPolicy = (String)config.getEntry(getConfigComponent(), "serviceSecurityPolicy", String.class, null); if(serviceSecurityPolicy!=null) System.setProperty("rio.service.security.policy", serviceSecurityPolicy); /* Establish default operating environment */ Environment.setupDefaultEnvironment(); /* Setup persistent provisioning attributes */ provisionEnabled = (Boolean) config.getEntry(getConfigComponent(), "provisionEnabled", Boolean.class, true); /* * The directory to provision external software to. This is the root * directory where software may be installed by ServiceBean instances which * require external software to be resident on compute resource the * Cybernode represents */ String provisionRoot = Environment.setupProvisionRoot(provisionEnabled, config); if(provisionEnabled) { logger.debug("Software provisioning has been enabled, default provision root location is [{}]", provisionRoot); } computeResource.setPersistentProvisioningRoot(provisionRoot); /* Setup the native library directory */ String nativeLibDirectories = Environment.setupNativeLibraryDirectories(config); /* Ensure org.rioproject.system.native property is set. This will be used * by the org.rioproject.system.SystemCapabilities class */ if(nativeLibDirectories!=null) System.setProperty(SystemCapabilities.NATIVE_LIBS, nativeLibDirectories); /* Initialize the ComputeResource */ initializeComputeResource(computeResource); if(logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Service Limit : ").append(serviceLimit).append("\n"); sb.append("System Capabilities\n"); MeasurableCapability[] mCaps = computeResource.getMeasurableCapabilities(); sb.append("MeasurableCapabilities : ("). append(mCaps.length). append(")\n"); for (MeasurableCapability mCap : mCaps) { sb.append("\t").append(mCap.getId()).append("\n"); ThresholdValues tValues = mCap.getThresholdValues(); sb.append("\t\tlow threshold : ").append(tValues.getLowThreshold()).append("\n"); sb.append("\t\thigh threshold : ").append(tValues.getHighThreshold()).append("\n"); sb.append("\t\treport rate : ").append(mCap.getPeriod()).append("\n"); sb.append("\t\tsample size : "); sb.append(mCap.getSampleSize()).append("\n"); } PlatformCapability[] pCaps = computeResource.getPlatformCapabilities(); sb.append("PlatformCapabilities : (").append(pCaps.length).append(")\n"); double KB = 1024; double MB = Math.pow(KB, 2); double GB = Math.pow(KB, 3); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); for (PlatformCapability pCap : pCaps) { boolean convert = false; if(pCap.getClass().getName().contains("StorageCapability") || pCap.getClass().getName().contains("Memory")) { convert = true; } sb.append("\t").append(stripPackageName(pCap.getClass().getName())).append("\n"); String[] keys = pCap.getPlatformKeys(); for (String key : keys) { Object value = pCap.getValue(key); if(convert && value instanceof Double) { if(pCap.getClass().getName().contains("StorageCapability")) { double d = ((Double)value)/GB; value = nf.format(d)+" GB"; } else { double d = ((Double)value)/MB; value = nf.format(d)+" MB"; } } sb.append("\t\t").append(key).append(" : ").append(value).append("\n"); } String path = pCap.getPath(); if (path != null) sb.append("\t\tPath : ").append(path).append("\n"); } logger.trace(sb.toString()); } /* Create the ServiceStatementManager */ serviceStatementManager = Environment.getServiceStatementManager(config); /* Start the timerTask for updating ServiceRecords */ long serviceRecordUpdateTaskTimer = 60; try { serviceRecordUpdateTaskTimer = Config.getLongEntry(config, getConfigComponent(), "serviceRecordUpdateTaskTimer", serviceRecordUpdateTaskTimer, 1, Long.MAX_VALUE); } catch(Throwable t) { logger.warn("Exception getting slaThresholdTaskPoolMinimum", t); } taskTimer = new Timer(true); long period = 1000*serviceRecordUpdateTaskTimer; long now = System.currentTimeMillis(); serviceRecordUpdateTask = new ServiceRecordUpdateTask(); taskTimer.scheduleAtFixedRate(serviceRecordUpdateTask, new Date(now+period), period); /* * Create a thread pool for processing SLAThresholdEvent */ thresholdTaskPool = Executors.newCachedThreadPool(); /* * Create event descriptor for the SLAThresholdEvent and add it as * an attribute */ EventDescriptor thresholdEventDesc = SLAThresholdEvent.getEventDescriptor(); getEventTable().put(thresholdEventDesc.eventID, getSLAEventHandler()); addAttribute(thresholdEventDesc); addAttribute(new BasicStatus(StatusType.NORMAL)); /* Create the container */ createContainer(); /* Create the consumer which will discover, register and maintain * connection(s) to ProvisionMonitor instances */ svcConsumer = new ServiceConsumer(new CybernodeAdapter((ServiceBeanInstantiator)getServiceProxy(),this, computeResource), serviceLimit, config); /* Get the property that determines whether instantiated services * should be terminated upon unregistration */ serviceTerminationOnUnregister = (Boolean) config.getEntry(getConfigComponent(), "serviceTerminationOnUnregister", Boolean.class, Boolean.TRUE); logger.debug("serviceTerminationOnUnregister={}", serviceTerminationOnUnregister); /* Get whether the Cybernode will make itself available as an asset */ boolean doEnlist = (Boolean)config.getEntry(getConfigComponent(), "enlist", Boolean.class, true); if(doEnlist) { doEnlist(); } else { logger.info("Do not enlist with ProvisionManagers as an instantiation resource"); } /* Create a computeResourcePolicyHandler to watch for thresholds * being crossed */ computeResourcePolicyHandler = new ComputeResourcePolicyHandler(context.getServiceElement(), getSLAEventHandler(), svcConsumer, makeServiceBeanInstance()); computeResource.addThresholdListener(computeResourcePolicyHandler); /* Ensure we have a serviceID */ if(serviceID==null) { serviceID = new ServiceID(getUuid().getMostSignificantBits(), getUuid().getLeastSignificantBits()); - logger.debug("Created new ServiceID:", serviceID.toString()); + logger.debug("Created new ServiceID: {}", serviceID.toString()); } if(logger.isInfoEnabled()) { String[] g = context.getServiceBeanConfig().getGroups(); StringBuilder buff = new StringBuilder(); if(g!= LookupDiscovery.ALL_GROUPS) { for(int i=0; i<g.length; i++) { if(i>0) buff.append(", "); buff.append(g[i]); } } logger.info("Started Cybernode [{}]", buff.toString()); } loadInitialServices(context.getConfiguration()); /* * Force a snapshot so the persistent store reflects the current state * of the Cybernode */ if(store!=null) store.snapshot(); } /* * Get the name of the class sans the package name */ private String stripPackageName(String className) { int ndx = className.lastIndexOf("."); if(ndx==-1) return className; return className.substring(ndx+1); } /** * Load any initial services * * @param config The Jini configuration to use */ protected void loadInitialServices(Configuration config) { /* Get the timeout value for loading initial services */ long initialServiceLoadDelay = 1000*5; try { initialServiceLoadDelay = Config.getLongEntry(config, getConfigComponent(), "initialServiceLoadDelay", initialServiceLoadDelay, 0, Long.MAX_VALUE); } catch(Throwable t) { logger.warn("Exception getting initialServiceLoadDelay", t); } logger.debug("initialServiceLoadDelay={}", initialServiceLoadDelay); /* * Schedule the task to Load any configured services */ if(initialServiceLoadDelay>0) { long now = System.currentTimeMillis(); getTaskTimer().schedule(new InitialServicesLoadTask(config), new Date(now+initialServiceLoadDelay)); } else { InitialServicesLoadTask serviceLoader = new InitialServicesLoadTask(config); serviceLoader.loadInitialServices(); } } /** * Scheduled Task which will load configured services */ class InitialServicesLoadTask extends TimerTask { Configuration config; /** * Create a InitialServicesLoadTask * * @param config Configuration, must not be null */ InitialServicesLoadTask(Configuration config) { if(config==null) throw new IllegalArgumentException("config is null"); this.config = config; } /** * The action to be performed by this timer task. */ public void run() { loadInitialServices(); } void loadInitialServices() { /* Load initial services */ String[] initialServices = new String[] {}; try { initialServices = (String[])config.getEntry(getConfigComponent(), "initialServices", String[].class, initialServices); } catch(ConfigurationException e) { logger.warn("Getting initialServices", e); } if(logger.isDebugEnabled()) logger.debug("Loading [{}] initialServices", initialServices.length); for (String initialService : initialServices) { URL deploymentURL; try { if (initialService.startsWith("http:")) deploymentURL = new URL(initialService); else deploymentURL = new File(initialService).toURI().toURL(); load(deploymentURL); } catch (Throwable t) { logger.error("Loading initial services : {}", initialService, t); } } } /* * Load and activate services */ void load(URL deploymentURL) { if(deploymentURL == null) throw new IllegalArgumentException("Deployment URL cannot be null"); try { /* Get the OperationalString loader */ OpStringLoader opStringLoader = new OpStringLoader(this.getClass().getClassLoader()); OperationalString[] opStrings = opStringLoader.parseOperationalString(deploymentURL); if(opStrings != null) { for (OperationalString opString : opStrings) { logger.debug("Activating Deployment [{}]", opString.getName()); ServiceElement[] services = opString.getServices(); for (ServiceElement service : services) { activate(service); } } } } catch(Throwable t) { logger.warn("Activating OperationalString", t); } } } /* * Create a ServiceProvisionEvent and instantiate the ServiceElement */ private void activate(ServiceElement sElem) { ServiceProvisionEvent spe = new ServiceProvisionEvent(getServiceProxy(), null, sElem); try { instantiate(spe); } catch (Throwable t) { logger.warn("Activating service [{}]", sElem.getName(), t); } } /** * Get the enlisted state */ public boolean isEnlisted() { return(enlisted); } /** * Set the enlisted flag * * @param value True if enlisted, false if not */ protected void setEnlisted(boolean value) { enlisted = value; } /** * Have the Cybernode add itself as a resource which can be * used to instantiate dynamic application services. * * If the Cybernode is already enlisted, this method will have * no effect */ protected void doEnlist() { if(isEnlisted()) { logger.debug("Already enlisted"); return; } logger.info("Enlist with ProvisionManagers as an instantiation resource using: {}", instantiatorID); try { svcConsumer.initializeProvisionDiscovery(context.getDiscoveryManagement()); } catch(Exception e) { logger.warn("Initializing Provision discovery", e); } setEnlisted(true); } /** * Get the Timer created for the Cybernode * * @return The task Timer used to schedule tasks */ protected Timer getTaskTimer() { return(taskTimer); } /** * Get the {@link net.jini.lookup.entry.ServiceInfo} for the Cybernode * * @return The ServiceInfo */ @Override protected ServiceInfo getServiceInfo() { URL implUrl = getClass().getProtectionDomain().getCodeSource().getLocation(); RioManifest rioManifest; String build = null; try { rioManifest = new RioManifest(implUrl); build = rioManifest.getRioBuild(); } catch(IOException e) { logger.warn("Getting Rio Manifest", e); } if(build==null) build="0"; return(new ServiceInfo(context.getServiceElement().getName(), "", "Rio Project", RioVersion.VERSION+" Build "+build, "", "")); } private URL[] getUIJars() throws MalformedURLException { return new URL[]{new URL("artifact:org.rioproject.cybernode:cybernode-ui:"+RioVersion.VERSION), new URL("artifact:org.rioproject:watch-ui:"+RioVersion.VERSION)}; } /** * Override parents getWatchUI, using cybernode-ui.jar as the JAR containing * org.rioproject.watch.AccumulatorViewer * @throws MalformedURLException * @throws IOException */ protected Entry getWatchUI() throws IOException { return(UIDescriptorFactory.getUIDescriptor( AdminUI.ROLE, new UIComponentFactory(getUIJars(), "org.rioproject.watch.AccumulatorViewer"))); } /** * Get the service UIs to add * * @return An array of UIDescriptors used for the service-UIs for the * Cybernode. * * @throws IOException If the UIDescriptors cannot be created */ protected Entry[] getServiceUIs() throws IOException { UIComponentFactory cybernodeUI = new UIComponentFactory(getUIJars(), "org.rioproject.cybernode.ui.PlatformCapabilityUI"); UIComponentFactory platformCapabilityUI = new UIComponentFactory(getUIJars(), "org.rioproject.cybernode.ui.CybernodeUI"); Entry[] uis = new Entry[] {UIDescriptorFactory.getUIDescriptor(AdminUI.ROLE, platformCapabilityUI), UIDescriptorFactory.getUIDescriptor(AdminUI.ROLE, cybernodeUI)}; return(uis); } protected ServiceBeanContainer getServiceBeanContainer() { return container; } /** * @see org.rioproject.deploy.ServiceBeanInstantiator#instantiate */ public DeployedService instantiate(ServiceProvisionEvent event) throws ServiceBeanInstantiationException, UnknownEventException { DeployedService deployedService; try { if(shutdownSequence.get()) { StringBuilder builder = new StringBuilder(); builder.append(CybernodeLogUtil.logName(event)).append(" shutting down, unavailable for service instantiation"); logger.warn(builder.toString()); throw new ServiceBeanInstantiationException(builder.toString()); } loaderLogger.info("Instantiating {}", CybernodeLogUtil.logName(event)); if(event.getID()!=ServiceProvisionEvent.ID) { logger.warn("Unknown event type [{}], ID={}", event.getClass().getName(), event.getID()); throw new UnknownEventException("Unknown event type ["+event.getID()+"]"); } /* Verify that the Cybernode does not instantiate a service past * it's specified max per machine or planned value * * This may occur if a provisioner is in the process of deploying * multiple instances of a service, and service instantiation time takes * longer then expected, or the off chance that multiple provisioners * may be managing the same opstring and may not be out of synch with * each other */ synchronized(inProcess) { /* Get the number of active instances for the ServiceElement */ int instantiatedServiceCount = 0; ServiceRecord[] records = container.getServiceRecords(); for (ServiceRecord record : records) { if (record.getType() == ServiceRecord.ACTIVE_SERVICE_RECORD && record.getServiceElement().equals(event.getServiceElement())) instantiatedServiceCount++; } /* Get the number of instances that are in the process of being * activated for the ServiceElement */ int inProcessServiceCount = 0; for(ServiceProvisionEvent spe : inProcess) { if(spe.getServiceElement().equals(event.getServiceElement())) inProcessServiceCount++; } /* Set the temporal service count to be equal to the in process * count and active instances */ int activeServiceCounter = inProcessServiceCount+instantiatedServiceCount; if(loaderLogger.isTraceEnabled()) loaderLogger.trace("{} activeServiceCounter=[{}], inProcessServiceCount=[{}], instantiatedServiceCount=[{}]", CybernodeLogUtil.logName(event), activeServiceCounter, inProcessServiceCount, instantiatedServiceCount); /* First check max per machine */ int maxPerMachine = event.getServiceElement().getMaxPerMachine(); if(maxPerMachine!=-1 && activeServiceCounter >= maxPerMachine) { if(loaderLogger.isTraceEnabled()) loaderLogger.trace("Abort allocation of {} "+ "activeServiceCounter=[{}] "+ "inProcessServiceCount=[{}] "+ "maxPerMachine=[{}]", CybernodeLogUtil.logName(event), activeServiceCounter, inProcessServiceCount, maxPerMachine); throw new ServiceBeanInstantiationException("MaxPerMachine "+"["+maxPerMachine+"] has been reached"); } /* The check planned service count */ int numPlannedServices = event.getServiceElement().getPlanned(); if(activeServiceCounter >= numPlannedServices) { if(loaderLogger.isTraceEnabled()) loaderLogger.trace("Cancel allocation of {} activeServiceCounter=[{}] numPlannedServices=[{}]", CybernodeLogUtil.logName(event), activeServiceCounter, numPlannedServices+"]"); return(null); } inProcess.add(event); } int inProcessCount; synchronized(inProcess) { inProcessCount = inProcess.size() - container.getActivationInProcessCount(); } int containerServiceCount = container.getServiceCounter(); if((inProcessCount+containerServiceCount) <= serviceLimit) { OperationalStringManager opMgr = event.getOperationalStringManager(); if(!event.getServiceElement().forkService()) { if(loaderLogger.isTraceEnabled()) loaderLogger.trace("Get OpStringManagerProxy for {}", CybernodeLogUtil.logName(event)); try { opMgr = OpStringManagerProxy.getProxy( event.getServiceElement().getOperationalStringName(), event.getOperationalStringManager(), context.getDiscoveryManagement()); if(loaderLogger.isTraceEnabled()) loaderLogger.trace("Got OpStringManagerProxy for {}", CybernodeLogUtil.logName(event)); } catch (Exception e) { loaderLogger.warn("Unable to create proxy for OperationalStringManager, " + "using provided OperationalStringManager", ThrowableUtil.getRootCause(e)); if(shutdownSequence.get()) { throw new ServiceBeanInstantiationException( String.format("Cancel allocation of %s, Cybernode is shutting down", CybernodeLogUtil.logName(event))); } opMgr = event.getOperationalStringManager(); } } try { loaderLogger.trace("Activating {}", CybernodeLogUtil.logName(event)); ServiceBeanInstance jsbInstance = container.activate(event.getServiceElement(), opMgr, getSLAEventHandler()); loaderLogger.trace("Activated {}", CybernodeLogUtil.logName(event)); ServiceBeanDelegate delegate = container.getServiceBeanDelegate(jsbInstance.getServiceBeanID()); ComputeResourceUtilization cru = delegate.getComputeResourceUtilization(); deployedService = new DeployedService(event.getServiceElement(), jsbInstance, cru); loaderLogger.trace("Created DeployedService for {}", CybernodeLogUtil.logName(event)); } catch(ServiceBeanInstantiationException e) { if(opMgr instanceof OpStringManagerProxy.OpStringManager) { try { ((OpStringManagerProxy.OpStringManager)opMgr).terminate(); } catch(IllegalStateException ex) { logger.warn("Shutting down OpStringManagerProxy more then once for service {}", CybernodeLogUtil.logName(event)); } } throw e; } return(deployedService); } else { throw new ServiceBeanInstantiationException("Service Limit of ["+serviceLimit+"] has been reached"); } } finally { synchronized(inProcess) { inProcess.remove(event); } } } /** * Create the container the Cybernode will use * * @throws ConfigurationException if the ServiceBeanContainer cannot be * created using the configuration */ void createContainer() throws ConfigurationException { Configuration config = context.getConfiguration(); ServiceBeanContainer defaultContainer = new JSBContainer(config); this.container = (ServiceBeanContainer)config.getEntry(getConfigComponent(), "serviceBeanContainer", ServiceBeanContainer.class, defaultContainer, config); this.container.setUuid(getUuid()); this.container.setComputeResource(computeResource); this.container.addListener(this); } /** * Change the BasicStatus Entry to reflect a change in state * * @param statusType The StatusType */ void setChanged(StatusType statusType) { joiner.modifyAttributes(new Entry[]{new BasicStatus()}, new Entry[]{new BasicStatus(statusType)}); } /** * Get the ComputeResource associated with this Cybernode * * @return The ComputeResource associated with this Cybernode */ public ComputeResource getComputeResource() { return(computeResource); } /** * The initializeComputeResource initializes the instantiated ComputeResource * object, and adds MeasurableCapability watches to the Watch Registry. * * @param computeResource The ComputeResource to initialize */ void initializeComputeResource(ComputeResource computeResource) { /* * Set whether the Cybernode supports persistent provisioning */ computeResource.setPersistentProvisioning(provisionEnabled); /* * Have the ComputeResource object start all it's MeasurableCapabilities */ computeResource.boot(); /* * Add MeasurableCapability watches to the Watch Registry */ MeasurableCapability[] mCaps = computeResource.getMeasurableCapabilities(); for (MeasurableCapability mCap : mCaps) { getWatchRegistry().register(mCap); } PlatformCapability[] pCaps = computeResource.getPlatformCapabilities(); MBeanServer mbeanServer = MBeanServerFactory.getMBeanServer(); for (PlatformCapability pCap : pCaps) { try { ObjectName objectName = getObjectName(pCap); if (objectName != null) mbeanServer.registerMBean(pCap, objectName); } catch (MalformedObjectNameException e) { logger.warn("PlatformCapability [{}.{}]", pCap.getClass().getName(), pCap.getName(), e); } catch (NotCompliantMBeanException e) { logger.warn("PlatformCapability [{}.{}]", pCap.getClass().getName(), pCap.getName(), e); } catch (MBeanRegistrationException e) { logger.warn("PlatformCapability [{}.{}]", pCap.getClass().getName(), pCap.getName(), e); } catch (InstanceAlreadyExistsException e) { logger.warn("PlatformCapability [{}.{}]", pCap.getClass().getName(), pCap.getName(), e); } } if(logger.isDebugEnabled()) logger.debug("Will update discovered Provision Monitors with resource utilization details at " + "intervals of {}", TimeUtil.format(computeResource.getReportInterval())); } /* * Get an ObjectName for a PlatformCapability */ private ObjectName getObjectName(PlatformCapability pCap) throws MalformedObjectNameException { return(JMXUtil.getObjectName(context, "org.rioproject.cybernode", "PlatformCapability", pCap.getName())); } /* * Make a ServiceBeanInstance for the Cybernode */ private ServiceBeanInstance makeServiceBeanInstance() throws IOException { return new ServiceBeanInstance(getUuid(), new MarshalledInstance(getServiceProxy()), context.getServiceElement().getServiceBeanConfig(), computeResource.getAddress().getHostAddress(), getUuid()); } /** * Scheduled Task which will update ServiceStatement instances with the latest and * greatest ServiceRecords */ class ServiceRecordUpdateTask extends TimerTask { /** * The action to be performed by this timer task. */ public void run() { ServiceRecord[] records = container.getServiceRecords(); for (ServiceRecord record : records) { ServiceStatement statement = serviceStatementManager.get(record.getServiceElement()); if (statement != null) { statement.putServiceRecord(getUuid(), record); serviceStatementManager.record(statement); } } } } /** * If deadlocked threads are detected fire SLAThresholdEvents */ private class DeadlockedThreadPolicyHandler implements ThresholdListener { public void notify(Calculable calculable, ThresholdValues thresholdValues, ThresholdType type) { double[] range = new double[]{ thresholdValues.getCurrentLowThreshold(), thresholdValues.getCurrentHighThreshold() }; SLA sla = new SLA(calculable.getId(), range); try { ServiceBeanInstance instance = makeServiceBeanInstance(); SLAThresholdEvent event = new SLAThresholdEvent(proxy, context.getServiceElement(), instance, calculable, sla, "Cybernode Thread Deadlock " + "Policy Handler", instance.getHostAddress(), type); thresholdTaskPool.execute(new SLAThresholdEventTask(event, getSLAEventHandler())); } catch(Exception e) { logger.warn("Could not send a SLA Threshold Notification as a result of compute resource threshold " + "[{}] being crossed", calculable.getId(), e); } } } /** * Class that manages the persistence details for the Cybernode */ class CybernodeLogHandler extends LogHandler implements SnapshotHandler { public void snapshot(OutputStream out) throws IOException { ObjectOutputStream oostream = new ObjectOutputStream(out); oostream.writeUTF(CybernodeImpl.class.getName()); oostream.writeInt(LOG_VERSION); oostream.flush(); } public void recover(InputStream in) throws Exception { ObjectInputStream oistream = new ObjectInputStream(in); if(!CybernodeImpl.class.getName().equals(oistream.readUTF())) throw new IOException("Log from wrong implementation"); if(oistream.readInt() != LOG_VERSION) throw new IOException("Wrong log format version"); } /** * This method always throws <code>UnsupportedOperationException</code> * since <code>CybernodeLogHandler</code> should never update a log. */ public void applyUpdate(Object update) throws Exception { throw new UnsupportedOperationException("CybernodeLogHandler : "+ "Recovering log update this "+ "should not happen"); } public void updatePerformed(int updateCount) { // empty implementation } public void takeSnapshot() throws IOException { store.snapshot(); } } /*--------------------- * Cybernode * --------------------*/ /* * @see org.rioproject.cybernode.Cybernode#enlist */ public void enlist() { doEnlist(); } @Deprecated public void enlist(Schedule s) { logger.warn("Schedule is ignored for enlisting"); doEnlist(); } @Deprecated public Schedule getSchedule() { logger.warn("Returning null for Schedule, operation no longer supported"); return null; } /* * @see org.rioproject.cybernode.Cybernode#release(boolean) */ public void release(boolean terminateServices) { doRelease(); setEnlisted(false); } private void doRelease() { logger.debug("Unregister from ProvisionMonitor instances "); svcConsumer.cancelRegistrations(); if(serviceTerminationOnUnregister) container.terminateServices(); } /*--------------------- * CybernodeAdmin *---------------------*/ /* * @see org.rioproject.cybernode.CybernodeAdmin#getServiceLimit */ public Integer getServiceLimit() { return(serviceLimit); } /* * @see org.rioproject.cybernode.CybernodeAdmin#setServiceLimit */ public void setServiceLimit(Integer limit) { this.serviceLimit = limit; svcConsumer.updateMonitors(serviceLimit); } /* * @see org.rioproject.cybernode.CybernodeAdmin#getServiceCount */ public Integer getServiceCount() { return(container.getServiceCounter()); } /* * @see org.rioproject.cybernode.CybernodeAdmin#getPersistentProvisioning */ public boolean getPersistentProvisioning() { return(provisionEnabled); } /* * @see org.rioproject.cybernode.CybernodeAdmin#setPersistentProvisioning */ public void setPersistentProvisioning(boolean provisionEnabled) throws IOException { if(this.provisionEnabled==provisionEnabled) return; this.provisionEnabled = provisionEnabled; if(this.provisionEnabled) Environment.setupProvisionRoot(this.provisionEnabled, config); computeResource.setPersistentProvisioning(this.provisionEnabled); } public double getUtilization() { return(computeResource.getUtilization()); } }
true
true
public void initialize(ServiceBeanContext context) throws Exception { /* * Create the instantiatorID. This will be used as the name set in the proxy, and used to track * registrations and updates in the ProvisionMonitor */ StringBuilder instantiatorIDBuilder = new StringBuilder(); instantiatorIDBuilder.append(context.getServiceElement().getName()).append("-"); String name = ManagementFactory.getRuntimeMXBean().getName(); String pid = name; int ndx = name.indexOf("@"); if(ndx>=1) { pid = name.substring(0, ndx); } instantiatorIDBuilder.append(pid).append("@"); instantiatorIDBuilder.append(HostUtil.getHostAddressFromProperty(Constants.RMI_HOST_ADDRESS)); instantiatorID = instantiatorIDBuilder.toString(); /* * Determine if a log directory has been provided. If so, create a * PersistentStore */ String logDirName = (String)context.getConfiguration().getEntry(CONFIG_COMPONENT, "logDirectory", String.class, null); if(logDirName!=null) { /* LogHandler required when dealing with the ReliableLog */ CybernodeLogHandler logHandler = new CybernodeLogHandler(); store = new PersistentStore(logDirName, logHandler, logHandler); if(logger.isDebugEnabled()) logger.debug("Cybernode: using absolute logdir path [{}]", store.getStoreLocation()); store.snapshot(); super.initialize(context, store); } else { super.initialize(context); } /* Get the Configuration */ config = context.getConfiguration(); try { Exporter defaultExporter = (Exporter)config.getEntry(RIO_CONFIG_COMPONENT, DEFAULT_EXPORTER, Exporter.class); logger.trace("{} has been set as the defaultExporter", defaultExporter); } catch(Exception e) { logger.error("The {}.{} attribute must be set", RIO_CONFIG_COMPONENT, DEFAULT_EXPORTER); throw e; } /* Set up thread deadlock detection. This seems a little clumsy to use * the WatchInjector and could probably be improved. This does make the * most use of the wiring for forked service monitoring. */ long threadDeadlockCheck = (Long)config.getEntry(CONFIG_COMPONENT, "threadDeadlockCheck", long.class, (long)5000); if(threadDeadlockCheck>=1000) { WatchDescriptor threadDeadlockDescriptor = ThreadDeadlockMonitor.getWatchDescriptor(); threadDeadlockDescriptor.setPeriod(threadDeadlockCheck); Method getThreadDeadlockCalculable = ThreadDeadlockMonitor.class.getMethod("getThreadDeadlockCalculable"); ThreadDeadlockMonitor threadDeadlockMonitor = new ThreadDeadlockMonitor(); threadDeadlockMonitor.setThreadMXBean(ManagementFactory.getThreadMXBean()); WatchInjector watchInjector = new WatchInjector(this, context); ThresholdWatch watch = (ThresholdWatch)watchInjector.inject(threadDeadlockDescriptor, threadDeadlockMonitor, getThreadDeadlockCalculable); watch.setThresholdValues(new ThresholdValues(0, 1)); watch.addThresholdListener(new DeadlockedThreadPolicyHandler()); } else { logger.info("Thread deadlock monitoring has been disabled. The " + "configured thread deadlock check time was " + "[{}]. To enable thread deadlock monitoring, the thread deadlock check " + "time must be >= 1000 milliseconds.", threadDeadlockCheck); } try { serviceLimit = Config.getIntEntry(config, getConfigComponent(), "serviceLimit", 500, 0, Integer.MAX_VALUE); } catch(Exception e) { logger.warn("Exception getting serviceLimit, default to 500"); } /* Get the ProxyPreparer for passed in OperationalStringManager * instances */ operationalStringManagerPreparer = (ProxyPreparer)config.getEntry(getConfigComponent(), "operationalStringManagerPreparer", ProxyPreparer.class, new BasicProxyPreparer()); /* Check for JMXConnection */ addAttributes(JMXUtil.getJMXConnectionEntries(config)); /* Add service UIs programmatically */ addAttributes(getServiceUIs()); /* Get the security policy to apply to loading services */ String serviceSecurityPolicy = (String)config.getEntry(getConfigComponent(), "serviceSecurityPolicy", String.class, null); if(serviceSecurityPolicy!=null) System.setProperty("rio.service.security.policy", serviceSecurityPolicy); /* Establish default operating environment */ Environment.setupDefaultEnvironment(); /* Setup persistent provisioning attributes */ provisionEnabled = (Boolean) config.getEntry(getConfigComponent(), "provisionEnabled", Boolean.class, true); /* * The directory to provision external software to. This is the root * directory where software may be installed by ServiceBean instances which * require external software to be resident on compute resource the * Cybernode represents */ String provisionRoot = Environment.setupProvisionRoot(provisionEnabled, config); if(provisionEnabled) { logger.debug("Software provisioning has been enabled, default provision root location is [{}]", provisionRoot); } computeResource.setPersistentProvisioningRoot(provisionRoot); /* Setup the native library directory */ String nativeLibDirectories = Environment.setupNativeLibraryDirectories(config); /* Ensure org.rioproject.system.native property is set. This will be used * by the org.rioproject.system.SystemCapabilities class */ if(nativeLibDirectories!=null) System.setProperty(SystemCapabilities.NATIVE_LIBS, nativeLibDirectories); /* Initialize the ComputeResource */ initializeComputeResource(computeResource); if(logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Service Limit : ").append(serviceLimit).append("\n"); sb.append("System Capabilities\n"); MeasurableCapability[] mCaps = computeResource.getMeasurableCapabilities(); sb.append("MeasurableCapabilities : ("). append(mCaps.length). append(")\n"); for (MeasurableCapability mCap : mCaps) { sb.append("\t").append(mCap.getId()).append("\n"); ThresholdValues tValues = mCap.getThresholdValues(); sb.append("\t\tlow threshold : ").append(tValues.getLowThreshold()).append("\n"); sb.append("\t\thigh threshold : ").append(tValues.getHighThreshold()).append("\n"); sb.append("\t\treport rate : ").append(mCap.getPeriod()).append("\n"); sb.append("\t\tsample size : "); sb.append(mCap.getSampleSize()).append("\n"); } PlatformCapability[] pCaps = computeResource.getPlatformCapabilities(); sb.append("PlatformCapabilities : (").append(pCaps.length).append(")\n"); double KB = 1024; double MB = Math.pow(KB, 2); double GB = Math.pow(KB, 3); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); for (PlatformCapability pCap : pCaps) { boolean convert = false; if(pCap.getClass().getName().contains("StorageCapability") || pCap.getClass().getName().contains("Memory")) { convert = true; } sb.append("\t").append(stripPackageName(pCap.getClass().getName())).append("\n"); String[] keys = pCap.getPlatformKeys(); for (String key : keys) { Object value = pCap.getValue(key); if(convert && value instanceof Double) { if(pCap.getClass().getName().contains("StorageCapability")) { double d = ((Double)value)/GB; value = nf.format(d)+" GB"; } else { double d = ((Double)value)/MB; value = nf.format(d)+" MB"; } } sb.append("\t\t").append(key).append(" : ").append(value).append("\n"); } String path = pCap.getPath(); if (path != null) sb.append("\t\tPath : ").append(path).append("\n"); } logger.trace(sb.toString()); } /* Create the ServiceStatementManager */ serviceStatementManager = Environment.getServiceStatementManager(config); /* Start the timerTask for updating ServiceRecords */ long serviceRecordUpdateTaskTimer = 60; try { serviceRecordUpdateTaskTimer = Config.getLongEntry(config, getConfigComponent(), "serviceRecordUpdateTaskTimer", serviceRecordUpdateTaskTimer, 1, Long.MAX_VALUE); } catch(Throwable t) { logger.warn("Exception getting slaThresholdTaskPoolMinimum", t); } taskTimer = new Timer(true); long period = 1000*serviceRecordUpdateTaskTimer; long now = System.currentTimeMillis(); serviceRecordUpdateTask = new ServiceRecordUpdateTask(); taskTimer.scheduleAtFixedRate(serviceRecordUpdateTask, new Date(now+period), period); /* * Create a thread pool for processing SLAThresholdEvent */ thresholdTaskPool = Executors.newCachedThreadPool(); /* * Create event descriptor for the SLAThresholdEvent and add it as * an attribute */ EventDescriptor thresholdEventDesc = SLAThresholdEvent.getEventDescriptor(); getEventTable().put(thresholdEventDesc.eventID, getSLAEventHandler()); addAttribute(thresholdEventDesc); addAttribute(new BasicStatus(StatusType.NORMAL)); /* Create the container */ createContainer(); /* Create the consumer which will discover, register and maintain * connection(s) to ProvisionMonitor instances */ svcConsumer = new ServiceConsumer(new CybernodeAdapter((ServiceBeanInstantiator)getServiceProxy(),this, computeResource), serviceLimit, config); /* Get the property that determines whether instantiated services * should be terminated upon unregistration */ serviceTerminationOnUnregister = (Boolean) config.getEntry(getConfigComponent(), "serviceTerminationOnUnregister", Boolean.class, Boolean.TRUE); logger.debug("serviceTerminationOnUnregister={}", serviceTerminationOnUnregister); /* Get whether the Cybernode will make itself available as an asset */ boolean doEnlist = (Boolean)config.getEntry(getConfigComponent(), "enlist", Boolean.class, true); if(doEnlist) { doEnlist(); } else { logger.info("Do not enlist with ProvisionManagers as an instantiation resource"); } /* Create a computeResourcePolicyHandler to watch for thresholds * being crossed */ computeResourcePolicyHandler = new ComputeResourcePolicyHandler(context.getServiceElement(), getSLAEventHandler(), svcConsumer, makeServiceBeanInstance()); computeResource.addThresholdListener(computeResourcePolicyHandler); /* Ensure we have a serviceID */ if(serviceID==null) { serviceID = new ServiceID(getUuid().getMostSignificantBits(), getUuid().getLeastSignificantBits()); logger.debug("Created new ServiceID:", serviceID.toString()); } if(logger.isInfoEnabled()) { String[] g = context.getServiceBeanConfig().getGroups(); StringBuilder buff = new StringBuilder(); if(g!= LookupDiscovery.ALL_GROUPS) { for(int i=0; i<g.length; i++) { if(i>0) buff.append(", "); buff.append(g[i]); } } logger.info("Started Cybernode [{}]", buff.toString()); } loadInitialServices(context.getConfiguration()); /* * Force a snapshot so the persistent store reflects the current state * of the Cybernode */ if(store!=null) store.snapshot(); }
public void initialize(ServiceBeanContext context) throws Exception { /* * Create the instantiatorID. This will be used as the name set in the proxy, and used to track * registrations and updates in the ProvisionMonitor */ StringBuilder instantiatorIDBuilder = new StringBuilder(); instantiatorIDBuilder.append(context.getServiceElement().getName()).append("-"); String name = ManagementFactory.getRuntimeMXBean().getName(); String pid = name; int ndx = name.indexOf("@"); if(ndx>=1) { pid = name.substring(0, ndx); } instantiatorIDBuilder.append(pid).append("@"); instantiatorIDBuilder.append(HostUtil.getHostAddressFromProperty(Constants.RMI_HOST_ADDRESS)); instantiatorID = instantiatorIDBuilder.toString(); /* * Determine if a log directory has been provided. If so, create a * PersistentStore */ String logDirName = (String)context.getConfiguration().getEntry(CONFIG_COMPONENT, "logDirectory", String.class, null); if(logDirName!=null) { /* LogHandler required when dealing with the ReliableLog */ CybernodeLogHandler logHandler = new CybernodeLogHandler(); store = new PersistentStore(logDirName, logHandler, logHandler); if(logger.isDebugEnabled()) logger.debug("Cybernode: using absolute logdir path [{}]", store.getStoreLocation()); store.snapshot(); super.initialize(context, store); } else { super.initialize(context); } /* Get the Configuration */ config = context.getConfiguration(); try { Exporter defaultExporter = (Exporter)config.getEntry(RIO_CONFIG_COMPONENT, DEFAULT_EXPORTER, Exporter.class); logger.trace("{} has been set as the defaultExporter", defaultExporter); } catch(Exception e) { logger.error("The {}.{} attribute must be set", RIO_CONFIG_COMPONENT, DEFAULT_EXPORTER); throw e; } /* Set up thread deadlock detection. This seems a little clumsy to use * the WatchInjector and could probably be improved. This does make the * most use of the wiring for forked service monitoring. */ long threadDeadlockCheck = (Long)config.getEntry(CONFIG_COMPONENT, "threadDeadlockCheck", long.class, (long)5000); if(threadDeadlockCheck>=1000) { WatchDescriptor threadDeadlockDescriptor = ThreadDeadlockMonitor.getWatchDescriptor(); threadDeadlockDescriptor.setPeriod(threadDeadlockCheck); Method getThreadDeadlockCalculable = ThreadDeadlockMonitor.class.getMethod("getThreadDeadlockCalculable"); ThreadDeadlockMonitor threadDeadlockMonitor = new ThreadDeadlockMonitor(); threadDeadlockMonitor.setThreadMXBean(ManagementFactory.getThreadMXBean()); WatchInjector watchInjector = new WatchInjector(this, context); ThresholdWatch watch = (ThresholdWatch)watchInjector.inject(threadDeadlockDescriptor, threadDeadlockMonitor, getThreadDeadlockCalculable); watch.setThresholdValues(new ThresholdValues(0, 1)); watch.addThresholdListener(new DeadlockedThreadPolicyHandler()); } else { logger.info("Thread deadlock monitoring has been disabled. The " + "configured thread deadlock check time was " + "[{}]. To enable thread deadlock monitoring, the thread deadlock check " + "time must be >= 1000 milliseconds.", threadDeadlockCheck); } try { serviceLimit = Config.getIntEntry(config, getConfigComponent(), "serviceLimit", 500, 0, Integer.MAX_VALUE); } catch(Exception e) { logger.warn("Exception getting serviceLimit, default to 500"); } /* Get the ProxyPreparer for passed in OperationalStringManager * instances */ operationalStringManagerPreparer = (ProxyPreparer)config.getEntry(getConfigComponent(), "operationalStringManagerPreparer", ProxyPreparer.class, new BasicProxyPreparer()); /* Check for JMXConnection */ addAttributes(JMXUtil.getJMXConnectionEntries(config)); /* Add service UIs programmatically */ addAttributes(getServiceUIs()); /* Get the security policy to apply to loading services */ String serviceSecurityPolicy = (String)config.getEntry(getConfigComponent(), "serviceSecurityPolicy", String.class, null); if(serviceSecurityPolicy!=null) System.setProperty("rio.service.security.policy", serviceSecurityPolicy); /* Establish default operating environment */ Environment.setupDefaultEnvironment(); /* Setup persistent provisioning attributes */ provisionEnabled = (Boolean) config.getEntry(getConfigComponent(), "provisionEnabled", Boolean.class, true); /* * The directory to provision external software to. This is the root * directory where software may be installed by ServiceBean instances which * require external software to be resident on compute resource the * Cybernode represents */ String provisionRoot = Environment.setupProvisionRoot(provisionEnabled, config); if(provisionEnabled) { logger.debug("Software provisioning has been enabled, default provision root location is [{}]", provisionRoot); } computeResource.setPersistentProvisioningRoot(provisionRoot); /* Setup the native library directory */ String nativeLibDirectories = Environment.setupNativeLibraryDirectories(config); /* Ensure org.rioproject.system.native property is set. This will be used * by the org.rioproject.system.SystemCapabilities class */ if(nativeLibDirectories!=null) System.setProperty(SystemCapabilities.NATIVE_LIBS, nativeLibDirectories); /* Initialize the ComputeResource */ initializeComputeResource(computeResource); if(logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Service Limit : ").append(serviceLimit).append("\n"); sb.append("System Capabilities\n"); MeasurableCapability[] mCaps = computeResource.getMeasurableCapabilities(); sb.append("MeasurableCapabilities : ("). append(mCaps.length). append(")\n"); for (MeasurableCapability mCap : mCaps) { sb.append("\t").append(mCap.getId()).append("\n"); ThresholdValues tValues = mCap.getThresholdValues(); sb.append("\t\tlow threshold : ").append(tValues.getLowThreshold()).append("\n"); sb.append("\t\thigh threshold : ").append(tValues.getHighThreshold()).append("\n"); sb.append("\t\treport rate : ").append(mCap.getPeriod()).append("\n"); sb.append("\t\tsample size : "); sb.append(mCap.getSampleSize()).append("\n"); } PlatformCapability[] pCaps = computeResource.getPlatformCapabilities(); sb.append("PlatformCapabilities : (").append(pCaps.length).append(")\n"); double KB = 1024; double MB = Math.pow(KB, 2); double GB = Math.pow(KB, 3); NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); for (PlatformCapability pCap : pCaps) { boolean convert = false; if(pCap.getClass().getName().contains("StorageCapability") || pCap.getClass().getName().contains("Memory")) { convert = true; } sb.append("\t").append(stripPackageName(pCap.getClass().getName())).append("\n"); String[] keys = pCap.getPlatformKeys(); for (String key : keys) { Object value = pCap.getValue(key); if(convert && value instanceof Double) { if(pCap.getClass().getName().contains("StorageCapability")) { double d = ((Double)value)/GB; value = nf.format(d)+" GB"; } else { double d = ((Double)value)/MB; value = nf.format(d)+" MB"; } } sb.append("\t\t").append(key).append(" : ").append(value).append("\n"); } String path = pCap.getPath(); if (path != null) sb.append("\t\tPath : ").append(path).append("\n"); } logger.trace(sb.toString()); } /* Create the ServiceStatementManager */ serviceStatementManager = Environment.getServiceStatementManager(config); /* Start the timerTask for updating ServiceRecords */ long serviceRecordUpdateTaskTimer = 60; try { serviceRecordUpdateTaskTimer = Config.getLongEntry(config, getConfigComponent(), "serviceRecordUpdateTaskTimer", serviceRecordUpdateTaskTimer, 1, Long.MAX_VALUE); } catch(Throwable t) { logger.warn("Exception getting slaThresholdTaskPoolMinimum", t); } taskTimer = new Timer(true); long period = 1000*serviceRecordUpdateTaskTimer; long now = System.currentTimeMillis(); serviceRecordUpdateTask = new ServiceRecordUpdateTask(); taskTimer.scheduleAtFixedRate(serviceRecordUpdateTask, new Date(now+period), period); /* * Create a thread pool for processing SLAThresholdEvent */ thresholdTaskPool = Executors.newCachedThreadPool(); /* * Create event descriptor for the SLAThresholdEvent and add it as * an attribute */ EventDescriptor thresholdEventDesc = SLAThresholdEvent.getEventDescriptor(); getEventTable().put(thresholdEventDesc.eventID, getSLAEventHandler()); addAttribute(thresholdEventDesc); addAttribute(new BasicStatus(StatusType.NORMAL)); /* Create the container */ createContainer(); /* Create the consumer which will discover, register and maintain * connection(s) to ProvisionMonitor instances */ svcConsumer = new ServiceConsumer(new CybernodeAdapter((ServiceBeanInstantiator)getServiceProxy(),this, computeResource), serviceLimit, config); /* Get the property that determines whether instantiated services * should be terminated upon unregistration */ serviceTerminationOnUnregister = (Boolean) config.getEntry(getConfigComponent(), "serviceTerminationOnUnregister", Boolean.class, Boolean.TRUE); logger.debug("serviceTerminationOnUnregister={}", serviceTerminationOnUnregister); /* Get whether the Cybernode will make itself available as an asset */ boolean doEnlist = (Boolean)config.getEntry(getConfigComponent(), "enlist", Boolean.class, true); if(doEnlist) { doEnlist(); } else { logger.info("Do not enlist with ProvisionManagers as an instantiation resource"); } /* Create a computeResourcePolicyHandler to watch for thresholds * being crossed */ computeResourcePolicyHandler = new ComputeResourcePolicyHandler(context.getServiceElement(), getSLAEventHandler(), svcConsumer, makeServiceBeanInstance()); computeResource.addThresholdListener(computeResourcePolicyHandler); /* Ensure we have a serviceID */ if(serviceID==null) { serviceID = new ServiceID(getUuid().getMostSignificantBits(), getUuid().getLeastSignificantBits()); logger.debug("Created new ServiceID: {}", serviceID.toString()); } if(logger.isInfoEnabled()) { String[] g = context.getServiceBeanConfig().getGroups(); StringBuilder buff = new StringBuilder(); if(g!= LookupDiscovery.ALL_GROUPS) { for(int i=0; i<g.length; i++) { if(i>0) buff.append(", "); buff.append(g[i]); } } logger.info("Started Cybernode [{}]", buff.toString()); } loadInitialServices(context.getConfiguration()); /* * Force a snapshot so the persistent store reflects the current state * of the Cybernode */ if(store!=null) store.snapshot(); }
diff --git a/plugins/com.aptana.ide.ui.io/src/com/aptana/ide/ui/io/navigator/actions/EditorUtils.java b/plugins/com.aptana.ide.ui.io/src/com/aptana/ide/ui/io/navigator/actions/EditorUtils.java index 9e95b1da..af90a3b1 100644 --- a/plugins/com.aptana.ide.ui.io/src/com/aptana/ide/ui/io/navigator/actions/EditorUtils.java +++ b/plugins/com.aptana.ide.ui.io/src/com/aptana/ide/ui/io/navigator/actions/EditorUtils.java @@ -1,210 +1,210 @@ /** * This file Copyright (c) 2005-2009 Aptana, Inc. This program is * dual-licensed under both the Aptana Public License and the GNU General * Public license. You may elect to use one or the other of these licenses. * * This program is distributed in the hope that it will be useful, but * AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or * NONINFRINGEMENT. Redistribution, except as permitted by whichever of * the GPL or APL you select, is prohibited. * * 1. For the GPL license (GPL), you can redistribute and/or modify this * program under the terms of the GNU General Public License, * Version 3, as published by the Free Software Foundation. You should * have received a copy of the GNU General Public License, Version 3 along * with this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Aptana provides a special exception to allow redistribution of this file * with certain other free and open source software ("FOSS") code and certain additional terms * pursuant to Section 7 of the GPL. You may view the exception and these * terms on the web at http://www.aptana.com/legal/gpl/. * * 2. For the Aptana Public License (APL), this program and the * accompanying materials are made available under the terms of the APL * v1.0 which accompanies this distribution, and is available at * http://www.aptana.com/legal/apl/. * * You may view the GPL, Aptana's exception and additional terms, and the * APL in the file titled license.html at the root of the corresponding * plugin containing this source file. * * Any modifications to this file must keep this entire header intact. */ package com.aptana.ide.ui.io.navigator.actions; import java.io.File; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPersistableElement; import org.eclipse.ui.IPropertyListener; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.ide.FileStoreEditorInput; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.progress.UIJob; import com.aptana.ide.core.FileUtils; import com.aptana.ide.core.StringUtils; import com.aptana.ide.core.ui.CoreUIUtils; import com.aptana.ide.ui.UIUtils; /** * @author Michael Xia ([email protected]) */ public class EditorUtils { public static class RemoteFileStoreEditorInput extends FileStoreEditorInput { public RemoteFileStoreEditorInput(IFileStore fileStore) { super(fileStore); } @Override public IPersistableElement getPersistable() { // not to persist for now until we figure out a way to re-associate // the local cache copy and the corresponding remote file on startup return null; } } /** * Opens a remote file in its editor. * * @param file * the file store of the remote file * @param editorDesc */ public static void openFileInEditor(final IFileStore fileStore) { Job job = new Job(Messages.EditorUtils_MSG_OpeningRemoteFile + fileStore.getName()) { protected IStatus run(IProgressMonitor monitor) { try { final IFileStore localFileStore = toLocalFileStore(fileStore, monitor); if (localFileStore != null) { UIJob openEditor = new UIJob("Opening editor") { //$NON-NLS-1$ public IStatus runInUIThread(IProgressMonitor monitor) { try { IWorkbenchPage page = CoreUIUtils.getActivePage(); IEditorPart editorPart = null; if (page != null) { IEditorInput editorInput = new RemoteFileStoreEditorInput( localFileStore); boolean opened = (page.findEditor(editorInput) != null); editorPart = page.openEditor(editorInput, IDE .getEditorDescriptor(localFileStore.getName()) .getId()); - if (!opened) { + if (!opened && editorPart != null) { attachSaveListener(fileStore, localFileStore, editorPart); } } } catch (Exception e) { UIUtils.showErrorMessage(StringUtils.format( Messages.EditorUtils_ERR_OpeningEditor, fileStore .toString()), e); } return Status.OK_STATUS; } }; openEditor.setSystem(true); openEditor.schedule(); } } catch (Exception e) { UIUtils.showErrorMessage(StringUtils.format( Messages.EditorUtils_ERR_OpeningEditor, fileStore.toString()), e); } return Status.OK_STATUS; } }; job.schedule(); } /** * Watches the local file for changes and saves it back to the original * remote file when the editor is saved. * * @param originalFile * the file store for the original remote file * @param localCacheFile * the file store for the local cache file * @param editorPart * the editor part the file is opened on */ public static void attachSaveListener(final IFileStore originalFile, final IFileStore localCacheFile, final IEditorPart editorPart) { if (originalFile == localCacheFile) { // the original is a local file; no need to re-save it return; } editorPart.addPropertyListener(new IPropertyListener() { public void propertyChanged(Object source, int propId) { if (propId == EditorPart.PROP_DIRTY && source instanceof EditorPart) { EditorPart ed = (EditorPart) source; if (ed.isDirty()) { return; } Job job = new Job(Messages.EditorUtils_MSG_RemotelySaving + ed.getPartName()) { protected IStatus run(IProgressMonitor monitor) { try { localCacheFile.copy(originalFile, EFS.OVERWRITE, monitor); } catch (CoreException e) { UIUtils.showErrorMessage(StringUtils.format( Messages.EditorUtils_ERR_SavingRemoteFile, originalFile .getName()), e); } return Status.OK_STATUS; } }; job.schedule(); } } }); } /** * Returns a file in the local file system with the same state as the remote * file. * * @param fileStore * the remote file store * @param monitor * the progress monitor (could be null) * @return File the local file store */ private static IFileStore toLocalFileStore(IFileStore fileStore, IProgressMonitor monitor) throws CoreException { File file = fileStore.toLocalFile(EFS.NONE, monitor); if (file != null) { return fileStore; } IPath path = new Path(FileUtils.systemTempDir); path = path.append(fileStore.toString()); IFileStore localFileStore = EFS.getLocalFileSystem().getStore(path); IFileStore parent = localFileStore.getParent(); if (!parent.fetchInfo(EFS.NONE, monitor).exists()) { parent.mkdir(EFS.NONE, monitor); } fileStore.copy(localFileStore, EFS.OVERWRITE, monitor); return localFileStore; } }
true
true
public static void openFileInEditor(final IFileStore fileStore) { Job job = new Job(Messages.EditorUtils_MSG_OpeningRemoteFile + fileStore.getName()) { protected IStatus run(IProgressMonitor monitor) { try { final IFileStore localFileStore = toLocalFileStore(fileStore, monitor); if (localFileStore != null) { UIJob openEditor = new UIJob("Opening editor") { //$NON-NLS-1$ public IStatus runInUIThread(IProgressMonitor monitor) { try { IWorkbenchPage page = CoreUIUtils.getActivePage(); IEditorPart editorPart = null; if (page != null) { IEditorInput editorInput = new RemoteFileStoreEditorInput( localFileStore); boolean opened = (page.findEditor(editorInput) != null); editorPart = page.openEditor(editorInput, IDE .getEditorDescriptor(localFileStore.getName()) .getId()); if (!opened) { attachSaveListener(fileStore, localFileStore, editorPart); } } } catch (Exception e) { UIUtils.showErrorMessage(StringUtils.format( Messages.EditorUtils_ERR_OpeningEditor, fileStore .toString()), e); } return Status.OK_STATUS; } }; openEditor.setSystem(true); openEditor.schedule(); } } catch (Exception e) { UIUtils.showErrorMessage(StringUtils.format( Messages.EditorUtils_ERR_OpeningEditor, fileStore.toString()), e); } return Status.OK_STATUS; } }; job.schedule(); }
public static void openFileInEditor(final IFileStore fileStore) { Job job = new Job(Messages.EditorUtils_MSG_OpeningRemoteFile + fileStore.getName()) { protected IStatus run(IProgressMonitor monitor) { try { final IFileStore localFileStore = toLocalFileStore(fileStore, monitor); if (localFileStore != null) { UIJob openEditor = new UIJob("Opening editor") { //$NON-NLS-1$ public IStatus runInUIThread(IProgressMonitor monitor) { try { IWorkbenchPage page = CoreUIUtils.getActivePage(); IEditorPart editorPart = null; if (page != null) { IEditorInput editorInput = new RemoteFileStoreEditorInput( localFileStore); boolean opened = (page.findEditor(editorInput) != null); editorPart = page.openEditor(editorInput, IDE .getEditorDescriptor(localFileStore.getName()) .getId()); if (!opened && editorPart != null) { attachSaveListener(fileStore, localFileStore, editorPart); } } } catch (Exception e) { UIUtils.showErrorMessage(StringUtils.format( Messages.EditorUtils_ERR_OpeningEditor, fileStore .toString()), e); } return Status.OK_STATUS; } }; openEditor.setSystem(true); openEditor.schedule(); } } catch (Exception e) { UIUtils.showErrorMessage(StringUtils.format( Messages.EditorUtils_ERR_OpeningEditor, fileStore.toString()), e); } return Status.OK_STATUS; } }; job.schedule(); }