input
stringlengths
20
285k
output
stringlengths
20
285k
public LibraryList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException{ JsonObject obj = json.getAsJsonObject(); LibraryList libraryList = new LibraryList(); for(Map.Entry<String, JsonElement> e : obj.entrySet()){ Library lib = context.deserialize(e.getValue(), Library.class); lib.name = e.getKey(); libraryList.libraries.add(lib); } return null; }
public LibraryList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException{ JsonObject obj = json.getAsJsonObject(); LibraryList libraryList = new LibraryList(); for(Map.Entry<String, JsonElement> e : obj.entrySet()){ Library lib = context.deserialize(e.getValue(), Library.class); lib.name = e.getKey(); libraryList.libraries.add(lib); } return libraryList; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player player = null; String subCmd = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(_pdfFile.getName() + " v" + _pdfFile.getVersion()); sender.sendMessage(_pdfFile.getDescription()); return true; } if (args.length >= 1) { String gameID = null; int gameNum = 0; if (command.getName().equalsIgnoreCase("sp2")) { gameID = "game2"; gameNum = 2; } else { gameID = "game"; gameNum = 1; } if (player == null) { sender.sendMessage("[" + _pdfFile.getName() + "] This command cannot be run from console"); return true; } subCmd = args[0]; if (subCmd.equalsIgnoreCase("join")) { if (SPPlayerManager.isPlayingGame(player)) { player.sendMessage(ChatColor.RED + "You appear to already be playing"); return true; } if (SPPlayerManager.isRunningGame(gameNum)) { player.sendMessage(ChatColor.RED + "The Spleef game is currently running"); return true; } if (SPPlayerManager.beginPlayerGame(player, gameNum)) { getServer().dispatchCommand(player, "spleef join " + gameID); getServer().broadcastMessage(ChatColor.GREEN + "[SPLEEF] " + player.getName() + " joined the Spleef game"); } return true; } else if (subCmd.equalsIgnoreCase("start")) { int time = new Integer(5); int i; if (!SPPlayerManager.isPlayingGame(player)) { player.sendMessage(ChatColor.RED + "You can't start a game you're not playing in!"); return true; } if (SPPlayerManager.isRunningGame(gameNum)) { player.sendMessage(ChatColor.RED + "The Spleef game has already started"); return true; } if (!SPPlayerManager.hasPlayers(gameNum)) { player.sendMessage(ChatColor.RED + "You can't start an empty game!"); return true; } if (args.length == 2) { try{ time = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "I don't think \"" + args[1] + "\" is a whole number..."); return true; } } getServer().dispatchCommand(player, "spleef reset " + gameID); SPPlayerManager.startGame(gameNum); BukkitScheduler scheduler = getServer().getScheduler(); getServer().broadcastMessage(ChatColor.GREEN + "[SPLEEF] " + player.getName() + " started the Spleef countdown"); for (i=1; time > 0; time--, i++) { scheduler.scheduleSyncDelayedTask(this, new GameStart(player, time, gameID), i * 20L); } scheduler.scheduleSyncDelayedTask(this, new GameStart(player, 0, gameID), i * 20L); return true; } else if (subCmd.equalsIgnoreCase("leave")) { if (!SPPlayerManager.isPlayingGame(player)) { player.sendMessage(ChatColor.RED + "You aren't in the game!"); return true; } getServer().dispatchCommand(player, "spleef leave"); getServer().broadcastMessage(ChatColor.GREEN + "[SPLEEF] " + player.getName() + " left the Spleef game"); return true; } else if (subCmd.equalsIgnoreCase("reset")) { if (SPPlayerManager.isRunningGame(gameNum)) { player.sendMessage(ChatColor.RED + "You can't reset during a Spleef game"); return true; } getServer().dispatchCommand(player, "spleef reset " + gameID); return true; } else if (subCmd.equalsIgnoreCase("updatefield")) { if (SPPlayerManager.isRunningGame(gameNum)) { player.sendMessage(ChatColor.RED + "You don't REALLY want to save the field during the game, do you?"); return true; } GameManager.getGame(gameID).getArena().saveState(); player.sendMessage(ChatColor.RED + "Field successfully updated"); return true; } else if (subCmd.equalsIgnoreCase("cancel")) { if (!SPPlayerManager.isPlayingGame(player)) { player.sendMessage(ChatColor.RED + "You can't cancel a game you're not playing!"); return true; } if (SPPlayerManager.isRunningGame()) { getServer().getScheduler().cancelTasks(this); getServer().broadcastMessage(ChatColor.GREEN + "[SPLEEF] All countdowns canceled"); } else { player.sendMessage(ChatColor.RED + "I don't see any games to cancel"); } return true; } } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player player = null; String subCmd = null; if (sender instanceof Player) { player = (Player) sender; } if (args.length == 0) { sender.sendMessage(_pdfFile.getName() + " v" + _pdfFile.getVersion()); sender.sendMessage(_pdfFile.getDescription()); return true; } if (args.length >= 1) { String gameID = null; int gameNum = 0; if (command.getName().equalsIgnoreCase("spl2")) { gameID = "game2"; gameNum = 2; } else { gameID = "game"; gameNum = 1; } if (player == null) { sender.sendMessage("[" + _pdfFile.getName() + "] This command cannot be run from console"); return true; } subCmd = args[0]; if (subCmd.equalsIgnoreCase("join")) { if (SPPlayerManager.isPlayingGame(player)) { player.sendMessage(ChatColor.RED + "You appear to already be playing"); return true; } if (SPPlayerManager.isRunningGame(gameNum)) { player.sendMessage(ChatColor.RED + "The Spleef game is currently running"); return true; } if (SPPlayerManager.beginPlayerGame(player, gameNum)) { getServer().dispatchCommand(player, "spleef join " + gameID); getServer().broadcastMessage(ChatColor.GREEN + "[SPLEEF] " + player.getName() + " joined the Spleef game"); } return true; } else if (subCmd.equalsIgnoreCase("start")) { int time = new Integer(5); int i; if (!SPPlayerManager.isPlayingGame(player)) { player.sendMessage(ChatColor.RED + "You can't start a game you're not playing in!"); return true; } if (SPPlayerManager.isRunningGame(gameNum)) { player.sendMessage(ChatColor.RED + "The Spleef game has already started"); return true; } if (!SPPlayerManager.hasPlayers(gameNum)) { player.sendMessage(ChatColor.RED + "You can't start an empty game!"); return true; } if (args.length == 2) { try{ time = Integer.parseInt(args[1]); } catch (NumberFormatException e) { player.sendMessage(ChatColor.RED + "I don't think \"" + args[1] + "\" is a whole number..."); return true; } } getServer().dispatchCommand(player, "spleef reset " + gameID); SPPlayerManager.startGame(gameNum); BukkitScheduler scheduler = getServer().getScheduler(); getServer().broadcastMessage(ChatColor.GREEN + "[SPLEEF] " + player.getName() + " started the Spleef countdown"); for (i=1; time > 0; time--, i++) { scheduler.scheduleSyncDelayedTask(this, new GameStart(player, time, gameID), i * 20L); } scheduler.scheduleSyncDelayedTask(this, new GameStart(player, 0, gameID), i * 20L); return true; } else if (subCmd.equalsIgnoreCase("leave")) { if (!SPPlayerManager.isPlayingGame(player)) { player.sendMessage(ChatColor.RED + "You aren't in the game!"); return true; } getServer().dispatchCommand(player, "spleef leave"); getServer().broadcastMessage(ChatColor.GREEN + "[SPLEEF] " + player.getName() + " left the Spleef game"); return true; } else if (subCmd.equalsIgnoreCase("reset")) { if (SPPlayerManager.isRunningGame(gameNum)) { player.sendMessage(ChatColor.RED + "You can't reset during a Spleef game"); return true; } getServer().dispatchCommand(player, "spleef reset " + gameID); return true; } else if (subCmd.equalsIgnoreCase("updatefield")) { if (SPPlayerManager.isRunningGame(gameNum)) { player.sendMessage(ChatColor.RED + "You don't REALLY want to save the field during the game, do you?"); return true; } GameManager.getGame(gameID).getArena().saveState(); player.sendMessage(ChatColor.RED + "Field successfully updated"); return true; } else if (subCmd.equalsIgnoreCase("cancel")) { if (!SPPlayerManager.isPlayingGame(player)) { player.sendMessage(ChatColor.RED + "You can't cancel a game you're not playing!"); return true; } if (SPPlayerManager.isRunningGame()) { getServer().getScheduler().cancelTasks(this); getServer().broadcastMessage(ChatColor.GREEN + "[SPLEEF] All countdowns canceled"); } else { player.sendMessage(ChatColor.RED + "I don't see any games to cancel"); } return true; } } return false; }
public IndianSettlementPanel(final Canvas canvas, IndianSettlement settlement) { super(canvas); setLayout(new MigLayout("wrap 2, gapx 20", "", "")); JLabel settlementLabel = new JLabel(canvas.getImageIcon(settlement, false)); Player indian = settlement.getOwner(); Player player = getMyPlayer(); boolean visible = settlement.hasContactedSettlement(player); String text = Messages.message(settlement.getNameFor(player)) + ", " + Messages.message(StringTemplate.template(settlement.isCapital() ? "indianCapital" : "indianSettlement") .addStringTemplate("%nation%", indian.getNationName())); String messageId = settlement.getShortAlarmLevelMessageId(player); text += " (" + Messages.message(messageId) + ")"; settlementLabel.setText(text); add(settlementLabel); Unit missionary = settlement.getMissionary(); if (missionary != null) { String missionaryName = Messages.message(StringTemplate.template("model.unit.nationUnit") .addStringTemplate("%nation%", missionary.getOwner().getNationName()) .addStringTemplate("%unit%", missionary.getLabel())); add(new JLabel(missionaryName, canvas.getImageIcon(missionary, true), JLabel.CENTER)); } add(localizedLabel("indianSettlement.learnableSkill"), "newline"); UnitType skillType = settlement.getLearnableSkill(); if (visible) { if (skillType == null) { add(localizedLabel("indianSettlement.skillNone")); } else { add(new JLabel(Messages.message(skillType.getNameKey()), canvas.getImageIcon(skillType, true), JLabel.CENTER)); } } else { add(localizedLabel("indianSettlement.skillUnknown")); } GoodsType[] wantedGoods = settlement.getWantedGoods(); String sale; add(localizedLabel("indianSettlement.highlyWanted"), "newline"); if (!visible || wantedGoods.length == 0 || wantedGoods[0] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { sale = player.getLastSaleString(settlement, wantedGoods[0]); add(new JLabel(Messages.message(wantedGoods[0].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[0], false), JLabel.CENTER)); } add(localizedLabel("indianSettlement.otherWanted"), "newline"); if (!visible || wantedGoods.length <= 1 || wantedGoods[1] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { int i, n = 1; for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) n++; } sale = player.getLastSaleString(settlement, wantedGoods[1]); add(new JLabel(Messages.message(wantedGoods[1].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[1], false), JLabel.CENTER), "split " + Integer.toString(n)); for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) { sale = player.getLastSaleString(settlement,wantedGoods[i]); add(new JLabel(Messages.message(wantedGoods[i].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[i], false), JLabel.CENTER)); } } } add(okButton, "newline 20, span, tag ok"); setSize(getPreferredSize()); }
public IndianSettlementPanel(final Canvas canvas, IndianSettlement settlement) { super(canvas); setLayout(new MigLayout("wrap 2, gapx 20", "", "")); JLabel settlementLabel = new JLabel(canvas.getImageIcon(settlement, false)); Player indian = settlement.getOwner(); Player player = getMyPlayer(); boolean visited = settlement.hasBeenVisited(player); String text = Messages.message(settlement.getNameFor(player)) + ", " + Messages.message(StringTemplate.template(settlement.isCapital() ? "indianCapital" : "indianSettlement") .addStringTemplate("%nation%", indian.getNationName())); String messageId = settlement.getShortAlarmLevelMessageId(player); text += " (" + Messages.message(messageId) + ")"; settlementLabel.setText(text); add(settlementLabel); Unit missionary = settlement.getMissionary(); if (missionary != null) { String missionaryName = Messages.message(StringTemplate.template("model.unit.nationUnit") .addStringTemplate("%nation%", missionary.getOwner().getNationName()) .addStringTemplate("%unit%", missionary.getLabel())); add(new JLabel(missionaryName, canvas.getImageIcon(missionary, true), JLabel.CENTER)); } add(localizedLabel("indianSettlement.learnableSkill"), "newline"); UnitType skillType = settlement.getLearnableSkill(); if (visited) { if (skillType == null) { add(localizedLabel("indianSettlement.skillNone")); } else { add(new JLabel(Messages.message(skillType.getNameKey()), canvas.getImageIcon(skillType, true), JLabel.CENTER)); } } else { add(localizedLabel("indianSettlement.skillUnknown")); } GoodsType[] wantedGoods = settlement.getWantedGoods(); String sale; add(localizedLabel("indianSettlement.highlyWanted"), "newline"); if (!visited || wantedGoods.length == 0 || wantedGoods[0] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { sale = player.getLastSaleString(settlement, wantedGoods[0]); add(new JLabel(Messages.message(wantedGoods[0].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[0], false), JLabel.CENTER)); } add(localizedLabel("indianSettlement.otherWanted"), "newline"); if (!visited || wantedGoods.length <= 1 || wantedGoods[1] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { int i, n = 1; for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) n++; } sale = player.getLastSaleString(settlement, wantedGoods[1]); add(new JLabel(Messages.message(wantedGoods[1].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[1], false), JLabel.CENTER), "split " + Integer.toString(n)); for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) { sale = player.getLastSaleString(settlement,wantedGoods[i]); add(new JLabel(Messages.message(wantedGoods[i].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[i], false), JLabel.CENTER)); } } } add(okButton, "newline 20, span, tag ok"); setSize(getPreferredSize()); }
public void onCreate(Bundle icicle) { Logger.debug(LOG_TAG, "onCreate(" + icicle + ")"); super.onCreate(icicle); setContentView(R.layout.fxaccount_sign_in); emailEdit = (EditText) ensureFindViewById(null, R.id.email, "email edit"); passwordEdit = (EditText) ensureFindViewById(null, R.id.password, "password edit"); showPasswordButton = (Button) ensureFindViewById(null, R.id.show_password, "show password button"); remoteErrorTextView = (TextView) ensureFindViewById(null, R.id.remote_error, "remote error text view"); button = (Button) ensureFindViewById(null, R.id.button, "sign in button"); progressBar = (ProgressBar) ensureFindViewById(null, R.id.progress, "progress bar"); minimumPasswordLength = 1; createSignInButton(); addListeners(); updateButtonState(); createShowPasswordButton(); View signInInsteadLink = ensureFindViewById(null, R.id.create_account_link, "create account instead link"); signInInsteadLink.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FxAccountSignInActivity.this, FxAccountCreateAccountActivity.class); intent.putExtra("email", emailEdit.getText().toString()); intent.putExtra("password", passwordEdit.getText().toString()); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivityForResult(intent, CHILD_REQUEST_CODE); } }); if (getIntent() != null && getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); emailEdit.setText(bundle.getString("email")); passwordEdit.setText(bundle.getString("password")); } TextView view = (TextView) findViewById(R.id.forgot_password_link); ActivityUtils.linkTextView(view, R.string.fxaccount_sign_in_forgot_password, R.string.fxaccount_link_forgot_password); }
public void onCreate(Bundle icicle) { Logger.debug(LOG_TAG, "onCreate(" + icicle + ")"); super.onCreate(icicle); setContentView(R.layout.fxaccount_sign_in); emailEdit = (EditText) ensureFindViewById(null, R.id.email, "email edit"); passwordEdit = (EditText) ensureFindViewById(null, R.id.password, "password edit"); showPasswordButton = (Button) ensureFindViewById(null, R.id.show_password, "show password button"); remoteErrorTextView = (TextView) ensureFindViewById(null, R.id.remote_error, "remote error text view"); button = (Button) ensureFindViewById(null, R.id.button, "sign in button"); progressBar = (ProgressBar) ensureFindViewById(null, R.id.progress, "progress bar"); minimumPasswordLength = 1; createSignInButton(); addListeners(); updateButtonState(); createShowPasswordButton(); View createAccountInsteadLink = ensureFindViewById(null, R.id.create_account_link, "create account instead link"); createAccountInsteadLink.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FxAccountSignInActivity.this, FxAccountCreateAccountActivity.class); intent.putExtra("email", emailEdit.getText().toString()); intent.putExtra("password", passwordEdit.getText().toString()); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivityForResult(intent, CHILD_REQUEST_CODE); } }); if (getIntent() != null && getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); emailEdit.setText(bundle.getString("email")); passwordEdit.setText(bundle.getString("password")); } TextView view = (TextView) findViewById(R.id.forgot_password_link); ActivityUtils.linkTextView(view, R.string.fxaccount_sign_in_forgot_password, R.string.fxaccount_link_forgot_password); }
Warning() { super("400", "state response"); }
Warning() { super("400", "stale response"); }
public Carpool getDomainObject(Buddy currentBuddy) { LocalDate proposedStartDate = Constants.DATE_FORMATTER.parseLocalDate(this.proposedStartDate); LocalTime officeArrivalTime = Constants.TIME_FORMATTER.parseLocalTime(this.officeArrivalTime); LocalTime officeDepartureTime = Constants.TIME_FORMATTER.parseLocalTime(this.officeDepartureTime); int capacity = Integer.parseInt(this.capacity); LocalTime pickupTime = Constants.TIME_FORMATTER.parseLocalTime(this.pickupTime); CabType cabType = CabType.valueOf(this.cabType); ArrayList<String> routePoints = new ArrayList<String>(); for (String routePoint : this.routePoints.split(",")) { String trimmedRoutePoint = routePoint.trim(); if (StringUtils.isNotBlank(trimmedRoutePoint)) { routePoints.add(trimmedRoutePoint); } } Carpool carpool = new Carpool(from + " - " + to, proposedStartDate, cabType, 0, officeArrivalTime, officeDepartureTime, Status.NOT_STARTED, null, capacity, routePoints); ArrayList<CarpoolBuddy> carpoolBuddies = new ArrayList<CarpoolBuddy>(); carpoolBuddies.add(new CarpoolBuddy(currentBuddy, pickupPoint, pickupTime)); carpool.setCarpoolBuddies(carpoolBuddies); return carpool; }
public Carpool getDomainObject(Buddy currentBuddy) { LocalDate proposedStartDate = Constants.DATE_FORMATTER.parseLocalDate(this.proposedStartDate); LocalTime officeArrivalTime = Constants.TIME_FORMATTER.parseLocalTime(this.officeArrivalTime); LocalTime officeDepartureTime = Constants.TIME_FORMATTER.parseLocalTime(this.officeDepartureTime); int capacity = Integer.parseInt(this.capacity); LocalTime pickupTime = Constants.TIME_FORMATTER.parseLocalTime(this.pickupTime); CabType cabType = CabType.valueOf(this.cabType); ArrayList<String> routePoints = new ArrayList<String>(); for (String routePoint : this.routePoints.split(",")) { String trimmedRoutePoint = routePoint.trim(); if (StringUtils.isNotBlank(trimmedRoutePoint) && !routePoints.contains(routePoint)) { routePoints.add(trimmedRoutePoint); } } Carpool carpool = new Carpool(from + " - " + to, proposedStartDate, cabType, 0, officeArrivalTime, officeDepartureTime, Status.NOT_STARTED, null, capacity, routePoints); ArrayList<CarpoolBuddy> carpoolBuddies = new ArrayList<CarpoolBuddy>(); carpoolBuddies.add(new CarpoolBuddy(currentBuddy, pickupPoint, pickupTime)); carpool.setCarpoolBuddies(carpoolBuddies); return carpool; }
public ProjectCreatorPanel(final String id) { super("div", getHTML(id)); m_projectName = new TextBox(); m_projectName.setTitle(Index.getStrings().projectName_tt()); m_projectName.addKeyUpHandler(this); m_projectName.getElement().setId(id + "projectNameTxt"); m_projectName.getElement().addClassName(WIDE_TEXT_FIELD); add(m_projectName, id + "projectName"); m_projectNameFeedback = new FormFeedback(); m_feedbacks.add(m_projectNameFeedback); add(m_projectNameFeedback, id + "projectNameRow"); m_packageName = new TextBox(); m_packageName.setTitle(Index.getStrings().packageName_tt()); m_packageName.addKeyUpHandler(this); m_packageName.getElement().setId(id + "packageNameTxt"); m_packageName.getElement().addClassName(WIDE_TEXT_FIELD); add(m_packageName, id + "packageName"); m_packageNameFeedback = new FormFeedback(); m_feedbacks.add(m_packageNameFeedback); add(m_packageNameFeedback, id + "packageNameRow"); m_submit = new SimpleButton(Index.getStrings().projectCreatorSubmit()); m_submit.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { event.preventDefault(); JSUtil.hide(id + "createForm"); JSUtil.show(id + "createFormInst"); createProject(); } }); add(m_submit, id + "projectCreatorButtons"); Anchor backToCreate = new Anchor("Back to Create Project", "#"); backToCreate.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { event.preventDefault(); JSUtil.hide(id + "createFormInst"); JSUtil.show(id + "createForm"); } }); add(backToCreate, id + Index.getStrings().backToCreate()); updateFormStatus(null); }
public ProjectCreatorPanel(final String id) { super("div", getHTML(id)); m_projectName = new TextBox(); m_projectName.setTitle(Index.getStrings().projectName_tt()); m_projectName.addKeyUpHandler(this); m_projectName.getElement().setId(id + "projectNameTxt"); m_projectName.getElement().addClassName(WIDE_TEXT_FIELD); add(m_projectName, id + "projectName"); m_projectNameFeedback = new FormFeedback(); m_feedbacks.add(m_projectNameFeedback); add(m_projectNameFeedback, id + "projectNameRow"); m_packageName = new TextBox(); m_packageName.setTitle(Index.getStrings().packageName_tt()); m_packageName.addKeyUpHandler(this); m_packageName.getElement().setId(id + "packageNameTxt"); m_packageName.getElement().addClassName(WIDE_TEXT_FIELD); add(m_packageName, id + "packageName"); m_packageNameFeedback = new FormFeedback(); m_feedbacks.add(m_packageNameFeedback); add(m_packageNameFeedback, id + "packageNameRow"); m_submit = new SimpleButton(Index.getStrings().projectCreatorSubmit()); m_submit.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { event.preventDefault(); JSUtil.hide(id + "createForm"); JSUtil.show(id + "createFormInst"); createProject(); } }); add(m_submit, id + "projectCreatorButtons"); Anchor backToCreate = new Anchor(Index.getStrings().backToCreate(), "#"); backToCreate.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { event.preventDefault(); JSUtil.hide(id + "createFormInst"); JSUtil.show(id + "createForm"); } }); add(backToCreate, id + "backToCreateAnchor"); updateFormStatus(null); }
public Planet(final Json j, final PlanetData data, final EVGameState state) { super(j, "planet", state); aData = data; aObserverSet = new HashSet<PlanetObserver>(); aBuildings = new HashMap<Integer, Building>(); final Json buildingsJson = j.getAttribute("buildings"); for (int b = 0; b < aData.getNumOfBuildingSlots(); b++) { if (buildingsJson.hasAttribute(String.valueOf(b))) { aBuildings.put(b, new Building(buildingsJson.getAttribute(String.valueOf(b)), state)); } else { aBuildings.put(b, null); } } }
public Planet(final Json j, final PlanetData data, final EVGameState state) { super(j, "planet", state); aData = data; aObserverSet = new HashSet<PlanetObserver>(); aBuildings = new HashMap<Integer, Building>(); final Json buildingsJson = j.getAttribute("buildings"); String slot; for (int b = 0; b < aData.getNumOfBuildingSlots(); b++) { slot = String.valueOf(b); if (buildingsJson.hasAttribute(slot) && !buildingsJson.getAttribute(slot).isNull()) { aBuildings.put(b, new Building(buildingsJson.getAttribute(slot), state)); } else { aBuildings.put(b, null); } } }
public String sendRequest(HTTPHandler.RequestData requestData) throws HTTPHandlerException { try { final URI uri = new URI(requestData.getURLString()); final String postString = requestData.getPostString(); m_pluginThreadContext.startTimer(); final HTTPConnection httpConnection = getConnection(uri); final AuthorizationData authorizationData = requestData.getAuthorizationData(); if (authorizationData != null && authorizationData instanceof HTTPHandler.BasicAuthorizationData) { final HTTPHandler.BasicAuthorizationData basicAuthorizationData = (HTTPHandler.BasicAuthorizationData)authorizationData; httpConnection.addBasicAuthorization( basicAuthorizationData.getRealm(), basicAuthorizationData.getUser(), basicAuthorizationData.getPassword()); } final NVPair[] headers = new NVPair[5]; int nextHeader = 0; final String ifModifiedSince = requestData.getIfModifiedSince(); if (ifModifiedSince != null) { headers[nextHeader++] = new NVPair("If-Modified-Since", ifModifiedSince); } final HTTPResponse response; if (postString == null) { response = httpConnection.Get(uri.getPath() + '?' + uri.getQueryString(), (String)null, headers); } else { final String contentType = requestData.getContentType(); headers[nextHeader++] = new NVPair("Content-Type", contentType != null ? contentType : "application/x-www-form-urlencoded"); response = httpConnection.Post(uri.getPath(), postString, headers); } final int statusCode = response.getStatusCode(); if (statusCode == HttpURLConnection.HTTP_OK) { final byte[] data = response.getData(); final String body = data != null? new String(data) : ""; m_pluginThreadContext.stopTimer(); m_pluginThreadContext.logMessage(uri + " OK"); return body; } else if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) { response.getInputStream().close(); m_pluginThreadContext.stopTimer(); m_pluginThreadContext.logMessage(uri + " was not modified"); } else if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == 307) { response.getInputStream().close(); m_pluginThreadContext.stopTimer(); m_pluginThreadContext.logMessage( uri + " returned a redirect (" + statusCode + "). " + "Ensure the next URL is " + response.getHeader("Location")); } else { response.getInputStream().close(); m_pluginThreadContext.stopTimer(); m_pluginThreadContext.logError("Unknown response code: " + statusCode + " (" + response.getReasonLine() + ") for " + uri); } return null; } catch (Exception e) { throw new HTTPHandlerException(e.getMessage(), e); } finally { m_pluginThreadContext.stopTimer(); } }
public String sendRequest(HTTPHandler.RequestData requestData) throws HTTPHandlerException { try { final URI uri = new URI(requestData.getURLString()); final String postString = requestData.getPostString(); m_pluginThreadContext.startTimer(); final HTTPConnection httpConnection = getConnection(uri); final AuthorizationData authorizationData = requestData.getAuthorizationData(); if (authorizationData != null && authorizationData instanceof HTTPHandler.BasicAuthorizationData) { final HTTPHandler.BasicAuthorizationData basicAuthorizationData = (HTTPHandler.BasicAuthorizationData)authorizationData; httpConnection.addBasicAuthorization( basicAuthorizationData.getRealm(), basicAuthorizationData.getUser(), basicAuthorizationData.getPassword()); } final NVPair[] headers = new NVPair[5]; int nextHeader = 0; final String ifModifiedSince = requestData.getIfModifiedSince(); if (ifModifiedSince != null) { headers[nextHeader++] = new NVPair("If-Modified-Since", ifModifiedSince); } final HTTPResponse response; if (postString == null) { String querystring = uri.getQueryString(); if ((querystring != null) && (querystring.length() > 0)) { response = httpConnection.Get(uri.getPath() + '?' + uri.getQueryString(), (String)null, headers); } else { response = httpConnection.Get(uri.getPath(), (String)null, headers); } } else { final String contentType = requestData.getContentType(); headers[nextHeader++] = new NVPair("Content-Type", contentType != null ? contentType : "application/x-www-form-urlencoded"); response = httpConnection.Post(uri.getPath(), postString, headers); } final int statusCode = response.getStatusCode(); if (statusCode == HttpURLConnection.HTTP_OK) { final byte[] data = response.getData(); final String body = data != null? new String(data) : ""; m_pluginThreadContext.stopTimer(); m_pluginThreadContext.logMessage(uri + " OK"); return body; } else if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) { response.getInputStream().close(); m_pluginThreadContext.stopTimer(); m_pluginThreadContext.logMessage(uri + " was not modified"); } else if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == 307) { response.getInputStream().close(); m_pluginThreadContext.stopTimer(); m_pluginThreadContext.logMessage( uri + " returned a redirect (" + statusCode + "). " + "Ensure the next URL is " + response.getHeader("Location")); } else { response.getInputStream().close(); m_pluginThreadContext.stopTimer(); m_pluginThreadContext.logError("Unknown response code: " + statusCode + " (" + response.getReasonLine() + ") for " + uri); } return null; } catch (Exception e) { throw new HTTPHandlerException(e.getMessage(), e); } finally { m_pluginThreadContext.stopTimer(); } }
public static String classNameToSignature(String qualifiedName) { StringBuffer signature= new StringBuffer(); int firstBrace= qualifiedName.indexOf('['); if (firstBrace < 0) { signature.append('L'); signature.append(qualifiedName.replace('.','/')); signature.append(';'); return signature.toString(); } int index= 0; while ((index= (qualifiedName.indexOf('[', index) + 1)) > 0) { signature.append('['); } String name= qualifiedName.substring(0, firstBrace); switch (name.charAt(0)) { case 'b': if (name.equals("byte")) { signature.append('B'); return signature.toString(); } else if (name.equals("boolean")) { signature.append('Z'); return signature.toString(); } break; case 'i': if (name.equals("int")) { signature.append('I'); return signature.toString(); } break; case 'd': if (name.equals("double")) { signature.append('D'); return signature.toString(); } break; case 's': if (name.equals("short")) { signature.append('S'); return signature.toString(); } break; case 'c': if (name.equals("char")) { signature.append('C'); return signature.toString(); } break; case 'l': if (name.equals("long")) { signature.append('J'); return signature.toString(); } break; } signature.append('L'); signature.append(name.replace('.','/')); signature.append(';'); return signature.toString(); }
public static String classNameToSignature(String qualifiedName) { StringBuffer signature= new StringBuffer(); int firstBrace= qualifiedName.indexOf('['); if (firstBrace < 0) { signature.append('L'); signature.append(qualifiedName.replace('.','/')); signature.append(';'); return signature.toString(); } int index= 0; while ((index= (qualifiedName.indexOf('[', index) + 1)) > 0) { signature.append('['); } String name= qualifiedName.substring(0, firstBrace); switch (name.charAt(0)) { case 'b': if (name.equals("byte")) { signature.append('B'); return signature.toString(); } else if (name.equals("boolean")) { signature.append('Z'); return signature.toString(); } break; case 'i': if (name.equals("int")) { signature.append('I'); return signature.toString(); } break; case 'd': if (name.equals("double")) { signature.append('D'); return signature.toString(); } break; case 's': if (name.equals("short")) { signature.append('S'); return signature.toString(); } break; case 'c': if (name.equals("char")) { signature.append('C'); return signature.toString(); } break; case 'l': if (name.equals("long")) { signature.append('J'); return signature.toString(); } break; case 'f': if (name.equals("float")) { signature.append('F'); return signature.toString(); } break; } signature.append('L'); signature.append(name.replace('.','/')); signature.append(';'); return signature.toString(); }
public boolean isJUnit3Class(ASTCompilationUnit node) { if (node.getType() != null && TypeHelper.isA(node, junit3Class)) { return true; } else if (node.getType() == null) { ASTClassOrInterfaceDeclaration cid = node.getFirstChildOfType(ASTClassOrInterfaceDeclaration.class); ASTExtendsList extendsList = cid.getFirstChildOfType(ASTExtendsList.class); if(extendsList == null){ return false; } if(((ASTClassOrInterfaceType)extendsList.jjtGetChild(0)).getImage().endsWith("TestCase")){ return true; } String className = cid.getImage(); return className.endsWith("Test"); } return false; }
public boolean isJUnit3Class(ASTCompilationUnit node) { if (node.getType() != null && TypeHelper.isA(node, junit3Class)) { return true; } else if (node.getType() == null) { ASTClassOrInterfaceDeclaration cid = node.getFirstChildOfType(ASTClassOrInterfaceDeclaration.class); if (cid == null) { return false; } ASTExtendsList extendsList = cid.getFirstChildOfType(ASTExtendsList.class); if(extendsList == null){ return false; } if(((ASTClassOrInterfaceType)extendsList.jjtGetChild(0)).getImage().endsWith("TestCase")){ return true; } String className = cid.getImage(); return className.endsWith("Test"); } return false; }
public ScheduleCell(final String id, Lesson lesson) { super(id); final String cellSubject = ((lesson == null) ? "" : lesson.getLessonDescription().getDiscipline().getName()); final String cellType = ((lesson == null) ? "" : "(" + lesson.getLessonDescription().getLessonType() + ")"); final String cellLecturer = ((lesson == null) ? "" : lesson.getLessonDescription().getLecturerNames()); final String cellGroup = ((lesson == null) || (lesson.getLessonDescription() == null)) ? "" : lesson.getLessonDescription().getStudentGroup().toString(); final String cellRoom = ((lesson == null) ? "" : lesson.getRoom().toString()); add(new Label("cellSubject", cellSubject)); add(new Label("cellType", cellType)); add(new LecturerLabel("cellLecturer", cellLecturer)); add(new GroupLabel("cellGroup", cellGroup)); add(new RoomLabel("cellRoom", cellRoom)); }
public ScheduleCell(final String id, Lesson lesson) { super(id); final String cellSubject = ((lesson == null) ? "" : lesson.getLessonDescription().getDiscipline().getName()); final String cellType = ((lesson == null) ? "" : "(" + lesson.getLessonDescription().getLessonType() + ")"); final String cellLecturer = ((lesson == null) ? "" : lesson.getLessonDescription().getLecturerNames()); final String cellGroup = ((lesson == null) || (lesson.getLessonDescription() == null)) ? "" : lesson.getLessonDescription().getStudentGroup().toString(); final String cellRoom = (((lesson == null) || (lesson.getRoom() == null)) ? "" : lesson.getRoom().toString()); add(new Label("cellSubject", cellSubject)); add(new Label("cellType", cellType)); add(new LecturerLabel("cellLecturer", cellLecturer)); add(new GroupLabel("cellGroup", cellGroup)); add(new RoomLabel("cellRoom", cellRoom)); }
public void testBasic() throws Exception { Graph gg = new Graph(); File file = new File("src/test/resources/nyc_streets/streets.shp"); file = new File("/Users/bdferris/oba/data/opentripplanner-data/nyc/streets/nyc_streets/streets.shp"); if (!file.exists()) { System.out.println("No New York City basemap; skipping; see comment here for details"); return; } ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file); ShapefileStreetSchema schema = new ShapefileStreetSchema(); schema.setIdAttribute("StreetCode"); schema.setNameAttribute("Street"); CaseBasedTraversalPermissionConverter reverse = new CaseBasedTraversalPermissionConverter( "TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY); CaseBasedTraversalPermissionConverter forward = new CaseBasedTraversalPermissionConverter( "TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY); forward.addPermission("W", StreetTraversalPermission.ALL); reverse.addPermission("W", StreetTraversalPermission.PEDESTRIAN_ONLY); forward.addPermission("A", StreetTraversalPermission.PEDESTRIAN_ONLY); reverse.addPermission("A", StreetTraversalPermission.ALL); forward.addPermission("T", StreetTraversalPermission.ALL); reverse.addPermission("T", StreetTraversalPermission.ALL); schema.setForwardPermissionConverter(forward); schema.setReversePermissionConverter(reverse); ShapefileStreetGraphBuilderImpl loader = new ShapefileStreetGraphBuilderImpl(); loader.setFeatureSourceFactory(factory); loader.setSchema(schema); loader.buildGraph(gg); assertEquals(104910,gg.getVertices().size()); Vertex start = gg.getVertex("PARK PL at VANDERBILT AV"); Vertex end = gg.getVertex("GRAND ST at LAFAYETTE ST"); assertNotNull(start); assertNotNull(end); }
public void testBasic() throws Exception { Graph gg = new Graph(); File file = new File("src/test/resources/nyc_streets/streets.shp"); if (!file.exists()) { System.out.println("No New York City basemap; skipping; see comment here for details"); return; } ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file); ShapefileStreetSchema schema = new ShapefileStreetSchema(); schema.setIdAttribute("StreetCode"); schema.setNameAttribute("Street"); CaseBasedTraversalPermissionConverter reverse = new CaseBasedTraversalPermissionConverter( "TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY); CaseBasedTraversalPermissionConverter forward = new CaseBasedTraversalPermissionConverter( "TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY); forward.addPermission("W", StreetTraversalPermission.ALL); reverse.addPermission("W", StreetTraversalPermission.PEDESTRIAN_ONLY); forward.addPermission("A", StreetTraversalPermission.PEDESTRIAN_ONLY); reverse.addPermission("A", StreetTraversalPermission.ALL); forward.addPermission("T", StreetTraversalPermission.ALL); reverse.addPermission("T", StreetTraversalPermission.ALL); schema.setForwardPermissionConverter(forward); schema.setReversePermissionConverter(reverse); ShapefileStreetGraphBuilderImpl loader = new ShapefileStreetGraphBuilderImpl(); loader.setFeatureSourceFactory(factory); loader.setSchema(schema); loader.buildGraph(gg); assertEquals(104910,gg.getVertices().size()); Vertex start = gg.getVertex("PARK PL at VANDERBILT AV"); Vertex end = gg.getVertex("GRAND ST at LAFAYETTE ST"); assertNotNull(start); assertNotNull(end); }
public void gameStart() { reset(); myGame.deal(dealerHand); loadPlayers(); loadHands(); loadChips(); ArrayList<Player> players = gameTable.getAllPlayers(); Scanner keyboard = new Scanner(System.in); for (int i=0; i<players.size(); i++) { System.out.println(players.get(i).getUsername() + ", you have " + players.get(i).getChips() + " chips."); System.out.println("how much do you want to bet?"); int a = keyboard.nextInt(); try { playersAndChips.get(players.get(i)).setBet(a); playersAndChips.get(players.get(i)).addChips(players.get(i), -a); System.out.println(" you want to bet " + a); } catch (Exception IllegalArgumentException) { while (a > playersAndChips.get(players.get(i)).getChips() || a < MIN_BET || a > MAX_BET) { System.out.println("sorry not enough chips, please enter " + playersAndChips.get(players.get(i)).getChips() + " or less" ); a = keyboard.nextInt(); playersAndChips.get(players.get(i)).setBet(a); playersAndChips.get(players.get(i)).addChips(players.get(i), -a); System.out.println(" you want to bet " + a); } } } System.out.println("Dealer's hand: " + dealerHand.toString()); if (dealerHand.checkBlackjack()) { dealerHand.setDone(); System.out.println("Game over!"); } else { while (dealerHand.getBlackjackValue() < MUST_HIT) myGame.hit(dealerHand); dealerHand.setDone(); System.out.println("Dealing everyone..."); for (int i=0; i<players.size(); i++){ System.out.println(players.get(i).getUsername()); } for (ArrayList<BlackjackHand> b : playersAndHands.values()) { BlackjackHand tmpHand = new BlackjackHand(); myGame.deal(tmpHand); b.add(tmpHand); } for (int i=0;i<getNumberOfPlayers();i++){ ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i)); System.out.println(players.get(i).getUsername() + ", your first hand is currently: " + b.get(0).toString()); if (b.size() == 2) { System.out.println(players.get(i).getUsername() + ", your second hand is currently: " + b.get(1).toString()); } } for (int i=0; i<players.size(); i++){ ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i)); System.out.println(players.get(i).getUsername()+": "); for (int j=0; j < b.size(); j++) { while (b.get(j).isPlayable() && !(b.get(j).isBust())){ System.out.println("now for your first hand, do you want to hit, stand, double down, split?"); String s = keyboard.next(); if (s.equals("hit")){ myGame.hit(b.get(j)); System.out.println("hand update: " +b.get(j).toString()); } else if (s.equals("stand")){ myGame.stand(b.get(j)); System.out.println("final hand: "+b.get(j).toString()); } else if (s.equals("doubledown")){ if (playersAndChips.get(players.get(i)).getChips() < 2*playersAndChips.get(players.get(i)).getBet()) { System.out.print("sorry not enough chips, please enter a different move" ); s = ""; } else { myGame.doubleDown(b.get(j)); System.out.println("hand update: "+b.get(j).toString()); } } else if (s.equals("split")){ if (b.get(j).checkPair() == false) { System.out.println("you dont have a pair! select a different move"); s = ""; } else { myGame.split(b.get(j)); System.out.println("split to be implemented: "+b.get(j).toString()); } } else { System.out.println("please enter something valid"); s = ""; } } } } System.out.println("Dealer's new hand: " + dealerHand.toString()); if (dealerHand.isBust()) System.out.println("Dealer bust!"); for (int i=0;i<getNumberOfPlayers();i++){ ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i)); if (b.size() == 1) { if (processWinner(b.get(0)) == 1) { players.get(i).addChips(playersAndChips.get(players.get(i)).getBet()); players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet()); System.out.println("Dealer wins!"); } if (processWinner(b.get(0)) == -1) { if (b.get(0).checkBlackjack()) { players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!"); } else { players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!"); } } if (processWinner(b.get(0)) == 0) { playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet()); System.out.println("Draw!"); } } else { if (processWinner(b.get(0)) == 1) { players.get(i).addChips(playersAndChips.get(players.get(i)).getBet()); players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet()); System.out.println("Dealer wins!"); } if (processWinner(b.get(0)) == -1) { if (b.get(0).checkBlackjack()) { players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!"); } else { players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!"); } } if (processWinner(b.get(0)) == 0) { playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet()); System.out.println("Draw!"); } if (processWinner(b.get(1)) == 1) { players.get(i).addChips(playersAndChips.get(players.get(i)).getBet()); players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet()); System.out.println("Dealer wins!"); } if (processWinner(b.get(1)) == -1) { if (b.get(0).checkBlackjack()) { players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!"); } else { players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!"); } } if (processWinner(b.get(1)) == 0) { playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet()); System.out.println("Draw!"); } } } } }
public void gameStart() { reset(); myGame.deal(dealerHand); loadPlayers(); loadHands(); loadChips(); ArrayList<Player> players = gameTable.getAllPlayers(); Scanner keyboard = new Scanner(System.in); for (int i=0; i<players.size(); i++) { System.out.println(players.get(i).getUsername() + ", you have " + players.get(i).getChips() + " chips."); System.out.println("how much do you want to bet?"); int a = keyboard.nextInt(); try { playersAndChips.get(players.get(i)).setBet(a); playersAndChips.get(players.get(i)).addChips(players.get(i), -a); System.out.println(" you want to bet " + a); } catch (Exception IllegalArgumentException) { while (a > playersAndChips.get(players.get(i)).getChips() || a < MIN_BET || a > MAX_BET) { System.out.println("sorry not enough chips, please enter " + playersAndChips.get(players.get(i)).getChips() + " or less" ); a = keyboard.nextInt(); playersAndChips.get(players.get(i)).setBet(a); playersAndChips.get(players.get(i)).addChips(players.get(i), -a); System.out.println(" you want to bet " + a); } } } System.out.println("Dealer's hand: " + dealerHand.toString()); if (dealerHand.checkBlackjack()) { dealerHand.setDone(); System.out.println("Game over!"); } else { while (dealerHand.getBlackjackValue() < MUST_HIT) myGame.hit(dealerHand); dealerHand.setDone(); System.out.println("Dealing everyone..."); for (int i=0; i<players.size(); i++){ System.out.println(players.get(i).getUsername()); } for (ArrayList<BlackjackHand> b : playersAndHands.values()) { BlackjackHand tmpHand = new BlackjackHand(); myGame.deal(tmpHand); b.add(tmpHand); } for (int i=0;i<getNumberOfPlayers();i++){ ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i)); System.out.println(players.get(i).getUsername() + ", your first hand is currently: " + b.get(0).toString()); if (b.size() == 2) { System.out.println(players.get(i).getUsername() + ", your second hand is currently: " + b.get(1).toString()); } } for (int i=0; i<players.size(); i++){ ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i)); System.out.println(players.get(i).getUsername()+": "); for (int j=0; j < b.size(); j++) { while (b.get(j).isPlayable() && !(b.get(j).isBust())){ System.out.println("Hit, stand, doubledown or split?"); String s = keyboard.next(); if (s.equals("hit")){ myGame.hit(b.get(j)); System.out.println("hand update: " +b.get(j).toString()); } else if (s.equals("stand")){ myGame.stand(b.get(j)); System.out.println("final hand: "+b.get(j).toString()); } else if (s.equals("doubledown")){ if (playersAndChips.get(players.get(i)).getChips() < 2*playersAndChips.get(players.get(i)).getBet()) { System.out.print("sorry not enough chips, please enter a different move" ); s = ""; } else { myGame.doubleDown(b.get(j)); System.out.println("hand update: "+b.get(j).toString()); } } else if (s.equals("split")){ if (b.get(j).checkPair() == false) { System.out.println("you dont have a pair! select a different move"); s = ""; } else { myGame.split(b.get(j)); System.out.println("split to be implemented: "+b.get(j).toString()); } } else { System.out.println("please enter something valid"); s = ""; } } } } System.out.println("Dealer's new hand: " + dealerHand.toString()); if (dealerHand.isBust()) System.out.println("Dealer bust!"); for (int i=0;i<getNumberOfPlayers();i++){ ArrayList<BlackjackHand> b = playersAndHands.get(players.get(i)); if (b.size() == 1) { if (processWinner(b.get(0)) == 1) { players.get(i).addChips(playersAndChips.get(players.get(i)).getBet()); players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet()); System.out.println("Dealer wins!"); } if (processWinner(b.get(0)) == -1) { if (b.get(0).checkBlackjack()) { players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!"); } else { players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!"); } } if (processWinner(b.get(0)) == 0) { playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet()); System.out.println("Draw!"); } } else { if (processWinner(b.get(0)) == 1) { players.get(i).addChips(playersAndChips.get(players.get(i)).getBet()); players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet()); System.out.println("Dealer wins!"); } if (processWinner(b.get(0)) == -1) { if (b.get(0).checkBlackjack()) { players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!"); } else { players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!"); } } if (processWinner(b.get(0)) == 0) { playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet()); System.out.println("Draw!"); } if (processWinner(b.get(1)) == 1) { players.get(i).addChips(playersAndChips.get(players.get(i)).getBet()); players.get(i).addLoss(playersAndChips.get(players.get(i)).getBet()); System.out.println("Dealer wins!"); } if (processWinner(b.get(1)) == -1) { if (b.get(0).checkBlackjack()) { players.get(i).addWin(BLACKJACK_PAYOUT_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println("BLACKJACK! X2 PAYOUT! " + gameTable.getPlayer(i).getUsername()+ " wins!"); } else { players.get(i).addWin(WIN_CONSTANT * playersAndChips.get(players.get(i)).getBet()); System.out.println(gameTable.getPlayer(i).getUsername()+ " wins!"); } } if (processWinner(b.get(1)) == 0) { playersAndChips.get(gameTable.getPlayer(i)).addChips(players.get(i), playersAndChips.get(gameTable.getPlayer(i)).getBet()); System.out.println("Draw!"); } } } } }
public static void rewrite(byte[] packet, int oldId, int newId) { int packetId = packet[0] & 0xFF; if ( packetId == 0x1D ) { for ( int pos = 2; pos < packet.length; pos += 4 ) { int readId = readInt( packet, pos ); if ( readId == oldId ) { setInt( packet, pos, newId ); } else if ( readId == newId ) { setInt( packet, pos, oldId ); } } } else { int[] idArray = entityIds[packetId]; if ( idArray != null ) { for ( int pos : idArray ) { int readId = readInt( packet, pos ); if ( readId == oldId ) { setInt( packet, pos, newId ); } else if ( readId == newId ) { setInt( packet, pos, oldId ); } } } } if ( packetId == 0x17 ) { int type = packet[5] & 0xFF; if ( type == 60 || type == 90 ) { if ( readInt( packet, 20 ) == oldId ) { setInt( packet, 20, newId ); } } } }
public static void rewrite(byte[] packet, int oldId, int newId) { int packetId = packet[0] & 0xFF; if ( packetId == 0x1D ) { for ( int pos = 2; pos < packet.length; pos += 4 ) { int readId = readInt( packet, pos ); if ( readId == oldId ) { setInt( packet, pos, newId ); } else if ( readId == newId ) { setInt( packet, pos, oldId ); } } } else { int[] idArray = entityIds[packetId]; if ( idArray != null ) { for ( int pos : idArray ) { int readId = readInt( packet, pos ); if ( readId == oldId ) { setInt( packet, pos, newId ); } else if ( readId == newId ) { setInt( packet, pos, oldId ); } } } } if ( packetId == 0x17 ) { int type = packet[5] & 0xFF; if ( type == 60 || type == 90 ) { int index20 = readInt( packet, 20 ); if ( packet.length > 24 && index20 == oldId ) { setInt( packet, 20, newId ); } } } }
public Object buildTreeNode(ParseNode node) { LabelInfo label = labels[node.getLabel() - labelStart]; IToken prevToken = tokenizer.currentToken(); int lastOffset = offset; AbstractParseNode[] subnodes = node.getChildren(); boolean isList = label.isList(); boolean lexicalStart = false; if (!inLexicalContext && label.isNonContextFree()) inLexicalContext = lexicalStart = true; List<Object> children; if (isList) { children = inLexicalContext ? null : new AutoConcatList<Object>(label.getSort()); LinkedList<AbstractParseNode> nodes = new LinkedList<AbstractParseNode>(); nodes.push(node); while (!nodes.isEmpty()) { AbstractParseNode current = nodes.pop(); LabelInfo currentLabel = current.isAmbNode() ? null : labels[current.getLabel() - labelStart]; if (currentLabel != null && currentLabel.isList() && (label.getSort() == null ? currentLabel.getSort() == null : label.getSort().equals(currentLabel.getSort()))) for (int i = current.getChildren().length - 1; i >= 0; i--) nodes.push(current.getChildren()[i]); else { Object child; if (inLexicalContext && current.isParseProductionChain()) child = chainToTreeTopdown(current); else child = current.toTreeTopdown(this); if (inLexicalContext) child = null; if (child != null) children.add(child); } } if (!inLexicalContext && isList && children.isEmpty()) { IToken token = tokenizer.makeToken(tokenizer.getStartOffset() - 1, IToken.TK_LAYOUT, true); ((AutoConcatList) children).setEmptyListToken(token); } } else { children = inLexicalContext ? null : new ArrayList<Object>(max(EXPECTED_NODE_CHILDREN, subnodes.length)); for (AbstractParseNode subnode : subnodes) { Object child; if (inLexicalContext && subnode.isParseProductionChain()) { child = chainToTreeTopdown(subnode); } else { child = subnode.toTreeTopdown(this); } if (inLexicalContext) child = null; if (child != null) children.add(tryBuildAutoConcatListNode(child)); } } Object result; if (lexicalStart) { result = tryCreateStringTerminal(label, lastOffset); inLexicalContext = false; } else if (inLexicalContext) { tokenizer.tryMakeLayoutToken(offset - 1, lastOffset - 1, label); result = null; } else if (isList) { result = children; } else { result = createNodeOrInjection(label, prevToken, children); } tokenizer.markPossibleSyntaxError(label, prevToken, offset - 1, prodReader); return result; }
public Object buildTreeNode(ParseNode node) { LabelInfo label = labels[node.getLabel() - labelStart]; IToken prevToken = tokenizer.currentToken(); int lastOffset = offset; AbstractParseNode[] subnodes = node.getChildren(); boolean isList = label.isList(); boolean lexicalStart = false; if (!inLexicalContext && label.isNonContextFree()) inLexicalContext = lexicalStart = true; List<Object> children; if (isList) { children = inLexicalContext ? null : new AutoConcatList<Object>(label.getSort()); LinkedList<AbstractParseNode> nodes = new LinkedList<AbstractParseNode>(); nodes.push(node); while (!nodes.isEmpty()) { AbstractParseNode current = nodes.pop(); LabelInfo currentLabel = current.isAmbNode() || current.isParseProductionNode() ? null : labels[current.getLabel() - labelStart]; if (currentLabel != null && currentLabel.isList() && (label.getSort() == null ? currentLabel.getSort() == null : label.getSort().equals(currentLabel.getSort()))) for (int i = current.getChildren().length - 1; i >= 0; i--) nodes.push(current.getChildren()[i]); else { Object child; if (inLexicalContext && current.isParseProductionChain()) child = chainToTreeTopdown(current); else child = current.toTreeTopdown(this); if (inLexicalContext) child = null; if (child != null) children.add(child); } } if (!inLexicalContext && isList && children.isEmpty()) { IToken token = tokenizer.makeToken(tokenizer.getStartOffset() - 1, IToken.TK_LAYOUT, true); ((AutoConcatList) children).setEmptyListToken(token); } } else { children = inLexicalContext ? null : new ArrayList<Object>(max(EXPECTED_NODE_CHILDREN, subnodes.length)); for (AbstractParseNode subnode : subnodes) { Object child; if (inLexicalContext && subnode.isParseProductionChain()) { child = chainToTreeTopdown(subnode); } else { child = subnode.toTreeTopdown(this); } if (inLexicalContext) child = null; if (child != null) children.add(tryBuildAutoConcatListNode(child)); } } Object result; if (lexicalStart) { result = tryCreateStringTerminal(label, lastOffset); inLexicalContext = false; } else if (inLexicalContext) { tokenizer.tryMakeLayoutToken(offset - 1, lastOffset - 1, label); result = null; } else if (isList) { result = children; } else { result = createNodeOrInjection(label, prevToken, children); } tokenizer.markPossibleSyntaxError(label, prevToken, offset - 1, prodReader); return result; }
public static void receivePresence(org.jdom2.Document tag) { if(tag.getRootElement().getAttribute("from") != null) { String from = tag.getRootElement().getAttribute("from").getValue(); if(from.substring(0, from.indexOf('/')).trim().equals(Session.to.trim())) { StegMPP.getUI().print("[System] ",Style.SYSTEM); if(tag.getRootElement().getChildText("show") != null) { StegMPP.getUI().println(Session.to + " Online"); } else if(tag.getRootElement().getAttributeValue("type") != null ) { if(tag.getRootElement().getAttributeValue("type").equals("unavailable") ) { StegMPP.getUI().println(Session.to + " Online"); } } } } }
public static void receivePresence(org.jdom2.Document tag) { if(tag.getRootElement().getAttribute("from") != null) { String from = tag.getRootElement().getAttribute("from").getValue(); if(from.substring(0, from.indexOf('/')).trim().equals(Session.to.trim())) { StegMPP.getUI().print("[System] ",Style.SYSTEM); if(tag.getRootElement().getChildText("show") != null) { StegMPP.getUI().println(Session.to + " Online"); } else if(tag.getRootElement().getAttributeValue("type") != null ) { if(tag.getRootElement().getAttributeValue("type").equals("unavailable") ) { StegMPP.getUI().println(Session.to + " Offline"); } } } } }
public static Request createProxiedRequest(SipServletRequestImpl originalRequest, ProxyBranchImpl proxyBranch, URI destination, SipURI outboundInterface, SipURI routeRecord, SipURI path) { try { final Request clonedRequest = (Request) originalRequest.getMessage().clone(); final String method = clonedRequest.getMethod(); final ProxyImpl proxy = (ProxyImpl) proxyBranch.getProxy(); final SipFactoryImpl sipFactoryImpl = proxy.getSipFactoryImpl(); ((MessageExt)clonedRequest).setApplicationData(null); String outboundTransport = null; RouteHeader rHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME); if(rHeader != null) { String nextApp = ((javax.sip.address.SipURI)rHeader.getAddress().getURI()).getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME); if(nextApp != null) { final SipApplicationSessionKey sipAppKey = originalRequest.getSipSession().getSipApplicationSession().getKey(); final String thisApp = sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(sipAppKey.getApplicationName()); outboundTransport = ((javax.sip.address.SipURI)rHeader.getAddress().getURI()).getTransportParam(); if(outboundTransport == null) { outboundTransport = ListeningPoint.UDP; } if(nextApp.equals(thisApp)) { clonedRequest.removeHeader(RouteHeader.NAME); } } } else { if(clonedRequest.getRequestURI().isSipURI()) { outboundTransport = ((javax.sip.address.SipURI)clonedRequest.getRequestURI()).getTransportParam(); } } String inboundTransport = ((ViaHeader)clonedRequest.getHeader(Via.NAME)).getTransport(); if(inboundTransport == null) inboundTransport = ListeningPoint.UDP; if(destination != null) { if(logger.isDebugEnabled()){ logger.debug("request URI on the request to proxy : " + destination); } Header route = clonedRequest.getHeader("Route"); if(route == null || originalRequest.isInitial()) { if(logger.isDebugEnabled()){ logger.debug("setting request uri as cloned request has no Route headers: " + destination); } clonedRequest.setRequestURI(((URIImpl)destination).getURI()); } else { if(logger.isDebugEnabled()){ logger.debug("NOT setting request uri as cloned request has at least one Route header: " + route); } } } else { if (method.equals(Request.CANCEL)) { clonedRequest.removeHeader(ViaHeader.NAME); clonedRequest.removeHeader(RecordRouteHeader.NAME); } SipConnector sipConnector = StaticServiceHolder.sipStandardService.findSipConnector(outboundTransport); if(sipConnector != null && sipConnector.isUseStaticAddress()) { javax.sip.address.URI uri = clonedRequest.getRequestURI(); if(uri.isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) uri; JainSipUtils.optimizeUriForInternalRoutingRequest(sipConnector, sipUri, originalRequest.getSipSession(), sipFactoryImpl, outboundTransport); } if(logger.isDebugEnabled()){ logger.debug("setting request uri as cloned request has no Route headers and is using static address: " + destination); } } } MaxForwardsHeader mf = (MaxForwardsHeader) clonedRequest .getHeader(MaxForwardsHeader.NAME); if (mf == null) { mf = SipFactories.headerFactory.createMaxForwardsHeader(70); clonedRequest.addHeader(mf); } else { mf.setMaxForwards(mf.getMaxForwards() - 1); } if (method.equals(Request.CANCEL)) { clonedRequest.removeHeader(ViaHeader.NAME); } final SipApplicationSessionKey sipAppKey = originalRequest.getSipSession().getSipApplicationSession().getKey(); final String appName = sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(sipAppKey.getApplicationName()); final SipServletRequestImpl proxyBranchMatchingRequest = (SipServletRequestImpl) proxyBranch.getMatchingRequest(originalRequest); if(outboundTransport == null && destination != null) { outboundTransport = destination.getParameter("transport"); } if(proxy.getOutboundInterface() == null) { String branchId = null; if(Request.ACK.equals(method) && proxyBranchMatchingRequest != null && proxyBranchMatchingRequest.getTransaction() != null && proxyBranchMatchingRequest.getTransaction().getState() != TransactionState.TERMINATED) { branchId = proxyBranchMatchingRequest.getTransaction().getBranchId(); logger.debug("reusing original branch id " + branchId); } else { branchId = JainSipUtils.createBranch(sipAppKey.getId(), appName); } proxyBranch.viaHeader = JainSipUtils.createViaHeader( sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, branchId, null); } else { String branchId = null; if(outboundTransport == null) { outboundTransport = proxy.getOutboundInterface().getTransportParam(); if(outboundTransport == null) { if(proxy.getOutboundInterface().isSecure()) { outboundTransport = ListeningPoint.TLS; } else { outboundTransport = ListeningPoint.UDP; } } } if(Request.ACK.equals(method) && proxyBranchMatchingRequest != null && proxyBranchMatchingRequest.getTransaction() != null && proxyBranchMatchingRequest.getTransaction().getState() != TransactionState.TERMINATED) { branchId = proxyBranchMatchingRequest.getTransaction().getBranchId(); logger.debug("reusing original branch id " + branchId); } else { branchId = JainSipUtils.createBranch(sipAppKey.getId(), appName); } proxyBranch.viaHeader = SipFactories.headerFactory.createViaHeader( proxy.getOutboundInterface().getHost(), proxy.getOutboundInterface().getPort(), outboundTransport, branchId); } clonedRequest.addHeader(proxyBranch.viaHeader); if(outboundTransport == null) outboundTransport = ListeningPoint.UDP; if(clonedRequest.getHeader(RouteHeader.NAME) == null) { if(clonedRequest.getRequestURI().isSipURI()) { javax.sip.address.SipURI sipURI = ((javax.sip.address.SipURI)clonedRequest.getRequestURI()); String transportFromURI = sipURI.getTransportParam(); if(transportFromURI == null) transportFromURI = ListeningPoint.UDP; if(!transportFromURI.equalsIgnoreCase(outboundTransport)) sipURI.setTransportParam(outboundTransport); } } if(routeRecord != null && !Request.REGISTER.equalsIgnoreCase(method)) { if(!inboundTransport.equalsIgnoreCase(outboundTransport)) { javax.sip.address.SipURI inboundRURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, inboundTransport); if(originalRequest.getTransport() != null) inboundRURI.setTransportParam(originalRequest.getTransport()); final Iterator<String> paramNames = routeRecord.getParameterNames(); while(paramNames.hasNext()) { String paramName = paramNames.next(); if(!paramName.equalsIgnoreCase("transport")) { inboundRURI.setParameter(paramName, routeRecord.getParameter(paramName)); } } inboundRURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, appName); inboundRURI.setParameter(MessageDispatcher.RR_PARAM_PROXY_APP, "true"); inboundRURI.setParameter(MessageDispatcher.APP_ID, sipAppKey.getId()); inboundRURI.setLrParam(); final Address rraddress = SipFactories.addressFactory .createAddress(null, inboundRURI); final RecordRouteHeader recordRouteHeader = SipFactories.headerFactory .createRecordRouteHeader(rraddress); clonedRequest.addFirst(recordRouteHeader); } javax.sip.address.SipURI rrURI = null; if(proxy.getOutboundInterface() == null) { rrURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, outboundTransport); } else { rrURI = ((SipURIImpl) proxy.getOutboundInterface()).getSipURI(); rrURI.setTransportParam(outboundTransport); } final Iterator<String> paramNames = routeRecord.getParameterNames(); while(paramNames.hasNext()) { String paramName = paramNames.next(); if(!paramName.equalsIgnoreCase("transport")) { rrURI.setParameter(paramName, routeRecord.getParameter(paramName)); } } rrURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, appName); rrURI.setParameter(MessageDispatcher.RR_PARAM_PROXY_APP, "true"); rrURI.setParameter(MessageDispatcher.APP_ID, sipAppKey.getId()); rrURI.setLrParam(); final Address rraddress = SipFactories.addressFactory .createAddress(null, rrURI); final RecordRouteHeader recordRouteHeader = SipFactories.headerFactory .createRecordRouteHeader(rraddress); clonedRequest.addFirst(recordRouteHeader); } if(path != null && Request.REGISTER.equalsIgnoreCase(method)) { final javax.sip.address.SipURI pathURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest); final Iterator<String> paramNames = path.getParameterNames(); while(paramNames.hasNext()) { String paramName = paramNames.next(); pathURI.setParameter(paramName, path.getParameter(paramName)); } final Address pathAddress = SipFactories.addressFactory .createAddress(null, pathURI); final PathHeader pathHeader = ((HeaderFactoryExt)SipFactories.headerFactory) .createPathHeader(pathAddress); clonedRequest.addFirst(pathHeader); } return clonedRequest; } catch (Exception e) { throw new RuntimeException("Problem while creating the proxied request for message " + originalRequest.getMessage(), e); } }
public static Request createProxiedRequest(SipServletRequestImpl originalRequest, ProxyBranchImpl proxyBranch, URI destination, SipURI outboundInterface, SipURI routeRecord, SipURI path) { try { final Request clonedRequest = (Request) originalRequest.getMessage().clone(); final String method = clonedRequest.getMethod(); final ProxyImpl proxy = (ProxyImpl) proxyBranch.getProxy(); final SipFactoryImpl sipFactoryImpl = proxy.getSipFactoryImpl(); ((MessageExt)clonedRequest).setApplicationData(null); String outboundTransport = null; RouteHeader rHeader = (RouteHeader) clonedRequest.getHeader(RouteHeader.NAME); if(rHeader != null) { String nextApp = ((javax.sip.address.SipURI)rHeader.getAddress().getURI()).getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME); if(nextApp != null) { final SipApplicationSessionKey sipAppKey = originalRequest.getSipSession().getSipApplicationSession().getKey(); final String thisApp = sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(sipAppKey.getApplicationName()); outboundTransport = ((javax.sip.address.SipURI)rHeader.getAddress().getURI()).getTransportParam(); if(outboundTransport == null) { outboundTransport = ListeningPoint.UDP; } if(nextApp.equals(thisApp)) { clonedRequest.removeHeader(RouteHeader.NAME); } } } else { if(clonedRequest.getRequestURI().isSipURI()) { outboundTransport = ((javax.sip.address.SipURI)clonedRequest.getRequestURI()).getTransportParam(); if(destination != null && destination.isSipURI()) { String destinationTransport = ((SipURI)destination).getTransportParam(); if(outboundTransport == null) { outboundTransport = destinationTransport; } else if(!outboundTransport.equalsIgnoreCase(destinationTransport)) { outboundTransport = destinationTransport; } } } } String inboundTransport = ((ViaHeader)clonedRequest.getHeader(Via.NAME)).getTransport(); if(inboundTransport == null) inboundTransport = ListeningPoint.UDP; if(destination != null) { if(logger.isDebugEnabled()){ logger.debug("request URI on the request to proxy : " + destination); } Header route = clonedRequest.getHeader("Route"); if(route == null || originalRequest.isInitial()) { if(logger.isDebugEnabled()){ logger.debug("setting request uri as cloned request has no Route headers: " + destination); } clonedRequest.setRequestURI(((URIImpl)destination).getURI()); } else { if(logger.isDebugEnabled()){ logger.debug("NOT setting request uri as cloned request has at least one Route header: " + route); } } } else { if (method.equals(Request.CANCEL)) { clonedRequest.removeHeader(ViaHeader.NAME); clonedRequest.removeHeader(RecordRouteHeader.NAME); } SipConnector sipConnector = StaticServiceHolder.sipStandardService.findSipConnector(outboundTransport); if(sipConnector != null && sipConnector.isUseStaticAddress()) { javax.sip.address.URI uri = clonedRequest.getRequestURI(); if(uri.isSipURI()) { javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) uri; JainSipUtils.optimizeUriForInternalRoutingRequest(sipConnector, sipUri, originalRequest.getSipSession(), sipFactoryImpl, outboundTransport); } if(logger.isDebugEnabled()){ logger.debug("setting request uri as cloned request has no Route headers and is using static address: " + destination); } } } MaxForwardsHeader mf = (MaxForwardsHeader) clonedRequest .getHeader(MaxForwardsHeader.NAME); if (mf == null) { mf = SipFactories.headerFactory.createMaxForwardsHeader(70); clonedRequest.addHeader(mf); } else { mf.setMaxForwards(mf.getMaxForwards() - 1); } if (method.equals(Request.CANCEL)) { clonedRequest.removeHeader(ViaHeader.NAME); } final SipApplicationSessionKey sipAppKey = originalRequest.getSipSession().getSipApplicationSession().getKey(); final String appName = sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(sipAppKey.getApplicationName()); final SipServletRequestImpl proxyBranchMatchingRequest = (SipServletRequestImpl) proxyBranch.getMatchingRequest(originalRequest); if(outboundTransport == null && destination != null) { outboundTransport = destination.getParameter("transport"); } if(proxy.getOutboundInterface() == null) { String branchId = null; if(Request.ACK.equals(method) && proxyBranchMatchingRequest != null && proxyBranchMatchingRequest.getTransaction() != null && proxyBranchMatchingRequest.getTransaction().getState() != TransactionState.TERMINATED) { branchId = proxyBranchMatchingRequest.getTransaction().getBranchId(); logger.debug("reusing original branch id " + branchId); } else { branchId = JainSipUtils.createBranch(sipAppKey.getId(), appName); } proxyBranch.viaHeader = JainSipUtils.createViaHeader( sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, branchId, null); } else { String branchId = null; if(outboundTransport == null) { outboundTransport = proxy.getOutboundInterface().getTransportParam(); if(outboundTransport == null) { if(proxy.getOutboundInterface().isSecure()) { outboundTransport = ListeningPoint.TLS; } else { outboundTransport = ListeningPoint.UDP; } } } if(Request.ACK.equals(method) && proxyBranchMatchingRequest != null && proxyBranchMatchingRequest.getTransaction() != null && proxyBranchMatchingRequest.getTransaction().getState() != TransactionState.TERMINATED) { branchId = proxyBranchMatchingRequest.getTransaction().getBranchId(); logger.debug("reusing original branch id " + branchId); } else { branchId = JainSipUtils.createBranch(sipAppKey.getId(), appName); } proxyBranch.viaHeader = SipFactories.headerFactory.createViaHeader( proxy.getOutboundInterface().getHost(), proxy.getOutboundInterface().getPort(), outboundTransport, branchId); } clonedRequest.addHeader(proxyBranch.viaHeader); if(outboundTransport == null) outboundTransport = ListeningPoint.UDP; if(clonedRequest.getHeader(RouteHeader.NAME) == null) { if(clonedRequest.getRequestURI().isSipURI()) { javax.sip.address.SipURI sipURI = ((javax.sip.address.SipURI)clonedRequest.getRequestURI()); String transportFromURI = sipURI.getTransportParam(); if(transportFromURI == null) transportFromURI = ListeningPoint.UDP; if(!transportFromURI.equalsIgnoreCase(outboundTransport)) sipURI.setTransportParam(outboundTransport); } } if(routeRecord != null && !Request.REGISTER.equalsIgnoreCase(method)) { if(!inboundTransport.equalsIgnoreCase(outboundTransport)) { javax.sip.address.SipURI inboundRURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, inboundTransport); if(originalRequest.getTransport() != null) inboundRURI.setTransportParam(originalRequest.getTransport()); final Iterator<String> paramNames = routeRecord.getParameterNames(); while(paramNames.hasNext()) { String paramName = paramNames.next(); if(!paramName.equalsIgnoreCase("transport")) { inboundRURI.setParameter(paramName, routeRecord.getParameter(paramName)); } } inboundRURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, appName); inboundRURI.setParameter(MessageDispatcher.RR_PARAM_PROXY_APP, "true"); inboundRURI.setParameter(MessageDispatcher.APP_ID, sipAppKey.getId()); inboundRURI.setLrParam(); final Address rraddress = SipFactories.addressFactory .createAddress(null, inboundRURI); final RecordRouteHeader recordRouteHeader = SipFactories.headerFactory .createRecordRouteHeader(rraddress); clonedRequest.addFirst(recordRouteHeader); } javax.sip.address.SipURI rrURI = null; if(proxy.getOutboundInterface() == null) { rrURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest, outboundTransport); } else { rrURI = ((SipURIImpl) proxy.getOutboundInterface()).getSipURI(); rrURI.setTransportParam(outboundTransport); } final Iterator<String> paramNames = routeRecord.getParameterNames(); while(paramNames.hasNext()) { String paramName = paramNames.next(); if(!paramName.equalsIgnoreCase("transport")) { rrURI.setParameter(paramName, routeRecord.getParameter(paramName)); } } rrURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, appName); rrURI.setParameter(MessageDispatcher.RR_PARAM_PROXY_APP, "true"); rrURI.setParameter(MessageDispatcher.APP_ID, sipAppKey.getId()); rrURI.setLrParam(); final Address rraddress = SipFactories.addressFactory .createAddress(null, rrURI); final RecordRouteHeader recordRouteHeader = SipFactories.headerFactory .createRecordRouteHeader(rraddress); clonedRequest.addFirst(recordRouteHeader); } if(path != null && Request.REGISTER.equalsIgnoreCase(method)) { final javax.sip.address.SipURI pathURI = JainSipUtils.createRecordRouteURI(sipFactoryImpl.getSipNetworkInterfaceManager(), clonedRequest); final Iterator<String> paramNames = path.getParameterNames(); while(paramNames.hasNext()) { String paramName = paramNames.next(); pathURI.setParameter(paramName, path.getParameter(paramName)); } final Address pathAddress = SipFactories.addressFactory .createAddress(null, pathURI); final PathHeader pathHeader = ((HeaderFactoryExt)SipFactories.headerFactory) .createPathHeader(pathAddress); clonedRequest.addFirst(pathHeader); } return clonedRequest; } catch (Exception e) { throw new RuntimeException("Problem while creating the proxied request for message " + originalRequest.getMessage(), e); } }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player player; if(sender instanceof Player) { player = (Player) sender; if(player.getItemInHand().getType() == Material.GOLD_HOE) { if(command.getName().equalsIgnoreCase("spellinfo")) { if(args.length==0) { Spell currentSpell = plugin.playerBooks.get(player.getName()).getCurrentSpell(); sender.sendMessage("Current spell " + currentSpell.abilityFormat(true) + ": " + currentSpell.getDescription()); return true; } else if (args.length==1) { if(plugin.playerBooks.get(player.getName()).getSpell(args[0]) != null) { Spell spell = plugin.playerBooks.get(player.getName()).getSpell(args[0]); sender.sendMessage(spell.abilityFormat() + ": " + spell.getDescription()); return true; } else { sender.sendMessage(ChatColor.DARK_RED + "Spell " + args[0] + " not found in your spellbook."); return true; } } else { return false; } } else if(command.getName().equalsIgnoreCase("listspells")) { sender.sendMessage("Currently available spells (arrow denotes selection:"); ArrayList<Spell> spellRegistry = plugin.playerBooks.get(player.getName()).getRegistry(); for (int iii=0;iii<spellRegistry.size();iii++) { if (spellRegistry.get(iii) == plugin.playerBooks.get(player.getName()).getCurrentSpell()) { sender.sendMessage(" - " + spellRegistry.get(iii).abilityFormat() + " <--"); } else { sender.sendMessage(" - " + spellRegistry.get(iii).abilityFormat()); } } sender.sendMessage("Key: " + ChatColor.DARK_GREEN + "(proper resources)" + ChatColor.DARK_RED + " (needs materials)"); return true; } else { plugin.log.info(this.toString() + " could not process the commmand: " + command.getName()); return false; } } else { sender.sendMessage(ChatColor.DARK_RED + "You must be wielding a Golden Scepter to use Spells."); return true; } } else { plugin.log.info(sender.getName() + " tried to use an ingame-only command."); return false; } }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player player; if(sender instanceof Player) { player = (Player) sender; if(player.getItemInHand().getType() == Material.GOLD_HOE) { if(command.getName().equalsIgnoreCase("spellinfo")) { if(args.length==0) { Spell currentSpell = plugin.playerBooks.get(player.getName()).getCurrentSpell(); sender.sendMessage("Current spell " + currentSpell.abilityFormat(true) + ": " + currentSpell.getDescription()); return true; } else if (args.length==1) { if(plugin.playerBooks.get(player.getName()).getSpell(args[0]) != null) { Spell spell = plugin.playerBooks.get(player.getName()).getSpell(args[0]); sender.sendMessage(spell.abilityFormat() + ": " + spell.getDescription()); return true; } else { sender.sendMessage(ChatColor.DARK_RED + "Spell " + args[0] + " not found in your spellbook."); return true; } } else { return false; } } else if(command.getName().equalsIgnoreCase("listspells")) { sender.sendMessage("Currently available spells (arrow denotes selection):"); ArrayList<Spell> spellRegistry = plugin.playerBooks.get(player.getName()).getRegistry(); for (int iii=0;iii<spellRegistry.size();iii++) { if (spellRegistry.get(iii) == plugin.playerBooks.get(player.getName()).getCurrentSpell()) { sender.sendMessage(" - " + spellRegistry.get(iii).abilityFormat() + " <--"); } else { sender.sendMessage(" - " + spellRegistry.get(iii).abilityFormat()); } } sender.sendMessage("Key: " + ChatColor.DARK_GREEN + "(proper resources)" + ChatColor.DARK_RED + " (needs materials)"); return true; } else { plugin.log.info(this.toString() + " could not process the commmand: " + command.getName()); return false; } } else { sender.sendMessage(ChatColor.DARK_RED + "You must be wielding a Golden Scepter to use Spells."); return true; } } else { plugin.log.info(sender.getName() + " tried to use an ingame-only command."); return false; } }
public static Boolean run(CommandSender sender, String alias, String[] args) { if (PlayerHelper.checkIsPlayer(sender)) { Player player = (Player)sender; if (Permissions.checkPerms(player, "cex.chatspy")) { if (Chat.spyActivePlayers.contains(player.getName())) { LogHelper.showInfo("chatSpyOn", sender); Chat.spyActivePlayers.remove(player.getName()); } else { LogHelper.showInfo("chatSpyOff", sender); Chat.spyActivePlayers.add(player.getName()); } } } return true; }
public static Boolean run(CommandSender sender, String alias, String[] args) { if (PlayerHelper.checkIsPlayer(sender)) { Player player = (Player)sender; if (Permissions.checkPerms(player, "cex.chatspy")) { if (Chat.spyActivePlayers.contains(player.getName())) { LogHelper.showInfo("chatSpyOff", sender); Chat.spyActivePlayers.remove(player.getName()); } else { LogHelper.showInfo("chatSpyOn", sender); Chat.spyActivePlayers.add(player.getName()); } } } return true; }
public int render(XMLLump lump, XMLLumpList collected, XMLWriter xmlw) { PrintOutputStream pos = xmlw.getInternalWriter(); RenderUtil.dumpTillLump(lump.parent.lumps, lump.lumpindex, lump.open_end.lumpindex + 1, pos); Set used = new HashSet(); for (int i = 0; i < collected.size(); ++i) { XMLLump collump = collected.lumpAt(i); String attr = URLRewriteSCR.getLinkAttribute(collump); if (attr != null) { String attrval = (String) collump.attributemap.get(attr); if (attrval != null) { String rewritten = urlRewriteSCR.resolveURL(collump.parent, attrval); int qpos = rewritten.indexOf('?'); if (qpos != -1) rewritten = rewritten.substring(0, qpos); if (used.contains(rewritten)) continue; else used.add(rewritten); } } urlRewriteSCR.render(collump, xmlw); RenderUtil.dumpTillLump(collump.parent.lumps, collump.open_end.lumpindex + 1, collump.close_tag.lumpindex + 1, pos); } return ComponentRenderer.NESTING_TAG; }
public int render(XMLLump lump, XMLLumpList collected, XMLWriter xmlw) { PrintOutputStream pos = xmlw.getInternalWriter(); RenderUtil.dumpTillLump(lump.parent.lumps, lump.lumpindex, lump.open_end.lumpindex + 1, pos); Set used = new HashSet(); for (int i = 0; i < collected.size(); ++i) { XMLLump collump = collected.lumpAt(i); String attr = URLRewriteSCR.getLinkAttribute(collump); if (attr != null) { String attrval = (String) collump.attributemap.get(attr); if (attrval != null) { String rewritten = urlRewriteSCR.resolveURL(collump.parent, attrval); if (rewritten == null) rewritten = attrval; int qpos = rewritten.indexOf('?'); if (qpos != -1) rewritten = rewritten.substring(0, qpos); if (used.contains(rewritten)) continue; else used.add(rewritten); } } urlRewriteSCR.render(collump, xmlw); RenderUtil.dumpTillLump(collump.parent.lumps, collump.open_end.lumpindex + 1, collump.close_tag.lumpindex + 1, pos); } return ComponentRenderer.NESTING_TAG; }
private String authenticate(String ticket) throws Exception { boolean isAuthenticated = false; if(logger.isInfoEnabled()) { try { throw new Exception("authenticate called with ticket:" + ticket); } catch (Exception e) { if(logger.isInfoEnabled()) logger.info("DEBUG:" + e.getMessage(), e); } } logger.info("ticket:" + ticket); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted ( java.security.cert.X509Certificate[] certs, String authType) { logger.info("Checking if client is trusted..."); } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } } }; HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost()); return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); String authenticatedUserName = null; ProxyTicketValidator pv = new ProxyTicketValidator(); if(ticket != null && ticket.substring(0, 2).equals("PT")) { pv.setCasValidateUrl(URLEncoder.encode(casProxyValidateUrl, "UTF-8")); logger.info("setting casProxyValidateUrl: " + casProxyValidateUrl); } else { pv.setCasValidateUrl(URLEncoder.encode(casServiceUrl, "UTF-8")); logger.info("setting casValidateUrl: " + casValidateUrl); } logger.info("validating: " + casServiceUrl); pv.setService(URLEncoder.encode(casServiceUrl, "UTF-8")); pv.setServiceTicket(ticket); pv.validate(); String xmlResponse = pv.getResponse(); logger.info("xmlResponse:" + xmlResponse); if(pv.isAuthenticationSuccesful()) { String user = pv.getUser(); List proxyList = pv.getProxyList(); authenticatedUserName = pv.getUser(); } else { String errorCode = pv.getErrorCode(); String errorMessage = pv.getErrorMessage(); } logger.info("proxies:\n " + pv.getProxyList()); return authenticatedUserName; }
private String authenticate(String ticket) throws Exception { boolean isAuthenticated = false; if(logger.isInfoEnabled()) { try { throw new Exception("authenticate called with ticket:" + ticket); } catch (Exception e) { if(logger.isInfoEnabled()) logger.info("DEBUG:" + e.getMessage(), e); } } logger.info("ticket:" + ticket); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted ( java.security.cert.X509Certificate[] certs, String authType) { logger.info("Checking if client is trusted..."); } public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } } }; HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost()); return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); String authenticatedUserName = null; ProxyTicketValidator pv = new ProxyTicketValidator(); if(ticket != null && ticket.substring(0, 2).equals("PT")) { pv.setCasValidateUrl(casProxyValidateUrl); logger.info("setting casProxyValidateUrl: " + casProxyValidateUrl); } else { pv.setCasValidateUrl(casValidateUrl); logger.info("setting casValidateUrl: " + casValidateUrl); } logger.info("validating: " + casServiceUrl); pv.setService(URLEncoder.encode(casServiceUrl, "UTF-8")); pv.setServiceTicket(ticket); pv.validate(); String xmlResponse = pv.getResponse(); logger.info("xmlResponse:" + xmlResponse); if(pv.isAuthenticationSuccesful()) { String user = pv.getUser(); List proxyList = pv.getProxyList(); authenticatedUserName = pv.getUser(); } else { String errorCode = pv.getErrorCode(); String errorMessage = pv.getErrorMessage(); } logger.info("proxies:\n " + pv.getProxyList()); return authenticatedUserName; }
public void testOneOp() { Action1<DebugNotification> events = mock(Action1.class); final DebugHook hook = new DebugHook(null, events); RxJavaPlugins.getInstance().registerObservableExecutionHook(hook); Observable.from(Arrays.asList(1, 3)).flatMap(new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer it) { return Observable.from(Arrays.asList(it, it + 1)); } }).take(3).subscribe(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { } }); verify(events, times(6)).call(subscribe()); verify(events, times(4)).call(onNext(1)); verify(events, times(3)).call(onNext(2)); verify(events, times(4)).call(onNext(3)); verify(events, never()).call(onNext(4)); }
public void testOneOp() { Action1<DebugNotification> events = mock(Action1.class); final DebugHook hook = new DebugHook(null, events); RxJavaPlugins.getInstance().registerObservableExecutionHook(hook); Observable.from(Arrays.asList(1, 3)).flatMap(new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer it) { return Observable.from(Arrays.asList(it, it + 1)); } }).take(3).subscribe(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer t) { } }); verify(events, atLeast(3)).call(subscribe()); verify(events, times(4)).call(onNext(1)); verify(events, times(3)).call(onNext(2)); verify(events, times(4)).call(onNext(3)); verify(events, never()).call(onNext(4)); }
private void registerRecipes() { OreDictionary.registerOre("itemRubber", rubberBarItem); OreDictionary.registerOre("woodRubber", rubberWoodBlock); FurnaceRecipes.smelting().addSmelting(rawRubberItem.shiftedIndex, 0, new ItemStack(rubberBarItem), 0.1F); FurnaceRecipes.smelting().addSmelting(rubberWoodBlock.blockID, 0, new ItemStack(Item.coal, 1, 1), 0.1F); GameRegistry.addShapelessRecipe(new ItemStack(Block.planks, 3, 3), new ItemStack(rubberWoodBlock)); GameRegistry.addRecipe(new ItemStack(plasticSheetItem, 4), new Object[] { "##", "##", Character.valueOf('#'), rawPlasticItem, } ); GameRegistry.addRecipe(new ItemStack(machineBaseItem, 3), new Object[] { "PPP", "SSS", Character.valueOf('P'), plasticSheetItem, Character.valueOf('S'), Block.stone, } ); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(syringeEmptyItem, 1), new Object[] { "PRP", "P P", " I ", Character.valueOf('P'), plasticSheetItem, Character.valueOf('R'), "itemRubber", Character.valueOf('I'), Item.ingotIron, } )); GameRegistry.addShapelessRecipe(new ItemStack(syringeHealthItem), new Object[] { syringeEmptyItem, Item.appleRed }); GameRegistry.addShapelessRecipe(new ItemStack(syringeGrowthItem), new Object[] { syringeEmptyItem, Item.goldenCarrot }); GameRegistry.addRecipe(new ItemStack(fertilizerItem, 6), new Object[] { "WBW", "STS", "WBW", Character.valueOf('W'), Item.wheat, Character.valueOf('B'), new ItemStack(Item.dyePowder, 1, 15), Character.valueOf('S'), Item.silk, Character.valueOf('T'), Item.stick, } ); GameRegistry.addRecipe(new ItemStack(safariNetItem, 1), new Object[] { " E ", "EGE", " E ", Character.valueOf('E'), Item.enderPearl, Character.valueOf('G'), Item.ghastTear, } ); GameRegistry.addRecipe(new ItemStack(factoryHammerItem, 1), new Object[] { "PPP", " S ", " S ", Character.valueOf('P'), plasticSheetItem, Character.valueOf('S'), Item.stick, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 0), new Object[] { "GGG", "CPC", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), Block.pistonBase, Character.valueOf('C'), Item.flowerPot, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 1), new Object[] { "GGG", "RRR", "BMB", Character.valueOf('G'), Item.ingotGold, Character.valueOf('R'), Item.fishingRod, Character.valueOf('B'), Item.bucketEmpty, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 2), new Object[] { "GGG", "SXS", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('X'), Item.axeGold, Character.valueOf('S'), Item.shears, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 3), new Object[] { "GGG", "SBS", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('B'), Item.bucketEmpty, Character.valueOf('S'), Item.shears, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 4), new Object[] { "GGG", "LBL", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('L'), Item.leather, Character.valueOf('B'), Item.glassBottle, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 5), new Object[] { "GGG", "SSS", "EME", Character.valueOf('G'), Item.ingotGold, Character.valueOf('E'), Item.spiderEye, Character.valueOf('S'), syringeEmptyItem, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 6), new Object[] { "GGG", " C ", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('C'), Block.chest, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 7), new Object[] { "GGG", "PHS", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), Item.pickaxeGold, Character.valueOf('H'), factoryHammerItem, Character.valueOf('S'), Item.shovelGold, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 8), new Object[] { "GGG", "BBB", "UMU", Character.valueOf('G'), Item.ingotGold, Character.valueOf('B'), Block.fenceIron, Character.valueOf('U'), Item.bucketEmpty, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 9), new Object[] { "GGG", "FFF", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('F'), Block.stoneOvenIdle, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 10), new Object[] { "GGG", "BUB", "BMB", Character.valueOf('G'), Item.ingotGold, Character.valueOf('B'), Item.brick, Character.valueOf('U'), Item.bucketEmpty, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 11), new Object[] { "GGG", "PFP", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), Block.pistonBase, Character.valueOf('F'), Block.stoneOvenIdle, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 12), new Object[] { "GGG", "CAC", "PMP", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), new ItemStack(Item.dyePowder, 1, 5), Character.valueOf('C'), Item.goldenCarrot, Character.valueOf('A'), Item.appleGold, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 13), new Object[] { "GGG", "BSP", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), Block.pistonBase, Character.valueOf('B'), Item.book, Character.valueOf('S'), Item.swordGold, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 14), new Object[] { "GGG", "BBB", "DMD", Character.valueOf('G'), Item.ingotGold, Character.valueOf('B'), Item.book, Character.valueOf('D'), Item.diamond, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 15), new Object[] { "GGG", "EEE", "PMP", Character.valueOf('G'), Item.ingotGold, Character.valueOf('E'), Item.emerald, Character.valueOf('P'), new ItemStack(Item.dyePowder, 1, 5), Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(conveyorBlock, 1, 16), new Object[] { "UUU", "RIR", Character.valueOf('U'), "itemRubber", Character.valueOf('R'), Item.redstone, Character.valueOf('I'), Item.ingotIron, } )); GameRegistry.addRecipe(new ItemStack(railPickupCargoBlock, 2), new Object[] { " C ", "SDS", "SSS", Character.valueOf('C'), Block.chest, Character.valueOf('S'), plasticSheetItem, Character.valueOf('D'), Block.railDetector } ); GameRegistry.addRecipe(new ItemStack(railDropoffCargoBlock, 2), new Object[] { "SSS", "SDS", " C ", Character.valueOf('C'), Block.chest, Character.valueOf('S'), plasticSheetItem, Character.valueOf('D'), Block.railDetector } ); GameRegistry.addRecipe(new ItemStack(railPickupPassengerBlock, 3), new Object[] { " L ", "SDS", "SSS", Character.valueOf('L'), Block.blockLapis, Character.valueOf('S'), plasticSheetItem, Character.valueOf('D'), Block.railDetector } ); GameRegistry.addRecipe(new ItemStack(railDropoffPassengerBlock, 3), new Object[] { "SSS", "SDS", " L ", Character.valueOf('L'), Block.blockLapis, Character.valueOf('S'), plasticSheetItem, Character.valueOf('D'), Block.railDetector } ); }
private void registerRecipes() { OreDictionary.registerOre("itemRubber", rubberBarItem); OreDictionary.registerOre("woodRubber", rubberWoodBlock); FurnaceRecipes.smelting().addSmelting(rawRubberItem.shiftedIndex, 0, new ItemStack(rubberBarItem), 0.1F); FurnaceRecipes.smelting().addSmelting(rubberWoodBlock.blockID, 0, new ItemStack(Item.coal, 1, 1), 0.1F); GameRegistry.addShapelessRecipe(new ItemStack(Block.planks, 3, 3), new ItemStack(rubberWoodBlock)); GameRegistry.addRecipe(new ItemStack(plasticSheetItem, 4), new Object[] { "##", "##", Character.valueOf('#'), rawPlasticItem, } ); GameRegistry.addRecipe(new ItemStack(machineBaseItem, 3), new Object[] { "PPP", "SSS", Character.valueOf('P'), plasticSheetItem, Character.valueOf('S'), Block.stone, } ); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(syringeEmptyItem, 1), new Object[] { "PRP", "P P", " I ", Character.valueOf('P'), plasticSheetItem, Character.valueOf('R'), "itemRubber", Character.valueOf('I'), Item.ingotIron, } )); GameRegistry.addShapelessRecipe(new ItemStack(syringeHealthItem), new Object[] { syringeEmptyItem, Item.appleRed }); GameRegistry.addShapelessRecipe(new ItemStack(syringeGrowthItem), new Object[] { syringeEmptyItem, Item.goldenCarrot }); GameRegistry.addRecipe(new ItemStack(fertilizerItem, 6), new Object[] { "WBW", "STS", "WBW", Character.valueOf('W'), Item.wheat, Character.valueOf('B'), new ItemStack(Item.dyePowder, 1, 15), Character.valueOf('S'), Item.silk, Character.valueOf('T'), Item.stick, } ); GameRegistry.addRecipe(new ItemStack(safariNetItem, 1), new Object[] { " E ", "EGE", " E ", Character.valueOf('E'), Item.enderPearl, Character.valueOf('G'), Item.ghastTear, } ); GameRegistry.addRecipe(new ItemStack(factoryHammerItem, 1), new Object[] { "PPP", " S ", " S ", Character.valueOf('P'), plasticSheetItem, Character.valueOf('S'), Item.stick, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 0), new Object[] { "GGG", "CPC", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), Block.pistonBase, Character.valueOf('C'), Item.flowerPot, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 1), new Object[] { "GGG", "RRR", "BMB", Character.valueOf('G'), Item.ingotGold, Character.valueOf('R'), Item.fishingRod, Character.valueOf('B'), Item.bucketEmpty, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 2), new Object[] { "GGG", "SXS", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('X'), Item.axeGold, Character.valueOf('S'), Item.shears, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 3), new Object[] { "GGG", "SBS", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('B'), Item.bucketEmpty, Character.valueOf('S'), Item.shears, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 4), new Object[] { "GGG", "LBL", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('L'), Item.leather, Character.valueOf('B'), Item.glassBottle, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 5), new Object[] { "GGG", "SSS", "EME", Character.valueOf('G'), Item.ingotGold, Character.valueOf('E'), Item.spiderEye, Character.valueOf('S'), syringeEmptyItem, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 6), new Object[] { "GGG", " C ", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('C'), Block.chest, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 7), new Object[] { "GGG", "PHS", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), Item.pickaxeGold, Character.valueOf('H'), factoryHammerItem, Character.valueOf('S'), Item.shovelGold, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 8), new Object[] { "GGG", "BBB", "UMU", Character.valueOf('G'), Item.ingotGold, Character.valueOf('B'), Block.fenceIron, Character.valueOf('U'), Item.bucketEmpty, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 9), new Object[] { "GGG", "FFF", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('F'), Block.stoneOvenIdle, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 10), new Object[] { "GGG", "BUB", "BMB", Character.valueOf('G'), Item.ingotGold, Character.valueOf('B'), Item.brick, Character.valueOf('U'), Item.bucketEmpty, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 11), new Object[] { "GGG", "PFP", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), Block.pistonBase, Character.valueOf('F'), Block.stoneOvenIdle, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 12), new Object[] { "GGG", "CAC", "PMP", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), new ItemStack(Item.dyePowder, 1, 5), Character.valueOf('C'), Item.goldenCarrot, Character.valueOf('A'), Item.appleGold, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 13), new Object[] { "GGG", "BSP", " M ", Character.valueOf('G'), Item.ingotGold, Character.valueOf('P'), Block.pistonBase, Character.valueOf('B'), Item.book, Character.valueOf('S'), Item.swordGold, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 14), new Object[] { "GGG", "BBB", "DMD", Character.valueOf('G'), Item.ingotGold, Character.valueOf('B'), Item.book, Character.valueOf('D'), Item.diamond, Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ItemStack(machineBlock, 1, 15), new Object[] { "GGG", "EEE", "PMP", Character.valueOf('G'), Item.ingotGold, Character.valueOf('E'), Item.emerald, Character.valueOf('P'), new ItemStack(Item.dyePowder, 1, 5), Character.valueOf('M'), machineBaseItem, } ); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(conveyorBlock, 16), new Object[] { "UUU", "RIR", Character.valueOf('U'), "itemRubber", Character.valueOf('R'), Item.redstone, Character.valueOf('I'), Item.ingotIron, } )); GameRegistry.addRecipe(new ItemStack(railPickupCargoBlock, 2), new Object[] { " C ", "SDS", "SSS", Character.valueOf('C'), Block.chest, Character.valueOf('S'), plasticSheetItem, Character.valueOf('D'), Block.railDetector } ); GameRegistry.addRecipe(new ItemStack(railDropoffCargoBlock, 2), new Object[] { "SSS", "SDS", " C ", Character.valueOf('C'), Block.chest, Character.valueOf('S'), plasticSheetItem, Character.valueOf('D'), Block.railDetector } ); GameRegistry.addRecipe(new ItemStack(railPickupPassengerBlock, 3), new Object[] { " L ", "SDS", "SSS", Character.valueOf('L'), Block.blockLapis, Character.valueOf('S'), plasticSheetItem, Character.valueOf('D'), Block.railDetector } ); GameRegistry.addRecipe(new ItemStack(railDropoffPassengerBlock, 3), new Object[] { "SSS", "SDS", " L ", Character.valueOf('L'), Block.blockLapis, Character.valueOf('S'), plasticSheetItem, Character.valueOf('D'), Block.railDetector } ); }
public void onPlayerInteractEvent(PlayerInteractEvent event) { Block b = event.getClickedBlock(); if(b == null || !(event.getClickedBlock() instanceof Block) || !(event.getPlayer() instanceof Player)) return; if(b.getTypeId() == configManager.interactBlock && !event.getPlayer().isSneaking()) { int id = this.helper.getIDbyBlock(b); if(id != 0) { KBArea a = this.helper.getArea(id); if(a != null) { Scoreboard bd = this.bh.generateNewBoard(); Objective o = bd.registerNewObjective("infos", "dummy"); o.setDisplaySlot(DisplaySlot.SIDEBAR); int miet = 0, preis = 0; if(a.miet > 0) { if(a.miet == 1) miet = a.price; else miet = a.miet; } if(a.sold == 1) preis = a.paid; else preis = a.price; if(configManager.lang.equalsIgnoreCase("de")) { if(a.sold == 0 && a.nobuy == 0) o.setDisplayName("GS Zum Verkauf"); else if(a.sold == 0 && a.nobuy == 1) o.setDisplayName("GS Unverkaueflich"); else if(a.sold == 1) o.setDisplayName("GS von "+a.owner); o.getScore(Bukkit.getOfflinePlayer("Hoehe:")).setScore(a.height); o.getScore(Bukkit.getOfflinePlayer("Keller:")).setScore(a.deep); o.getScore(Bukkit.getOfflinePlayer("Wert:")).setScore(preis); if(miet != 0) o.getScore(Bukkit.getOfflinePlayer("Miete:")).setScore(miet); } else { if(a.sold == 0 && a.nobuy == 0) o.setDisplayName("Lot for sale"); else if(a.sold == 0 && a.nobuy == 1) o.setDisplayName("Unbuyable lot"); else if(a.sold == 1) o.setDisplayName("Lot of "+a.owner); o.getScore(Bukkit.getOfflinePlayer("Height:")).setScore(a.height); o.getScore(Bukkit.getOfflinePlayer("Basement:")).setScore(a.deep); o.getScore(Bukkit.getOfflinePlayer("Value:")).setScore(preis); if(miet != 0) o.getScore(Bukkit.getOfflinePlayer("Rent:")).setScore(miet); } this.bh.registerPrivateBoard(event.getPlayer(), "krimbuy_detail_"+id, bd); this.bh.showBoardToPlayer(event.getPlayer(), "krimbuy_detail_"+id); Bukkit.getServer().getScheduler().runTaskLater(this.m, new removeBoard(this,event.getPlayer(),"krimbuy_detail_"+id), 10*20); } } } }
public void onPlayerInteractEvent(PlayerInteractEvent event) { Block b = event.getClickedBlock(); if(b == null || !(event.getClickedBlock() instanceof Block) || !(event.getPlayer() instanceof Player)) return; if(b.getTypeId() == configManager.interactBlock && !event.getPlayer().isSneaking()) { int id = this.helper.getIDbyBlock(b); if(id != 0) { KBArea a = this.helper.getArea(id); if(a != null) { Scoreboard bd = this.bh.generateNewBoard(); Objective o = bd.registerNewObjective("infos", "dummy"); o.setDisplaySlot(DisplaySlot.SIDEBAR); int miet = 0, preis = 0; if(a.miet > 0) { if(a.miet == 1) miet = a.price; else miet = a.miet; } if(a.sold == 1) preis = a.paid; else preis = a.price; if(configManager.lang.equalsIgnoreCase("de")) { if(a.sold == 0 && a.nobuy == 0) o.setDisplayName("GS Zum Verkauf"); else if(a.sold == 0 && a.nobuy == 1) o.setDisplayName("GS Unverkaueflich"); else if(a.sold == 1) o.setDisplayName(a.gruppe+" von "+a.owner); o.getScore(Bukkit.getOfflinePlayer("Hoehe:")).setScore(a.height); o.getScore(Bukkit.getOfflinePlayer("Keller:")).setScore(a.deep); o.getScore(Bukkit.getOfflinePlayer("Preis:")).setScore(preis); o.getScore(Bukkit.getOfflinePlayer("Level:")).setScore(a.level); if(miet != 0) o.getScore(Bukkit.getOfflinePlayer("Miete:")).setScore(miet); } else { if(a.sold == 0 && a.nobuy == 0) o.setDisplayName("Lot for sale"); else if(a.sold == 0 && a.nobuy == 1) o.setDisplayName("Unbuyable lot"); else if(a.sold == 1) o.setDisplayName(a.gruppe+" of "+a.owner); o.getScore(Bukkit.getOfflinePlayer("Height:")).setScore(a.height); o.getScore(Bukkit.getOfflinePlayer("Basement:")).setScore(a.deep); o.getScore(Bukkit.getOfflinePlayer("Value:")).setScore(preis); o.getScore(Bukkit.getOfflinePlayer("Level:")).setScore(a.level); if(miet != 0) o.getScore(Bukkit.getOfflinePlayer("Rent:")).setScore(miet); } this.bh.registerPrivateBoard(event.getPlayer(), "krimbuy_detail_"+id, bd); this.bh.showBoardToPlayer(event.getPlayer(), "krimbuy_detail_"+id); Bukkit.getServer().getScheduler().runTaskLater(this.m, new removeBoard(this,event.getPlayer(),"krimbuy_detail_"+id), 10*20); } } } }
public String commit() throws RepositoryStateException { if (this.commiterEmail == null || this.commiterName == null || this.commitMessage == null || this.authorEmail == null || this.authorName == null) { throw new RepositoryStateException("Requiring all fields to be filled, before executing a commit..."); } this.log.debug("Doing commit for author [" + this.authorName + "; " + this.authorEmail + "] with message [" + this.commitMessage + "]..."); try { this.log.trace("Writing index..."); this.index.write(); } catch (IOException e) { throw new RepositoryStateException("Cant write index...", e); } IndexDiff diff; try { this.log.trace("Creating diff from index..."); diff = new IndexDiff(this.repository.mapTree(Constants.HEAD), this.repository.getIndex()); diff.diff(); } catch (IOException e) { throw new RepositoryStateException("Cant write diff tree...", e); } HashSet<String> allFiles = new HashSet<String>(); allFiles.addAll(diff.getAdded()); allFiles.addAll(diff.getChanged()); allFiles.addAll(diff.getModified()); allFiles.addAll(diff.getRemoved()); this.log.debug("[" + allFiles.size() + "] files changed and to commit..."); try { this.log.trace("creating repository tree..."); Tree projectTree = this.repository.mapTree(Constants.HEAD); if (projectTree == null) { projectTree = new Tree(this.repository); } this.log.trace("Iterating each files and write the trees for each of them..."); for (String string : allFiles) { File actualFile = new File(this.repositoryPath.getAbsolutePath() + File.separator + string); this.log.debug("Writing file [" + actualFile.getAbsolutePath() + "] to index..."); TreeEntry treeMember = projectTree.findBlobMember(string); if (treeMember != null) { treeMember.delete(); } this.log.trace("Getting entry index..."); Entry idxEntry = this.index.getEntry(string); if (diff.getMissing().contains(actualFile)) { this.log.debug("For any reason file is missing and situation have to be handeld..."); File thisFile = new File(this.repositoryPath, string); if (!thisFile.isFile()) { this.index.remove(this.repositoryPath, thisFile); this.index.write(); continue; } else { if (idxEntry.update(thisFile)) { this.index.write(); } } } this.log.trace("Adding file to tree..."); if (idxEntry != null) { projectTree.addFile(string); TreeEntry newMember = projectTree.findBlobMember(string); newMember.setId(idxEntry.getObjectId()); } } this.log.debug("Writing tree with subtrees..."); writeTreeWithSubTrees(projectTree); this.log.trace("Retrieving current ids for commit..."); ObjectId currentHeadId = this.repository.resolve(Constants.HEAD); ObjectId[] parentIds; if (currentHeadId != null) { parentIds = new ObjectId[] { currentHeadId }; } else { parentIds = new ObjectId[0]; } this.log.trace("Creating commit object and prepare for commit..."); org.eclipse.jgit.lib.Commit commit = new org.eclipse.jgit.lib.Commit(this.repository, parentIds); commit.setTree(projectTree); commit.setMessage(this.commitMessage); commit.setAuthor(new PersonIdent(this.authorName, this.authorEmail)); commit.setCommitter(new PersonIdent(this.commiterName, this.commiterEmail)); this.log.debug("Writing commit to disk..."); ObjectWriter writer = new ObjectWriter(this.repository); commit.setCommitId(writer.writeCommit(commit)); RefUpdate ru = this.repository.updateRef(Constants.HEAD); ru.setNewObjectId(commit.getCommitId()); ru.setRefLogMessage(this.commitMessage, true); if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) { throw new RepositoryStateException("Failed to update " + ru.getName() + " to commit " + commit.getCommitId() + "."); } return commit.getCommitId().name(); } catch (Exception e) { throw new RepositoryStateException("Cant do commit...", e); } }
public String commit() throws RepositoryStateException { if (this.commiterEmail == null || this.commiterName == null || this.commitMessage == null || this.authorEmail == null || this.authorName == null) { throw new RepositoryStateException("Requiring all fields to be filled, before executing a commit..."); } this.log.debug("Doing commit for author [" + this.authorName + "; " + this.authorEmail + "] with message [" + this.commitMessage + "]..."); try { this.log.trace("Writing index..."); this.index.write(); } catch (IOException e) { throw new RepositoryStateException("Cant write index...", e); } IndexDiff diff; try { this.log.trace("Creating diff from index..."); diff = new IndexDiff(this.repository.mapTree(Constants.HEAD), this.repository.getIndex()); diff.diff(); } catch (IOException e) { throw new RepositoryStateException("Cant write diff tree...", e); } HashSet<String> allFiles = new HashSet<String>(); allFiles.addAll(diff.getAdded()); allFiles.addAll(diff.getChanged()); allFiles.addAll(diff.getModified()); allFiles.addAll(diff.getRemoved()); this.log.debug("[" + allFiles.size() + "] files changed and to commit..."); try { this.log.trace("creating repository tree..."); Tree projectTree = this.repository.mapTree(Constants.HEAD); if (projectTree == null) { projectTree = new Tree(this.repository); } this.log.trace("Iterating each files and write the trees for each of them..."); for (String string : allFiles) { File actualFile = new File(this.repositoryPath.getAbsolutePath() + File.separator + string); this.log.debug("Writing file [" + actualFile.getAbsolutePath() + "] to index..."); TreeEntry treeMember = projectTree.findBlobMember(string); if (treeMember != null) { treeMember.delete(); } this.log.trace("Getting entry index..."); Entry idxEntry = this.index.getEntry(string); if (diff.getMissing().contains(string)) { this.log.debug("For any reason file is missing and situation have to be handeld..."); File thisFile = new File(this.repositoryPath, string); if (!thisFile.isFile()) { this.index.remove(this.repositoryPath, thisFile); continue; } else { idxEntry.update(thisFile); } } this.log.trace("Adding file to tree..."); if (idxEntry != null) { projectTree.addFile(string); TreeEntry newMember = projectTree.findBlobMember(string); newMember.setId(idxEntry.getObjectId()); } } this.index.write(); this.log.debug("Writing tree with subtrees..."); writeTreeWithSubTrees(projectTree); this.log.trace("Retrieving current ids for commit..."); ObjectId currentHeadId = this.repository.resolve(Constants.HEAD); ObjectId[] parentIds; if (currentHeadId != null) { parentIds = new ObjectId[] { currentHeadId }; } else { parentIds = new ObjectId[0]; } this.log.trace("Creating commit object and prepare for commit..."); org.eclipse.jgit.lib.Commit commit = new org.eclipse.jgit.lib.Commit(this.repository, parentIds); commit.setTree(projectTree); commit.setMessage(this.commitMessage); commit.setAuthor(new PersonIdent(this.authorName, this.authorEmail)); commit.setCommitter(new PersonIdent(this.commiterName, this.commiterEmail)); this.log.debug("Writing commit to disk..."); ObjectWriter writer = new ObjectWriter(this.repository); commit.setCommitId(writer.writeCommit(commit)); RefUpdate ru = this.repository.updateRef(Constants.HEAD); ru.setNewObjectId(commit.getCommitId()); ru.setRefLogMessage(this.commitMessage, true); if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE) { throw new RepositoryStateException("Failed to update " + ru.getName() + " to commit " + commit.getCommitId() + "."); } return commit.getCommitId().name(); } catch (Exception e) { throw new RepositoryStateException("Cant do commit...", e); } }
public Option[] config() { String apiBundleVersion = System.getProperty("cytoscape.api.version"); String implBundleVersion = System.getProperty("cytoscape.impl.version"); return options( junitBundles(), felix(), frameworkStartLevel(50), repository("http://code.cytoscape.org/nexus/content/repositories/snapshots/"), repository("http://code.cytoscape.org/nexus/content/repositories/releases/"), repository("http://code.cytoscape.org/nexus/content/repositories/thirdparty/"), mavenBundle().groupId("cytoscape-sun").artifactId("jhall").version("1.0").startLevel(3), mavenBundle().groupId("com.googlecode.guava-osgi").artifactId("guava-osgi").version("9.0.0").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("parallelcolt").version("0.9.4").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("opencsv").version("2.1").startLevel(3), mavenBundle().groupId("com.lowagie.text").artifactId("com.springsource.com.lowagie.text").version("2.0.8").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-graphicsio").version("2.1.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-graphicsio-svg").version("2.1.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-graphicsio-ps").version("2.1.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-graphics2d").version("2.1.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("l2fprod-common-shared").version("7.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("l2fprod-common-fontchooser").version("7.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("l2fprod-common-sheet").version("7.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("org.swinglabs.swingx").version("1.6.1").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-export").version("2.1.1").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-util").version("2.0.2").startLevel(3), mavenBundle().groupId("org.cytoscape").artifactId("event-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("model-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("group-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("viewmodel-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("presentation-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("vizmap-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("session-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("io-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("property-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("work-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("core-task-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("application-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("layout-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("datasource-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("vizmap-gui-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("work-swing-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("swing-application-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("equations-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("swing-application-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("service-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("property-impl").version(implBundleVersion).startLevel(7), mavenBundle().groupId("org.cytoscape").artifactId("swing-util-api").version(apiBundleVersion).startLevel(8), mavenBundle().groupId("org.cytoscape").artifactId("datasource-impl").version(implBundleVersion).startLevel(9), mavenBundle().groupId("org.cytoscape").artifactId("equations-impl").version(implBundleVersion).startLevel(9), mavenBundle().groupId("org.cytoscape").artifactId("event-impl").version(implBundleVersion).startLevel(9), mavenBundle().groupId("org.cytoscape").artifactId("model-impl").version(implBundleVersion).startLevel(11), mavenBundle().groupId("org.cytoscape").artifactId("group-impl").version(implBundleVersion).startLevel(11), mavenBundle().groupId("org.cytoscape").artifactId("work-impl").version(implBundleVersion).startLevel(11), mavenBundle().groupId("org.cytoscape").artifactId("work-headless-impl").version(implBundleVersion).startLevel(11), mavenBundle().groupId("org.cytoscape").artifactId("presentation-impl").version(implBundleVersion).startLevel(13), mavenBundle().groupId("org.cytoscape").artifactId("layout-impl").version(implBundleVersion).startLevel(15), mavenBundle().groupId("org.cytoscape").artifactId("viewmodel-impl").version(implBundleVersion).startLevel(15), mavenBundle().groupId("org.cytoscape").artifactId("vizmap-impl").version(implBundleVersion).startLevel(15), mavenBundle().groupId("org.cytoscape").artifactId("application-impl").version(implBundleVersion).startLevel(17), mavenBundle().groupId("org.cytoscape").artifactId("session-impl").version(implBundleVersion).startLevel(19), mavenBundle().groupId("org.cytoscape").artifactId("ding-presentation-impl").version(implBundleVersion).startLevel(21), mavenBundle().groupId("org.cytoscape").artifactId("io-impl").version(implBundleVersion).startLevel(23), mavenBundle().groupId("org.cytoscape").artifactId("core-task-impl").version(implBundleVersion).startLevel(25), mavenBundle().groupId("org.cytoscape").artifactId("vizmap-gui-impl").version(implBundleVersion).startLevel(27) ); }
public Option[] config() { String apiBundleVersion = System.getProperty("cytoscape.api.version"); String implBundleVersion = System.getProperty("cytoscape.impl.version"); return options( junitBundles(), felix(), frameworkStartLevel(50), repository("http://code.cytoscape.org/nexus/content/repositories/snapshots/"), repository("http://code.cytoscape.org/nexus/content/repositories/releases/"), repository("http://code.cytoscape.org/nexus/content/repositories/thirdparty/"), mavenBundle().groupId("cytoscape-sun").artifactId("jhall").version("1.0").startLevel(3), mavenBundle().groupId("com.googlecode.guava-osgi").artifactId("guava-osgi").version("9.0.0").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("parallelcolt").version("0.9.4").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("opencsv").version("2.1").startLevel(3), mavenBundle().groupId("com.lowagie.text").artifactId("com.springsource.com.lowagie.text").version("2.0.8").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-graphicsio").version("2.1.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-graphicsio-svg").version("2.1.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-graphicsio-ps").version("2.1.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-graphics2d").version("2.1.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("l2fprod-common-shared").version("7.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("l2fprod-common-fontchooser").version("7.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("l2fprod-common-sheet").version("7.3").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("org.swinglabs.swingx").version("1.6.1").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-export").version("2.1.1").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("freehep-util").version("2.0.2").startLevel(3), mavenBundle().groupId("cytoscape-temp").artifactId("protostuff-core-json-osgi").version("1.0.7").startLevel(3), mavenBundle().groupId("org.codehaus.jackson").artifactId("jackson-core-lgpl").version("1.9.7").startLevel(3), mavenBundle().groupId("org.cytoscape").artifactId("event-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("model-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("group-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("viewmodel-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("presentation-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("vizmap-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("session-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("io-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("property-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("work-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("core-task-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("application-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("layout-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("datasource-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("vizmap-gui-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("work-swing-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("swing-application-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("equations-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("swing-application-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("service-api").version(apiBundleVersion).startLevel(5), mavenBundle().groupId("org.cytoscape").artifactId("property-impl").version(implBundleVersion).startLevel(7), mavenBundle().groupId("org.cytoscape").artifactId("swing-util-api").version(apiBundleVersion).startLevel(8), mavenBundle().groupId("org.cytoscape").artifactId("datasource-impl").version(implBundleVersion).startLevel(9), mavenBundle().groupId("org.cytoscape").artifactId("equations-impl").version(implBundleVersion).startLevel(9), mavenBundle().groupId("org.cytoscape").artifactId("event-impl").version(implBundleVersion).startLevel(9), mavenBundle().groupId("org.cytoscape").artifactId("model-impl").version(implBundleVersion).startLevel(11), mavenBundle().groupId("org.cytoscape").artifactId("group-impl").version(implBundleVersion).startLevel(11), mavenBundle().groupId("org.cytoscape").artifactId("work-impl").version(implBundleVersion).startLevel(11), mavenBundle().groupId("org.cytoscape").artifactId("work-headless-impl").version(implBundleVersion).startLevel(11), mavenBundle().groupId("org.cytoscape").artifactId("presentation-impl").version(implBundleVersion).startLevel(13), mavenBundle().groupId("org.cytoscape").artifactId("layout-impl").version(implBundleVersion).startLevel(15), mavenBundle().groupId("org.cytoscape").artifactId("viewmodel-impl").version(implBundleVersion).startLevel(15), mavenBundle().groupId("org.cytoscape").artifactId("vizmap-impl").version(implBundleVersion).startLevel(15), mavenBundle().groupId("org.cytoscape").artifactId("application-impl").version(implBundleVersion).startLevel(17), mavenBundle().groupId("org.cytoscape").artifactId("session-impl").version(implBundleVersion).startLevel(19), mavenBundle().groupId("org.cytoscape").artifactId("ding-presentation-impl").version(implBundleVersion).startLevel(21), mavenBundle().groupId("org.cytoscape").artifactId("io-impl").version(implBundleVersion).startLevel(23), mavenBundle().groupId("org.cytoscape").artifactId("core-task-impl").version(implBundleVersion).startLevel(25), mavenBundle().groupId("org.cytoscape").artifactId("vizmap-gui-impl").version(implBundleVersion).startLevel(27) ); }
public static void actionManagement(HttpServletRequest request, boolean isAdmin, boolean isModerator, String userId, ResourceLocator resource, JspWriter out, ForumsSessionController fsc) { int action = ForumHelper.getIntParameter(request, "action"); if (action != -1) { int params = ForumHelper.getIntParameter(request, "params"); try { switch (action) { case DEPLOY_FORUM: { fsc.deployForum(params); break; } case UNDEPLOY_FORUM: { fsc.undeployForum(params); break; } case CREATE_FORUM: { String forumName = request.getParameter("forumName").trim(); String forumDescription = request.getParameter("forumDescription").trim(); String[] forumModerators = request.getParameterValues("moderators"); int forumParent = ForumHelper.getIntParameter(request, "forumFolder"); String categoryId = request.getParameter("CategoryId").trim(); String keywords = request.getParameter("forumKeywords").trim(); String positions = request.getParameter("Positions"); fsc.setForumPositions(positions); int forumId = fsc.createForum(forumName, forumDescription, userId, forumParent, categoryId, keywords); if (forumModerators != null) { for (String moderator : forumModerators) { fsc.addModerator(forumId, moderator.trim()); } } break; } case DELETE_FORUM: { fsc.deleteForum(params); break; } case LOCK_FORUM: { if (isAdmin) { fsc.lockForum(params, 1); } else if (isModerator) { fsc.lockForum(params, 2); } break; } case UNLOCK_FORUM: { boolean success = true; if (isAdmin) { success = fsc.unlockForum(params, 1) == 0; } else if (isModerator) { success = fsc.unlockForum(params, 2) == 0; } if (success) { out.println("<script language=\"Javascript\">"); out.println("alert(\"" + resource.getString("adminTopicLock") + "\");"); out.println("</script>"); } break; } case UPDATE_FORUM: { String forumName = request.getParameter("forumName").trim(); String forumDescription = request.getParameter("forumDescription").trim(); int forumId = ForumHelper.getIntParameter(request, "forumId"); String keywords = request.getParameter("forumKeywords").trim(); int forumParent = ForumHelper.getIntParameter(request, "forumFolder"); String[] forumModerators = request.getParameterValues("moderators"); fsc.removeAllModerators(forumId); if (forumModerators != null) { for (String moderator : forumModerators) { fsc.addModerator(forumId, moderator.trim()); } } String categoryId = request.getParameter("CategoryId").trim(); fsc .updateForum(forumId, forumName, forumDescription, forumParent, categoryId, keywords); break; } case CREATE_MESSAGE: { int forumId = ForumHelper.getIntParameter(request, "forumId"); int parentId = ForumHelper.getIntParameter(request, "parentId", 0); String messageTitle = request.getParameter("messageTitle").trim(); String messageText = request.getParameter("messageText").trim(); String forumKeywords = request.getParameter("forumKeywords"); String subscribe = request.getParameter("subscribeMessage"); if (StringUtil.isDefined(messageTitle) && StringUtil.isDefined(messageText)) { Collection<UploadedFile> uploadedFiles = FileUploadManager.getUploadedFiles(request); int result = fsc.createMessage(messageTitle, userId, forumId, parentId, messageText, forumKeywords, uploadedFiles); if (subscribe == null) { subscribe = "0"; } else { subscribe = "1"; if (result != 0) { fsc.subscribeMessage(result, userId); } } if (parentId > 0) { fsc.deployMessage(parentId); } } break; } case DELETE_MESSAGE: { fsc.deleteMessage(params); break; } case DEPLOY_MESSAGE: { fsc.deployMessage(params); break; } case UNDEPLOY_MESSAGE: { fsc.undeployMessage(params); break; } case MOVE_MESSAGE: { int messageId = ForumHelper.getIntParameter(request, "messageId"); int folderId = ForumHelper.getIntParameter(request, "messageNewFolder"); fsc.moveMessage(messageId, folderId); break; } case UNSUBSCRIBE_THREAD: { fsc.unsubscribeMessage(params, userId); break; } case SUBSCRIBE_THREAD: { fsc.subscribeMessage(params, userId); break; } case UPDATE_MESSAGE: { int messageId = ForumHelper.getIntParameter(request, "messageId"); String keywords = request.getParameter("forumKeywords").trim(); fsc.updateMessageKeywords(messageId, keywords); break; } case EVALUATE_FORUM: { int forumId = ForumHelper.getIntParameter(request, "forumId"); int note = ForumHelper.getIntParameter(request, "note", -1); if (note > 0) { fsc.updateForumNotation(forumId, note); } break; } } } catch (NumberFormatException nfe) { SilverTrace.info( "forums", "JSPforumsListActionManager", "root.EX_NO_MESSAGE", null, nfe); } catch (IOException ioe) { SilverTrace.info( "forums", "JSPforumsListActionManager", "root.EX_NO_MESSAGE", null, ioe); } } }
public static void actionManagement(HttpServletRequest request, boolean isAdmin, boolean isModerator, String userId, ResourceLocator resource, JspWriter out, ForumsSessionController fsc) { int action = ForumHelper.getIntParameter(request, "action"); if (action != -1) { int params = ForumHelper.getIntParameter(request, "params"); try { switch (action) { case DEPLOY_FORUM: { fsc.deployForum(params); break; } case UNDEPLOY_FORUM: { fsc.undeployForum(params); break; } case CREATE_FORUM: { String forumName = request.getParameter("forumName").trim(); String forumDescription = request.getParameter("forumDescription").trim(); String[] forumModerators = request.getParameterValues("moderators"); int forumParent = ForumHelper.getIntParameter(request, "forumFolder"); String categoryId = request.getParameter("CategoryId").trim(); String keywords = request.getParameter("forumKeywords").trim(); String positions = request.getParameter("Positions"); fsc.setForumPositions(positions); int forumId = fsc.createForum(forumName, forumDescription, userId, forumParent, categoryId, keywords); if (forumModerators != null) { for (String moderator : forumModerators) { fsc.addModerator(forumId, moderator.trim()); } } request.setAttribute("nbChildrens", fsc.getForumSonsNb(forumParent)); break; } case DELETE_FORUM: { fsc.deleteForum(params); int forumId = ForumHelper.getIntParameter(request, "forumId"); request.setAttribute("nbChildrens", fsc.getForumSonsNb(forumId)); break; } case LOCK_FORUM: { if (isAdmin) { fsc.lockForum(params, 1); } else if (isModerator) { fsc.lockForum(params, 2); } break; } case UNLOCK_FORUM: { boolean success = true; if (isAdmin) { success = fsc.unlockForum(params, 1) == 0; } else if (isModerator) { success = fsc.unlockForum(params, 2) == 0; } if (success) { out.println("<script language=\"Javascript\">"); out.println("alert(\"" + resource.getString("adminTopicLock") + "\");"); out.println("</script>"); } break; } case UPDATE_FORUM: { String forumName = request.getParameter("forumName").trim(); String forumDescription = request.getParameter("forumDescription").trim(); int forumId = ForumHelper.getIntParameter(request, "forumId"); String keywords = request.getParameter("forumKeywords").trim(); int forumParent = ForumHelper.getIntParameter(request, "forumFolder"); String[] forumModerators = request.getParameterValues("moderators"); fsc.removeAllModerators(forumId); if (forumModerators != null) { for (String moderator : forumModerators) { fsc.addModerator(forumId, moderator.trim()); } } String categoryId = request.getParameter("CategoryId").trim(); fsc .updateForum(forumId, forumName, forumDescription, forumParent, categoryId, keywords); break; } case CREATE_MESSAGE: { int forumId = ForumHelper.getIntParameter(request, "forumId"); int parentId = ForumHelper.getIntParameter(request, "parentId", 0); String messageTitle = request.getParameter("messageTitle").trim(); String messageText = request.getParameter("messageText").trim(); String forumKeywords = request.getParameter("forumKeywords"); String subscribe = request.getParameter("subscribeMessage"); if (StringUtil.isDefined(messageTitle) && StringUtil.isDefined(messageText)) { Collection<UploadedFile> uploadedFiles = FileUploadManager.getUploadedFiles(request); int result = fsc.createMessage(messageTitle, userId, forumId, parentId, messageText, forumKeywords, uploadedFiles); if (subscribe == null) { subscribe = "0"; } else { subscribe = "1"; if (result != 0) { fsc.subscribeMessage(result, userId); } } if (parentId > 0) { fsc.deployMessage(parentId); } } break; } case DELETE_MESSAGE: { fsc.deleteMessage(params); break; } case DEPLOY_MESSAGE: { fsc.deployMessage(params); break; } case UNDEPLOY_MESSAGE: { fsc.undeployMessage(params); break; } case MOVE_MESSAGE: { int messageId = ForumHelper.getIntParameter(request, "messageId"); int folderId = ForumHelper.getIntParameter(request, "messageNewFolder"); fsc.moveMessage(messageId, folderId); break; } case UNSUBSCRIBE_THREAD: { fsc.unsubscribeMessage(params, userId); break; } case SUBSCRIBE_THREAD: { fsc.subscribeMessage(params, userId); break; } case UPDATE_MESSAGE: { int messageId = ForumHelper.getIntParameter(request, "messageId"); String keywords = request.getParameter("forumKeywords").trim(); fsc.updateMessageKeywords(messageId, keywords); break; } case EVALUATE_FORUM: { int forumId = ForumHelper.getIntParameter(request, "forumId"); int note = ForumHelper.getIntParameter(request, "note", -1); if (note > 0) { fsc.updateForumNotation(forumId, note); } break; } } } catch (NumberFormatException nfe) { SilverTrace.info( "forums", "JSPforumsListActionManager", "root.EX_NO_MESSAGE", null, nfe); } catch (IOException ioe) { SilverTrace.info( "forums", "JSPforumsListActionManager", "root.EX_NO_MESSAGE", null, ioe); } } }
public boolean execute(PlugInContext context) throws Exception { IEditor editor = context.getActiveEditor(); final TableEditableElement element = (TableEditableElement) editor.getElement(); TableComponent currentTable = (TableComponent) editor.getView().getComponent(); final int rowIndex = currentTable.getTable().rowAtPoint( getEvent().getPoint()); final int dbRowIndex = currentTable.getRowIndex(rowIndex); final int columnIndex = currentTable.getTable().columnAtPoint( getEvent().getPoint()); BackgroundManager bm = Services.getService(BackgroundManager.class); bm.backgroundOperation(new BackgroundJob() { @Override public void run(ProgressMonitor pm) { try { DataSource dataSource = element.getDataSource(); ArrayList<Integer> newSel = new ArrayList<Integer>(); Value ref = dataSource.getFieldValue(dbRowIndex, columnIndex); for (int i = 0; i < dataSource.getRowCount(); i++) { Value value = dataSource.getFieldValue(i, columnIndex); if (!ref.isNull()) { if (value.equals(ref).getAsBoolean()) { newSel.add(i); } } else { if (value.isNull()) { newSel.add(i); } } } int[] sel = new int[newSel.size()]; for (int i = 0; i < sel.length; i++) { sel[i] = newSel.get(i); } element.getSelection().setSelectedRows(sel); } catch (DriverException e) { ErrorMessages.error(ErrorMessages.CannotReadSource, e); } } @Override public String getTaskName() { return I18N.getString("orbisgis.org.orbisgis.core.ui.plugins.editors.tableEditor.findMatch"); } }); return true; }
public boolean execute(PlugInContext context) throws Exception { IEditor editor = context.getActiveEditor(); final TableEditableElement element = (TableEditableElement) editor.getElement(); TableComponent currentTable = (TableComponent) editor.getView().getComponent(); final int rowIndex = currentTable.getTable().rowAtPoint( getEvent().getPoint()); final int dbRowIndex = currentTable.getRowIndex(rowIndex); final int columnIndex = currentTable.getTable().columnAtPoint( getEvent().getPoint()); BackgroundManager bm = Services.getService(BackgroundManager.class); bm.backgroundOperation(new BackgroundJob() { @Override public void run(ProgressMonitor pm) { try { DataSource dataSource = element.getDataSource(); ArrayList<Integer> newSel = new ArrayList<Integer>(); Value ref = dataSource.getFieldValue(dbRowIndex, columnIndex); for (int i = 0; i < dataSource.getRowCount(); i++) { Value value = dataSource.getFieldValue(i, columnIndex); Value comp = value.equals(ref); if (!comp.isNull()) { if (comp.getAsBoolean()) { newSel.add(i); } } } int[] sel = new int[newSel.size()]; for (int i = 0; i < sel.length; i++) { sel[i] = newSel.get(i); } element.getSelection().setSelectedRows(sel); } catch (DriverException e) { ErrorMessages.error(ErrorMessages.CannotReadSource, e); } } @Override public String getTaskName() { return I18N.getString("orbisgis.org.orbisgis.core.ui.plugins.editors.tableEditor.findMatch"); } }); return true; }
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { List<News> newsList = DAO.getList(News.class); List<Album> albumsList = DAO.getList(Album.class); List<Album> featuredAlbumsList = DAO.getList(Album.class); Long lol = DAO.countAlbumComments(0); for(Album fAlbum : featuredAlbumsList) { String coverPath = "images/albums/cover_" + fAlbum.getArtist().getName().replace(" ", "_").toLowerCase() + "_" + fAlbum.getName().replace(" ", "_").toLowerCase() + ".jpg"; fAlbum.setCover(coverPath); } request.setAttribute("lol", lol); request.setAttribute("news", newsList); request.setAttribute("albums", albumsList); request.setAttribute("featuredAlbums", featuredAlbumsList); request.setCharacterEncoding("UTF-8"); RequestDispatcher jsp = request.getRequestDispatcher("index.jsp"); jsp.forward(request, response); }
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { List<News> newsList = DAO.getList(News.class); List<Album> albumsList = DAO.getList(Album.class); List<Album> featuredAlbumsList = DAO.getList(Album.class); int lol = DAO.countAlbumComments(0); for(Album fAlbum : featuredAlbumsList) { String coverPath = "images/albums/cover_" + fAlbum.getArtist().getName().replace(" ", "_").toLowerCase() + "_" + fAlbum.getName().replace(" ", "_").toLowerCase() + ".jpg"; fAlbum.setCover(coverPath); } request.setAttribute("lol", lol); request.setAttribute("news", newsList); request.setAttribute("albums", albumsList); request.setAttribute("featuredAlbums", featuredAlbumsList); request.setCharacterEncoding("UTF-8"); RequestDispatcher jsp = request.getRequestDispatcher("index.jsp"); jsp.forward(request, response); }
public static void main(String[] args) throws Exception { ParallCAPMain pcapMain = new ParallCAPMain(); if (args.length != 4) { String errorReport = "ParallelCap: the Correct arguments are \n" + "java cgl.imr.samples.parallcap.parallelcapmain " + "<partition file> <num map tasks> <num reduce tasks> <numLoop>"; System.out.println(errorReport); System.exit(0); } String partitionFile = args[0]; int numMapTasks = Integer.parseInt(args[1]); int numReduceTasks = Integer.parseInt(args[2]); int numLoop = Integer.parseInt(args[3]); List<Value> grayNodes = null; double beginTime = System.currentTimeMillis(); try { grayNodes = ParallCAPMain.driveMapReduce(numMapTasks, numReduceTasks, partitionFile, numLoop); System.out.println("Current gray nodes: "); for (Value val : grayNodes) { System.out.println(((Node)val).getId()); } } catch (Exception e) { e.printStackTrace(); } double endTime = System.currentTimeMillis(); double timeInSeconds = ((double)(endTime - beginTime)) / 1000; System.out .println("------------------------------------------------------"); System.out.println("Parallel Cap took " + timeInSeconds + " seconds."); System.out .println("------------------------------------------------------"); }
public static void main(String[] args) throws Exception { ParallCAPMain pcapMain = new ParallCAPMain(); if (args.length != 4) { String errorReport = "ParallelCap: the Correct arguments are \n" + "java cgl.imr.samples.parallcap.parallelcapmain " + "<partition file> <num map tasks> <num reduce tasks> <numLoop>"; System.out.println(errorReport); System.exit(0); } String partitionFile = args[0]; int numMapTasks = Integer.parseInt(args[1]); int numReduceTasks = Integer.parseInt(args[2]); int numLoop = Integer.parseInt(args[3]); List<Value> grayNodes = null; double beginTime = System.currentTimeMillis(); try { grayNodes = ParallCAPMain.driveMapReduce(numMapTasks, numReduceTasks, partitionFile, numLoop); System.out.println("Current gray nodes: "); for (Value val : grayNodes) { NodeVectorValue tmpVec = (NodeVectorValue)val; for (Node node : tmpVec.getGrayNodeList()) { System.out.println(node.getId()); } } } catch (Exception e) { e.printStackTrace(); } double endTime = System.currentTimeMillis(); double timeInSeconds = ((double)(endTime - beginTime)) / 1000; System.out .println("------------------------------------------------------"); System.out.println("Parallel Cap took " + timeInSeconds + " seconds."); System.out .println("------------------------------------------------------"); }
public void handle(HttpExchange exchange) throws IOException { try (final InputStream is = exchange.getRequestBody(); final InputStreamReader sr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(sr);) { final String postBody = br.readLine(); if (postBody == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } final int idx = postBody.indexOf('=') + 1; if (idx == -1 || postBody.length() - idx < 3) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } final Uri uri = Uri.create(postBody.substring(idx), true); if (uri == null) { logger.warn("banned: " + uri + " - " + exchange.getRemoteAddress().getHostName()); reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } if (vfs.isBanned(uri)) { reply(exchange, vfs.get(VirtualFileSystem.Error.FORBIDDEN_PHISHING), false); return; } final byte[] hashedUri = vfs.add(uri); if (hashedUri == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } reply(exchange, new NormalResponse(hashedUri), false); } catch (IOException e) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } }
public void handle(HttpExchange exchange) throws IOException { try (final InputStream is = exchange.getRequestBody(); final InputStreamReader sr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(sr);) { final String postBody = br.readLine(); if (postBody == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } final int idx = postBody.indexOf('=') + 1; if (idx == -1 || postBody.length() - idx < 3) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } final Uri uri = Uri.create(postBody.substring(idx), true); if (uri == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } if (vfs.isBanned(uri)) { logger.warn("banned: " + uri + " - " + exchange.getRemoteAddress().getHostName()); reply(exchange, vfs.get(VirtualFileSystem.Error.FORBIDDEN_PHISHING), false); return; } final byte[] hashedUri = vfs.add(uri); if (hashedUri == null) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } reply(exchange, new NormalResponse(hashedUri), false); } catch (IOException e) { reply(exchange, vfs.get(VirtualFileSystem.Error.BAD_REQUEST), false); return; } }
public void close() throws IOException { inputStream.close(); LOG.info( "closing stream, testing digest: [" + digestHex == null ? "none" : digestHex + "]" ); if( digestHex == null ) return; String digestHex = new String( Hex.encodeHex( ( (DigestInputStream) inputStream ).getMessageDigest().digest() ) ); if( !digestHex.equals( this.digestHex ) ) { String message = "given digest: [" + this.digestHex + "], does not match input stream digest: [" + digestHex + "]"; LOG.error( message ); throw new IOException( message ); } }
public void close() throws IOException { inputStream.close(); LOG.info( "closing stream, testing digest: [" + ( digestHex == null ? "none" : digestHex ) + "]" ); if( digestHex == null ) return; String digestHex = new String( Hex.encodeHex( ( (DigestInputStream) inputStream ).getMessageDigest().digest() ) ); if( !digestHex.equals( this.digestHex ) ) { String message = "given digest: [" + this.digestHex + "], does not match input stream digest: [" + digestHex + "]"; LOG.error( message ); throw new IOException( message ); } }
public IdentifyPillarsForPutFileResponse createIdentifyPillarsForPutFileResponse( IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage, String pillarId, String pillarDestinationId) { IdentifyPillarsForPutFileResponse ipfpfResponse = new IdentifyPillarsForPutFileResponse(); ipfpfResponse.setTo(receivedIdentifyRequestMessage.getReplyTo()); ipfpfResponse.setCorrelationID(receivedIdentifyRequestMessage.getCorrelationID()); ipfpfResponse.setCollectionID(collectionId); ipfpfResponse.setPillarID(pillarId); ipfpfResponse.setReplyTo(pillarDestinationId); ipfpfResponse.setTimeToDeliver(TIME_TO_DELIVER_DEFAULT); ipfpfResponse.setMinVersion(VERSION_DEFAULT); ipfpfResponse.setVersion(VERSION_DEFAULT); ipfpfResponse.setPillarChecksumSpec(null); return ipfpfResponse; }
public IdentifyPillarsForPutFileResponse createIdentifyPillarsForPutFileResponse( IdentifyPillarsForPutFileRequest receivedIdentifyRequestMessage, String pillarId, String pillarDestinationId) { IdentifyPillarsForPutFileResponse ipfpfResponse = new IdentifyPillarsForPutFileResponse(); ipfpfResponse.setTo(receivedIdentifyRequestMessage.getReplyTo()); ipfpfResponse.setCorrelationID(receivedIdentifyRequestMessage.getCorrelationID()); ipfpfResponse.setCollectionID(collectionId); ipfpfResponse.setPillarID(pillarId); ipfpfResponse.setReplyTo(pillarDestinationId); ipfpfResponse.setTimeToDeliver(TIME_TO_DELIVER_DEFAULT); ipfpfResponse.setMinVersion(VERSION_DEFAULT); ipfpfResponse.setVersion(VERSION_DEFAULT); ipfpfResponse.setResponseInfo(IDENTIFY_INFO_DEFAULT); ipfpfResponse.setPillarChecksumSpec(null); return ipfpfResponse; }
private static Translator createWBModuleTranslator(EStructuralFeature afeature) { GenericTranslator result = new GenericTranslator(WORKBENCH_COMPONENT, afeature); result.setChildren(new Translator[] { IDTranslator.INSTANCE, new Translator(RUNTIME_NAME, MODULE_CORE_PKG.getWorkbenchComponent_Name(), DOM_ATTRIBUTE), createModuleTypeTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ComponentType()), createWBResourceTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Resources()), createDependentModuleTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ReferencedComponents()), new Translator(META_RESOURCES, MODULE_CORE_PKG.getWorkbenchComponent_MetadataResources()), createPropertiesTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Properties()) }); return result; }
private static Translator createWBModuleTranslator(EStructuralFeature afeature) { GenericTranslator result = new GenericTranslator(WORKBENCH_COMPONENT, afeature); result.setChildren(new Translator[] { IDTranslator.INSTANCE, new Translator(RUNTIME_NAME, MODULE_CORE_PKG.getWorkbenchComponent_Name(), DOM_ATTRIBUTE), createModuleTypeTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ComponentType()), createWBResourceTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Resources()), createDependentModuleTranslator(MODULE_CORE_PKG.getWorkbenchComponent_ReferencedComponents()), new IPathTranslator(META_RESOURCES, MODULE_CORE_PKG.getWorkbenchComponent_MetadataResources()), createPropertiesTranslator(MODULE_CORE_PKG.getWorkbenchComponent_Properties()) }); return result; }
public void testHMAC() { HMAC h1 = new HMAC(); assertNotNull(h1); try { Provider sp = new com.sun.crypto.provider.SunJCE(); Security.addProvider(sp); } catch (Exception e) { HMAC.message("Problem loading crypto provider", e); fail("Problem loading crypto provider" + e); } byte[] hmac = h1.computeMac(); assertNull("Currently HMAC is broken since you can't actually " + "set the keyData or data elements. This test will break once someone fixes that", hmac); }
public void testHMAC() { HMAC h1 = new HMAC(); assertNotNull(h1); try { Provider sp = new com.sun.crypto.provider.SunJCE(); Security.addProvider(sp); } catch (Exception e) { fail("Problem loading crypto provider" + e); } byte[] hmac = h1.computeMac(); assertNull("Currently HMAC is broken since you can't actually " + "set the keyData or data elements. This test will break once someone fixes that", hmac); }
private void flush(){ if(unsortedCount == 0) return; Arrays.sort(unsorted); ListIterator<Interval> it = intervals.listIterator(); int i = 0; while(i < unsorted.length){ int start = i; while((i < unsorted.length - 1) && (unsorted[i + 1] == unsorted[i] + 1)) i++; Interval interval = new Interval(start, i); while(it.hasNext()){ if(it.next().start > interval.end){ it.previous(); break; } } it.add(interval); i++; } normalize(); unsortedCount = 0; }
private void flush(){ if(unsortedCount == 0) return; Arrays.sort(unsorted); ListIterator<Interval> it = intervals.listIterator(); int i = 0; while(i < unsortedCount){ int start = i; while((i < unsortedCount - 1) && (unsorted[i + 1] == unsorted[i] + 1)) i++; Interval interval = new Interval(start, i); while(it.hasNext()){ if(it.next().start > interval.end){ it.previous(); break; } } it.add(interval); i++; } normalize(); unsortedCount = 0; }
public String primGetNextToken() throws java.io.IOException { int yy_input; int yy_action; while (true) { yychar += yylength(); boolean yy_counted = false; for (yy_currentPos = yy_startRead; yy_currentPos < yy_markedPos; yy_currentPos++) { switch (yy_buffer[yy_currentPos]) { case '\r': yyline++; yy_counted = true; break; case '\n': if (yy_counted) yy_counted = false; else { yyline++; } break; default: yy_counted = false; } } if (yy_counted) { if (yy_advance() == '\n') yyline--; if (!yy_atEOF) yy_currentPos--; } yy_action = -1; yy_currentPos = yy_startRead = yy_markedPos; yy_state = yy_lexical_state; yy_forAction: { while (true) { yy_input = yy_advance(); if (yy_input == YYEOF) break yy_forAction; int yy_next = yytrans[yy_rowMap[yy_state] + yycmap[yy_input]]; if (yy_next == -1) break yy_forAction; yy_state = yy_next; int yy_attributes = YY_ATTRIBUTE[yy_state]; if ((yy_attributes & 1) > 0) { yy_action = yy_state; yy_markedPos = yy_currentPos; if ((yy_attributes & 8) > 0) break yy_forAction; } } } switch (yy_action) { case 279: case 280: case 281: case 282: { if (Debug.debugTokenizer) dump("\nCDATA start"); fStateStack.push(yystate()); yybegin(ST_CDATA_TEXT); return XML_CDATA_OPEN; } case 284: break; case 271: { if (Debug.debugTokenizer) dump("element"); yybegin(ST_XML_ELEMENT_DECLARATION); return XML_ELEMENT_DECLARATION; } case 285: break; case 270: { if (Debug.debugTokenizer) dump("attlist"); yybegin(ST_XML_ATTLIST_DECLARATION); return XML_ATTLIST_DECLARATION; } case 286: break; case 269: { if (Debug.debugTokenizer) dump("doctype"); yybegin(ST_XML_DOCTYPE_DECLARATION); return XML_DOCTYPE_DECLARATION; } case 287: break; case 264: { if (Debug.debugTokenizer) dump("doctype external id"); yybegin(ST_XML_DOCTYPE_ID_PUBLIC); return XML_DOCTYPE_EXTERNAL_ID_PUBLIC; } case 288: break; case 263: { if (Debug.debugTokenizer) dump("doctype external id"); yybegin(ST_XML_DOCTYPE_ID_SYSTEM); return XML_DOCTYPE_EXTERNAL_ID_SYSTEM; } case 289: break; case 233: { if (Debug.debugTokenizer) dump("\nCharRef"); return XML_CHAR_REFERENCE; } case 290: break; case 229: { if (Debug.debugTokenizer) dump("\ncomment start"); fEmbeddedHint = XML_COMMENT_TEXT; fEmbeddedPostState = ST_XML_COMMENT; yybegin(ST_XML_COMMENT); return XML_COMMENT_OPEN; } case 291: break; case 210: { if (Debug.debugTokenizer) dump("comment end"); fEmbeddedHint = UNDEFINED; yybegin(YYINITIAL); return XML_COMMENT_CLOSE; } case 292: break; case 209: { if (Debug.debugTokenizer) dump("CDATA end"); yybegin(fStateStack.pop()); return XML_CDATA_CLOSE; } case 293: break; case 208: { if (Debug.debugTokenizer) dump("\nPEReference"); return XML_PE_REFERENCE; } case 294: break; case 205: { if (Debug.debugTokenizer) dump("\nEntityRef"); return XML_ENTITY_REFERENCE; } case 295: break; case 196: case 198: case 258: { return SMARTY_VARIABLE; } case 296: break; case 195: { return SMARTY_COMMENT; } case 297: break; case 192: { return SMARTY_CONSTANT_ENCAPSED_STRING; } case 298: break; case 189: { int incomingState = yystate(); fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_TAG_NAME); assembleEmbeddedContainer(XML_END_TAG_OPEN, new String[] { XML_TAG_CLOSE, XML_EMPTY_TAG_CLOSE }); if (yystate() != ST_ABORT_EMBEDDED) yybegin(incomingState); return PROXY_CONTEXT; } case 299: break; case 187: { yybegin(fStateStack.pop()); return PHP_CLOSE; } case 300: break; case 142: case 156: case 164: { return XML_DOCTYPE_INTERNAL_SUBSET; } case 301: break; case 133: { String tagName = yytext().substring(1); yypushback(yylength() - 1); if (!isNestable(tagName) || (!fStateStack.empty() && (fStateStack.peek() == ST_XML_ATTRIBUTE_NAME || fStateStack.peek() == ST_XML_EQUALS || fStateStack.peek() == ST_XML_ATTRIBUTE_VALUE))) { yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } if (Debug.debugTokenizer) dump("tag in place of attr value"); fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; fStateStack.push(yystate()); yybegin(ST_XML_TAG_NAME); assembleEmbeddedTagSequence(XML_TAG_OPEN, tagName); fStateStack.pop(); yybegin(ST_XML_ATTRIBUTE_NAME); return PROXY_CONTEXT; } case 302: break; case 131: { String tagName = yytext().substring(1); yypushback(yylength() - 1); if (!isNestable(tagName) || (!fStateStack.empty() && (fStateStack.peek() == ST_XML_ATTRIBUTE_NAME || fStateStack.peek() == ST_XML_EQUALS || fStateStack.peek() == ST_XML_ATTRIBUTE_VALUE))) { yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } if (Debug.debugTokenizer) dump("tag in place of attr name"); fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; fStateStack.push(yystate()); yybegin(ST_XML_TAG_NAME); assembleEmbeddedTagSequence(XML_TAG_OPEN, tagName); fStateStack.pop(); yybegin(ST_XML_EQUALS); return PROXY_CONTEXT; } case 303: break; case 130: { yybegin(YYINITIAL); fEmbeddedHint = UNDEFINED; return XML_EMPTY_TAG_CLOSE; } case 304: break; case 121: { fStateStack.push(yystate()); if (Debug.debugTokenizer) dump("\ndeclaration start"); yybegin(ST_XML_DECLARATION); return XML_DECLARATION_OPEN; } case 305: break; case 120: case 122: case 201: { if (UseAspTagsHandler.useAspTagsAsPhp(project) || yytext().charAt(1) != '%') { String phpStart = yytext(); int i = phpStart.length() - 1; while (i >= 0 && Character.isWhitespace(phpStart.charAt(i--))) { yypushback(1); } fStateStack.push(yystate()); if (fStateStack.peek() == YYINITIAL) { yybegin(ST_PHP_CONTENT); return PHP_OPEN; } else { if (yystate() == ST_XML_ATTRIBUTE_VALUE_DQUOTED) fEmbeddedPostState = ST_XML_ATTRIBUTE_VALUE_DQUOTED; else if (yystate() == ST_XML_ATTRIBUTE_VALUE_SQUOTED) fEmbeddedPostState = ST_XML_ATTRIBUTE_VALUE_SQUOTED; else if (yystate() == ST_CDATA_TEXT) { fEmbeddedPostState = ST_CDATA_TEXT; fEmbeddedHint = XML_CDATA_TEXT; } yybegin(ST_PHP_CONTENT); assembleEmbeddedContainer(PHP_OPEN, PHP_CLOSE); if (yystate() == ST_BLOCK_TAG_INTERNAL_SCAN) { yybegin(ST_BLOCK_TAG_SCAN); return BLOCK_TEXT; } if (yystate() == ST_XML_TAG_NAME) { fEmbeddedHint = XML_TAG_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; } else if ((yystate() == ST_XML_ATTRIBUTE_NAME || yystate() == ST_XML_EQUALS)) { fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; } else if (yystate() == ST_XML_ATTRIBUTE_VALUE) { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; } return PROXY_CONTEXT; } } yypushback(1); yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } case 306: break; case 119: { fEmbeddedHint = XML_TAG_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_TAG_NAME); return XML_END_TAG_OPEN; } case 307: break; case 118: { yybegin(ST_SMARTY_DOUBLE_QUOTES); return SMARTY_BACKTICK_END; } case 308: break; case 116: { yybegin(ST_SMARTY_DOUBLE_QUOTES_SPECIAL); return SMARTY_BACKTICK_START; } case 309: break; case 114: { yybegin(ST_SMARTY_CONTENT); return SMARTY_DOUBLE_QUOTES_END; } case 310: break; case 112: case 113: case 197: case 227: case 245: case 257: case 267: case 274: case 278: { return SMARTY_DOUBLE_QUOTES_CONTENT; } case 311: break; case 110: { yybegin(YYINITIAL); return SMARTY_CLOSE; } case 312: break; case 108: { return SMARTY_NUMBER; } case 313: break; case 106: { yybegin(ST_SMARTY_DOUBLE_QUOTES); return SMARTY_DOUBLE_QUOTES_START; } case 314: break; case 54: { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_VALUE_SQUOTED; yybegin(ST_XML_ATTRIBUTE_VALUE_SQUOTED); fStateStack.push(yystate()); assembleEmbeddedContainer(XML_TAG_ATTRIBUTE_VALUE_SQUOTE, XML_TAG_ATTRIBUTE_VALUE_SQUOTE); fStateStack.pop(); fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; yybegin(ST_XML_ATTRIBUTE_NAME); return PROXY_CONTEXT; } case 315: break; case 53: { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_VALUE_DQUOTED; yybegin(ST_XML_ATTRIBUTE_VALUE_DQUOTED); fStateStack.push(yystate()); assembleEmbeddedContainer(XML_TAG_ATTRIBUTE_VALUE_DQUOTE, XML_TAG_ATTRIBUTE_VALUE_DQUOTE); fStateStack.pop(); fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; yybegin(ST_XML_ATTRIBUTE_NAME); return PROXY_CONTEXT; } case 316: break; case 50: case 135: { fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; yybegin(ST_XML_ATTRIBUTE_NAME); return XML_TAG_ATTRIBUTE_VALUE; } case 317: break; case 49: { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_ATTRIBUTE_VALUE); return XML_TAG_ATTRIBUTE_EQUALS; } case 318: break; case 48: { fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_EQUALS); return XML_TAG_ATTRIBUTE_NAME; } case 319: break; case 44: case 45: { if (Debug.debugTokenizer) dump("tag name"); fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; yybegin(ST_XML_ATTRIBUTE_NAME); return XML_TAG_NAME; } case 320: break; case 42: { fEmbeddedHint = UNDEFINED; if (isBlockMarker()) { fEmbeddedHint = getBlockMarkerContext(); fEmbeddedPostState = ST_BLOCK_TAG_SCAN; yybegin(ST_BLOCK_TAG_SCAN); } else yybegin(YYINITIAL); return XML_TAG_CLOSE; } case 321: break; case 38: case 39: { if (Debug.debugTokenizer) dump("comment content"); return scanXMLCommentText(); } case 322: break; case 37: { if (Debug.debugTokenizer) dump("LINE FEED"); return WHITE_SPACE; } case 323: break; case 0: case 28: case 124: case 126: case 203: case 204: case 232: { if (Debug.debugTokenizer) dump("\nXML content"); final String text = yytext(); assert text != null; final char startChar = text.charAt(0); if (startChar == '{') { yybegin(ST_SMARTY_CONTENT); yypushback(yylength() - 1); return SMARTY_OPEN; } return XML_CONTENT; } case 324: break; case 5: case 41: { if (!fStateStack.empty() && (fStateStack.peek() == ST_XML_ATTRIBUTE_VALUE_SQUOTED || fStateStack.peek() == ST_XML_ATTRIBUTE_VALUE_DQUOTED)) { yybegin(ST_ABORT_EMBEDDED); yypushback(yylength() - 1); return XML_TAG_ATTRIBUTE_VALUE; } yybegin(YYINITIAL); return XML_CONTENT; } case 325: break; case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 17: case 47: { if (Debug.debugTokenizer) dump("white space"); return WHITE_SPACE; } case 326: break; case 16: case 79: case 80: case 175: case 222: case 242: case 255: case 265: case 272: case 276: { if (Debug.debugTokenizer) dump("elementdecl contentspec"); return XML_ELEMENT_DECL_CONTENT; } case 327: break; case 18: case 86: case 87: case 186: case 226: case 244: case 256: case 266: case 273: case 277: { if (Debug.debugTokenizer) dump("attlist contentspec"); return XML_ATTLIST_DECL_CONTENT; } case 328: break; case 29: case 46: case 51: case 55: { if (Debug.debugTokenizer) dump("\nstart tag open"); fEmbeddedHint = XML_TAG_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } case 329: break; case 30: case 31: case 34: case 35: case 36: case 40: case 43: case 52: case 57: case 58: case 59: case 60: case 61: case 63: case 64: case 66: case 71: case 76: case 83: case 97: case 100: case 115: case 117: { if (Debug.debugTokenizer) System.out.println("!!!unexpected!!!: \"" + yytext() + "\":" + yychar + "-" + (yychar + yylength())); return UNDEFINED; } case 330: break; case 32: case 33: { if (Debug.debugTokenizer) dump("CDATA text"); String blockContext = doBlockScan("]]>", XML_CDATA_TEXT, ST_CDATA_END); if (blockContext == XML_CDATA_TEXT) yybegin(ST_CDATA_END); return blockContext; } case 331: break; case 56: { if (Debug.debugTokenizer) dump("declaration end"); if (Debug.debugTokenizer) { if (fStateStack.peek() != YYINITIAL) System.out.println("end embedded region"); } yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } case 332: break; case 62: { if (Debug.debugTokenizer) dump("doctype type"); yybegin(ST_XML_DOCTYPE_EXTERNAL_ID); return XML_DOCTYPE_NAME; } case 333: break; case 65: case 67: case 68: case 69: case 148: case 149: case 152: case 153: case 217: { if (Debug.debugTokenizer) dump("doctype public reference"); yybegin(ST_XML_DOCTYPE_ID_SYSTEM); return XML_DOCTYPE_EXTERNAL_ID_PUBREF; } case 334: break; case 70: case 72: case 73: case 74: case 160: { if (Debug.debugTokenizer) dump("doctype system reference"); yybegin(ST_XML_DECLARATION_CLOSE); return XML_DOCTYPE_EXTERNAL_ID_SYSREF; } case 335: break; case 75: case 77: case 78: case 168: case 169: case 172: case 173: case 220: { if (Debug.debugTokenizer) dump("elementdecl name"); yybegin(ST_XML_ELEMENT_DECLARATION_CONTENT); return XML_ELEMENT_DECL_NAME; } case 336: break; case 81: { if (Debug.debugTokenizer) dump("elementdecl close"); if (Debug.debugTokenizer) { if (fStateStack.peek() != YYINITIAL) System.out.println("end embedded region"); } yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } case 337: break; case 82: case 84: case 85: case 179: case 180: case 183: case 184: case 224: { if (Debug.debugTokenizer) dump("attlist name"); yybegin(ST_XML_ATTLIST_DECLARATION_CONTENT); return XML_ATTLIST_DECL_NAME; } case 338: break; case 88: { if (Debug.debugTokenizer) dump("attlist close"); if (Debug.debugTokenizer) { if (fStateStack.peek() != YYINITIAL) System.out.println("end embedded region"); } yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } case 339: break; case 91: case 92: case 93: { return doScanEndPhp(UseAspTagsHandler.useAspTagsAsPhp(project), PHP_CONTENT, ST_PHP_CONTENT, ST_PHP_CONTENT); } case 340: break; case 94: case 98: { return XML_TAG_ATTRIBUTE_VALUE; } case 341: break; case 95: { int incomingState = yystate(); fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_TAG_NAME); assembleEmbeddedContainer(XML_TAG_OPEN, new String[] { XML_TAG_CLOSE, XML_EMPTY_TAG_CLOSE }); if (yystate() != ST_ABORT_EMBEDDED) yybegin(incomingState); return PROXY_CONTEXT; } case 342: break; case 96: { return XML_TAG_ATTRIBUTE_VALUE_SQUOTE; } case 343: break; case 99: { return XML_TAG_ATTRIBUTE_VALUE_DQUOTE; } case 344: break; case 101: case 107: { return doScan("}", false, false, SMARTY_CONTENT, ST_SMARTY_CONTENT, ST_SMARTY_CONTENT); } case 345: break; case 102: case 103: case 109: case 111: { return SMARTY_DELIMITER; } case 346: break; case 104: { return SMARTY_WHITESPACE; } case 347: break; case 105: { return SMARTY_LABEL; } case 348: break; case 89: case 90: { return doBlockTagScan(); } case 349: break; default: if (yy_input == YYEOF && yy_startRead == yy_currentPos) { yy_atEOF = true; yy_do_eof(); return null; } else { yy_ScanError(YY_NO_MATCH); } } } }
public String primGetNextToken() throws java.io.IOException { int yy_input; int yy_action; while (true) { yychar += yylength(); boolean yy_counted = false; for (yy_currentPos = yy_startRead; yy_currentPos < yy_markedPos; yy_currentPos++) { switch (yy_buffer[yy_currentPos]) { case '\r': yyline++; yy_counted = true; break; case '\n': if (yy_counted) yy_counted = false; else { yyline++; } break; default: yy_counted = false; } } if (yy_counted) { if (yy_advance() == '\n') yyline--; if (!yy_atEOF) yy_currentPos--; } yy_action = -1; yy_currentPos = yy_startRead = yy_markedPos; yy_state = yy_lexical_state; yy_forAction: { while (true) { yy_input = yy_advance(); if (yy_input == YYEOF) break yy_forAction; int yy_next = yytrans[yy_rowMap[yy_state] + yycmap[yy_input]]; if (yy_next == -1) break yy_forAction; yy_state = yy_next; int yy_attributes = YY_ATTRIBUTE[yy_state]; if ((yy_attributes & 1) > 0) { yy_action = yy_state; yy_markedPos = yy_currentPos; if ((yy_attributes & 8) > 0) break yy_forAction; } } } switch (yy_action) { case 279: case 280: case 281: case 282: { if (Debug.debugTokenizer) dump("\nCDATA start"); fStateStack.push(yystate()); yybegin(ST_CDATA_TEXT); return XML_CDATA_OPEN; } case 284: break; case 271: { if (Debug.debugTokenizer) dump("element"); yybegin(ST_XML_ELEMENT_DECLARATION); return XML_ELEMENT_DECLARATION; } case 285: break; case 270: { if (Debug.debugTokenizer) dump("attlist"); yybegin(ST_XML_ATTLIST_DECLARATION); return XML_ATTLIST_DECLARATION; } case 286: break; case 269: { if (Debug.debugTokenizer) dump("doctype"); yybegin(ST_XML_DOCTYPE_DECLARATION); return XML_DOCTYPE_DECLARATION; } case 287: break; case 264: { if (Debug.debugTokenizer) dump("doctype external id"); yybegin(ST_XML_DOCTYPE_ID_PUBLIC); return XML_DOCTYPE_EXTERNAL_ID_PUBLIC; } case 288: break; case 263: { if (Debug.debugTokenizer) dump("doctype external id"); yybegin(ST_XML_DOCTYPE_ID_SYSTEM); return XML_DOCTYPE_EXTERNAL_ID_SYSTEM; } case 289: break; case 233: { if (Debug.debugTokenizer) dump("\nCharRef"); return XML_CHAR_REFERENCE; } case 290: break; case 229: { if (Debug.debugTokenizer) dump("\ncomment start"); fEmbeddedHint = XML_COMMENT_TEXT; fEmbeddedPostState = ST_XML_COMMENT; yybegin(ST_XML_COMMENT); return XML_COMMENT_OPEN; } case 291: break; case 210: { if (Debug.debugTokenizer) dump("comment end"); fEmbeddedHint = UNDEFINED; yybegin(YYINITIAL); return XML_COMMENT_CLOSE; } case 292: break; case 209: { if (Debug.debugTokenizer) dump("CDATA end"); yybegin(fStateStack.pop()); return XML_CDATA_CLOSE; } case 293: break; case 208: { if (Debug.debugTokenizer) dump("\nPEReference"); return XML_PE_REFERENCE; } case 294: break; case 205: { if (Debug.debugTokenizer) dump("\nEntityRef"); return XML_ENTITY_REFERENCE; } case 295: break; case 196: case 198: case 258: { return SMARTY_VARIABLE; } case 296: break; case 195: { return SMARTY_COMMENT; } case 297: break; case 192: { return SMARTY_CONSTANT_ENCAPSED_STRING; } case 298: break; case 189: { int incomingState = yystate(); fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_TAG_NAME); assembleEmbeddedContainer(XML_END_TAG_OPEN, new String[] { XML_TAG_CLOSE, XML_EMPTY_TAG_CLOSE }); if (yystate() != ST_ABORT_EMBEDDED) yybegin(incomingState); return PROXY_CONTEXT; } case 299: break; case 187: { yybegin(fStateStack.pop()); return PHP_CLOSE; } case 300: break; case 142: case 156: case 164: { return XML_DOCTYPE_INTERNAL_SUBSET; } case 301: break; case 133: { String tagName = yytext().substring(1); yypushback(yylength() - 1); if (!isNestable(tagName) || (!fStateStack.empty() && (fStateStack.peek() == ST_XML_ATTRIBUTE_NAME || fStateStack.peek() == ST_XML_EQUALS || fStateStack.peek() == ST_XML_ATTRIBUTE_VALUE))) { yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } if (Debug.debugTokenizer) dump("tag in place of attr value"); fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; fStateStack.push(yystate()); yybegin(ST_XML_TAG_NAME); assembleEmbeddedTagSequence(XML_TAG_OPEN, tagName); fStateStack.pop(); yybegin(ST_XML_ATTRIBUTE_NAME); return PROXY_CONTEXT; } case 302: break; case 131: { String tagName = yytext().substring(1); yypushback(yylength() - 1); if (!isNestable(tagName) || (!fStateStack.empty() && (fStateStack.peek() == ST_XML_ATTRIBUTE_NAME || fStateStack.peek() == ST_XML_EQUALS || fStateStack.peek() == ST_XML_ATTRIBUTE_VALUE))) { yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } if (Debug.debugTokenizer) dump("tag in place of attr name"); fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; fStateStack.push(yystate()); yybegin(ST_XML_TAG_NAME); assembleEmbeddedTagSequence(XML_TAG_OPEN, tagName); fStateStack.pop(); yybegin(ST_XML_EQUALS); return PROXY_CONTEXT; } case 303: break; case 130: { yybegin(YYINITIAL); fEmbeddedHint = UNDEFINED; return XML_EMPTY_TAG_CLOSE; } case 304: break; case 121: { fStateStack.push(yystate()); if (Debug.debugTokenizer) dump("\ndeclaration start"); yybegin(ST_XML_DECLARATION); return XML_DECLARATION_OPEN; } case 305: break; case 120: case 122: case 201: { if (UseAspTagsHandler.useAspTagsAsPhp(project) || yytext().charAt(1) != '%') { String phpStart = yytext(); int i = phpStart.length() - 1; while (i >= 0 && Character.isWhitespace(phpStart.charAt(i--))) { yypushback(1); } fStateStack.push(yystate()); if (fStateStack.peek() == YYINITIAL) { yybegin(ST_PHP_CONTENT); return PHP_OPEN; } else { if (yystate() == ST_XML_ATTRIBUTE_VALUE_DQUOTED) fEmbeddedPostState = ST_XML_ATTRIBUTE_VALUE_DQUOTED; else if (yystate() == ST_XML_ATTRIBUTE_VALUE_SQUOTED) fEmbeddedPostState = ST_XML_ATTRIBUTE_VALUE_SQUOTED; else if (yystate() == ST_CDATA_TEXT) { fEmbeddedPostState = ST_CDATA_TEXT; fEmbeddedHint = XML_CDATA_TEXT; } yybegin(ST_PHP_CONTENT); assembleEmbeddedContainer(PHP_OPEN, PHP_CLOSE); if (yystate() == ST_BLOCK_TAG_INTERNAL_SCAN) { yybegin(ST_BLOCK_TAG_SCAN); return BLOCK_TEXT; } if (yystate() == ST_XML_TAG_NAME) { fEmbeddedHint = XML_TAG_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; } else if ((yystate() == ST_XML_ATTRIBUTE_NAME || yystate() == ST_XML_EQUALS)) { fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; } else if (yystate() == ST_XML_ATTRIBUTE_VALUE) { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; } return PROXY_CONTEXT; } } yypushback(1); yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } case 306: break; case 119: { fEmbeddedHint = XML_TAG_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_TAG_NAME); return XML_END_TAG_OPEN; } case 307: break; case 118: { yybegin(ST_SMARTY_DOUBLE_QUOTES); return SMARTY_BACKTICK_END; } case 308: break; case 116: { yybegin(ST_SMARTY_DOUBLE_QUOTES_SPECIAL); return SMARTY_BACKTICK_START; } case 309: break; case 114: { yybegin(ST_SMARTY_CONTENT); return SMARTY_DOUBLE_QUOTES_END; } case 310: break; case 112: case 113: case 197: case 227: case 245: case 257: case 267: case 274: case 278: { return SMARTY_DOUBLE_QUOTES_CONTENT; } case 311: break; case 110: { yybegin(YYINITIAL); return SMARTY_CLOSE; } case 312: break; case 108: { return SMARTY_NUMBER; } case 313: break; case 106: { yybegin(ST_SMARTY_DOUBLE_QUOTES); return SMARTY_DOUBLE_QUOTES_START; } case 314: break; case 54: { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_VALUE_SQUOTED; yybegin(ST_XML_ATTRIBUTE_VALUE_SQUOTED); fStateStack.push(yystate()); assembleEmbeddedContainer(XML_TAG_ATTRIBUTE_VALUE_SQUOTE, XML_TAG_ATTRIBUTE_VALUE_SQUOTE); fStateStack.pop(); fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; yybegin(ST_XML_ATTRIBUTE_NAME); return PROXY_CONTEXT; } case 315: break; case 53: { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_VALUE_DQUOTED; yybegin(ST_XML_ATTRIBUTE_VALUE_DQUOTED); fStateStack.push(yystate()); assembleEmbeddedContainer(XML_TAG_ATTRIBUTE_VALUE_DQUOTE, XML_TAG_ATTRIBUTE_VALUE_DQUOTE); fStateStack.pop(); fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; yybegin(ST_XML_ATTRIBUTE_NAME); return PROXY_CONTEXT; } case 316: break; case 50: case 135: { fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; yybegin(ST_XML_ATTRIBUTE_NAME); return XML_TAG_ATTRIBUTE_VALUE; } case 317: break; case 49: { fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_ATTRIBUTE_VALUE); return XML_TAG_ATTRIBUTE_EQUALS; } case 318: break; case 48: { fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_EQUALS); return XML_TAG_ATTRIBUTE_NAME; } case 319: break; case 44: case 45: { if (Debug.debugTokenizer) dump("tag name"); fEmbeddedHint = XML_TAG_ATTRIBUTE_NAME; fEmbeddedPostState = ST_XML_EQUALS; yybegin(ST_XML_ATTRIBUTE_NAME); return XML_TAG_NAME; } case 320: break; case 42: { fEmbeddedHint = UNDEFINED; if (isBlockMarker()) { fEmbeddedHint = getBlockMarkerContext(); fEmbeddedPostState = ST_BLOCK_TAG_SCAN; yybegin(ST_BLOCK_TAG_SCAN); } else yybegin(YYINITIAL); return XML_TAG_CLOSE; } case 321: break; case 38: case 39: { if (Debug.debugTokenizer) dump("comment content"); return scanXMLCommentText(); } case 322: break; case 37: { if (Debug.debugTokenizer) dump("LINE FEED"); return WHITE_SPACE; } case 323: break; case 0: case 28: case 124: case 126: case 203: case 204: case 232: { if (Debug.debugTokenizer) dump("\nXML content"); final String text = yytext(); assert text != null; final int startChar = text.indexOf('{'); if (startChar != -1) { yybegin(ST_SMARTY_CONTENT); yypushback(yylength() - startChar - 1); return SMARTY_OPEN; } return XML_CONTENT; } case 324: break; case 5: case 41: { if (!fStateStack.empty() && (fStateStack.peek() == ST_XML_ATTRIBUTE_VALUE_SQUOTED || fStateStack.peek() == ST_XML_ATTRIBUTE_VALUE_DQUOTED)) { yybegin(ST_ABORT_EMBEDDED); yypushback(yylength() - 1); return XML_TAG_ATTRIBUTE_VALUE; } yybegin(YYINITIAL); return XML_CONTENT; } case 325: break; case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 17: case 47: { if (Debug.debugTokenizer) dump("white space"); return WHITE_SPACE; } case 326: break; case 16: case 79: case 80: case 175: case 222: case 242: case 255: case 265: case 272: case 276: { if (Debug.debugTokenizer) dump("elementdecl contentspec"); return XML_ELEMENT_DECL_CONTENT; } case 327: break; case 18: case 86: case 87: case 186: case 226: case 244: case 256: case 266: case 273: case 277: { if (Debug.debugTokenizer) dump("attlist contentspec"); return XML_ATTLIST_DECL_CONTENT; } case 328: break; case 29: case 46: case 51: case 55: { if (Debug.debugTokenizer) dump("\nstart tag open"); fEmbeddedHint = XML_TAG_NAME; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_TAG_NAME); return XML_TAG_OPEN; } case 329: break; case 30: case 31: case 34: case 35: case 36: case 40: case 43: case 52: case 57: case 58: case 59: case 60: case 61: case 63: case 64: case 66: case 71: case 76: case 83: case 97: case 100: case 115: case 117: { if (Debug.debugTokenizer) System.out.println("!!!unexpected!!!: \"" + yytext() + "\":" + yychar + "-" + (yychar + yylength())); return UNDEFINED; } case 330: break; case 32: case 33: { if (Debug.debugTokenizer) dump("CDATA text"); String blockContext = doBlockScan("]]>", XML_CDATA_TEXT, ST_CDATA_END); if (blockContext == XML_CDATA_TEXT) yybegin(ST_CDATA_END); return blockContext; } case 331: break; case 56: { if (Debug.debugTokenizer) dump("declaration end"); if (Debug.debugTokenizer) { if (fStateStack.peek() != YYINITIAL) System.out.println("end embedded region"); } yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } case 332: break; case 62: { if (Debug.debugTokenizer) dump("doctype type"); yybegin(ST_XML_DOCTYPE_EXTERNAL_ID); return XML_DOCTYPE_NAME; } case 333: break; case 65: case 67: case 68: case 69: case 148: case 149: case 152: case 153: case 217: { if (Debug.debugTokenizer) dump("doctype public reference"); yybegin(ST_XML_DOCTYPE_ID_SYSTEM); return XML_DOCTYPE_EXTERNAL_ID_PUBREF; } case 334: break; case 70: case 72: case 73: case 74: case 160: { if (Debug.debugTokenizer) dump("doctype system reference"); yybegin(ST_XML_DECLARATION_CLOSE); return XML_DOCTYPE_EXTERNAL_ID_SYSREF; } case 335: break; case 75: case 77: case 78: case 168: case 169: case 172: case 173: case 220: { if (Debug.debugTokenizer) dump("elementdecl name"); yybegin(ST_XML_ELEMENT_DECLARATION_CONTENT); return XML_ELEMENT_DECL_NAME; } case 336: break; case 81: { if (Debug.debugTokenizer) dump("elementdecl close"); if (Debug.debugTokenizer) { if (fStateStack.peek() != YYINITIAL) System.out.println("end embedded region"); } yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } case 337: break; case 82: case 84: case 85: case 179: case 180: case 183: case 184: case 224: { if (Debug.debugTokenizer) dump("attlist name"); yybegin(ST_XML_ATTLIST_DECLARATION_CONTENT); return XML_ATTLIST_DECL_NAME; } case 338: break; case 88: { if (Debug.debugTokenizer) dump("attlist close"); if (Debug.debugTokenizer) { if (fStateStack.peek() != YYINITIAL) System.out.println("end embedded region"); } yybegin(fStateStack.pop()); return XML_DECLARATION_CLOSE; } case 339: break; case 91: case 92: case 93: { return doScanEndPhp(UseAspTagsHandler.useAspTagsAsPhp(project), PHP_CONTENT, ST_PHP_CONTENT, ST_PHP_CONTENT); } case 340: break; case 94: case 98: { return XML_TAG_ATTRIBUTE_VALUE; } case 341: break; case 95: { int incomingState = yystate(); fEmbeddedHint = XML_TAG_ATTRIBUTE_VALUE; fEmbeddedPostState = ST_XML_ATTRIBUTE_NAME; yybegin(ST_XML_TAG_NAME); assembleEmbeddedContainer(XML_TAG_OPEN, new String[] { XML_TAG_CLOSE, XML_EMPTY_TAG_CLOSE }); if (yystate() != ST_ABORT_EMBEDDED) yybegin(incomingState); return PROXY_CONTEXT; } case 342: break; case 96: { return XML_TAG_ATTRIBUTE_VALUE_SQUOTE; } case 343: break; case 99: { return XML_TAG_ATTRIBUTE_VALUE_DQUOTE; } case 344: break; case 101: case 107: { return doScan("}", false, false, SMARTY_CONTENT, ST_SMARTY_CONTENT, ST_SMARTY_CONTENT); } case 345: break; case 102: case 103: case 109: case 111: { return SMARTY_DELIMITER; } case 346: break; case 104: { return SMARTY_WHITESPACE; } case 347: break; case 105: { return SMARTY_LABEL; } case 348: break; case 89: case 90: { return doBlockTagScan(); } case 349: break; default: if (yy_input == YYEOF && yy_startRead == yy_currentPos) { yy_atEOF = true; yy_do_eof(); return null; } else { yy_ScanError(YY_NO_MATCH); } } } }
private void processFiles (Stencil stencil, String[] licenseArray, long licenseModTime, char[] buffer, String directoryPath, FileFilter... fileFilters) throws MojoExecutionException { File tempFile; BufferedReader fileReader; FileWriter fileWriter; LicenseState licenseState; Pattern skipPattern = null; String singleLine = null; int charsRead; if (stencil.getSkipLines() != null) { skipPattern = Pattern.compile(stencil.getSkipLines()); } for (File licensedFile : new LicensedFileIterator(new File(directoryPath), fileFilters)) { try { fileWriter = new FileWriter(tempFile = new File(licensedFile.getParent() + System.getProperty("file.separator") + "license.temp")); try { fileReader = new BufferedReader(new FileReader(licensedFile)); licenseState = (stencil.getFirstLine() != null) ? LicenseState.FIRST : LicenseState.LAST; while ((!(licenseState.equals(LicenseState.COMPLETED) || licenseState.equals(LicenseState.TERMINATED))) && ((singleLine = fileReader.readLine()) != null)) { if ((skipPattern == null) || (!skipPattern.matcher(singleLine).matches())) { switch (licenseState) { case FIRST: if (singleLine.length() > 0) { licenseState = singleLine.equals(stencil.getFirstLine()) ? LicenseState.LAST : LicenseState.TERMINATED; } break; case LAST: if ((stencil.getLastLine() != null) && singleLine.equals(stencil.getLastLine())) { licenseState = LicenseState.COMPLETED; } else if ((singleLine.length() > 0) && (!singleLine.startsWith(stencil.getBeforeEachLine()))) { licenseState = LicenseState.TERMINATED; } else if ((singleLine.length() == 0) && stencil.willPrefixBlankLines()) { licenseState = LicenseState.TERMINATED; } break; default: throw new MojoFailureException("Unknown or inappropriate license seek state(" + licenseState.name() + ")"); } } else { fileWriter.write(singleLine); fileWriter.write(System.getProperty("file.separator")); } } if (licenseState.equals(LicenseState.COMPLETED) || ((singleLine != null) && (singleLine.length() == 0))) { do { singleLine = fileReader.readLine(); } while ((singleLine != null) && (singleLine.length() == 0)); } for (int count = 0; count < stencil.getBlankLinesBefore(); count++) { fileWriter.write(System.getProperty("file.separator")); } if (stencil.getFirstLine() != null) { fileWriter.write(stencil.getFirstLine()); fileWriter.write(System.getProperty("file.separator")); } for (String licenseLine : licenseArray) { if ((stencil.getBeforeEachLine() != null) && ((licenseLine.length() > 0) || stencil.willPrefixBlankLines())) { fileWriter.write(stencil.getBeforeEachLine()); } fileWriter.write(stencil.getFirstLine()); fileWriter.write(System.getProperty("file.separator")); } if (stencil.getLastLine() != null) { fileWriter.write(stencil.getLastLine()); fileWriter.write(System.getProperty("file.separator")); } for (int count = 0; count < stencil.getBlankLinesAfter(); count++) { fileWriter.write(System.getProperty("file.separator")); } if (singleLine != null) { fileWriter.write(singleLine); fileWriter.write(System.getProperty("file.separator")); } while ((charsRead = fileReader.read(buffer)) >= 0) { fileWriter.write(buffer, 0, charsRead); } fileWriter.close(); fileReader.close(); if (!licensedFile.delete()) { throw new MojoFailureException("Unable to delete file(" + licensedFile.getAbsolutePath() + ")"); } } catch (Exception exception) { tempFile.delete(); throw new MojoExecutionException("Exception during license processing", exception); } if (!tempFile.renameTo(licensedFile)) { throw new MojoFailureException("Unable to rename temp file(" + tempFile.getAbsolutePath() + ") to processed file(" + licensedFile.getAbsolutePath() + ")"); } } catch (MojoExecutionException mojoExecutionException) { throw mojoExecutionException; } catch (Exception exception) { throw new MojoExecutionException("Exception during license processing", exception); } } }
private void processFiles (Stencil stencil, String[] licenseArray, long licenseModTime, char[] buffer, String directoryPath, FileFilter... fileFilters) throws MojoExecutionException { File tempFile; BufferedReader fileReader; FileWriter fileWriter; LicenseState licenseState; Pattern skipPattern = null; String singleLine = null; int charsRead; if (stencil.getSkipLines() != null) { skipPattern = Pattern.compile(stencil.getSkipLines()); } for (File licensedFile : new LicensedFileIterator(new File(directoryPath), fileFilters)) { try { fileWriter = new FileWriter(tempFile = new File(licensedFile.getParent() + System.getProperty("file.separator") + "license.temp")); try { fileReader = new BufferedReader(new FileReader(licensedFile)); licenseState = (stencil.getFirstLine() != null) ? LicenseState.FIRST : LicenseState.LAST; while ((!(licenseState.equals(LicenseState.COMPLETED) || licenseState.equals(LicenseState.TERMINATED))) && ((singleLine = fileReader.readLine()) != null)) { if ((skipPattern == null) || (!skipPattern.matcher(singleLine).matches())) { switch (licenseState) { case FIRST: if (singleLine.length() > 0) { licenseState = singleLine.equals(stencil.getFirstLine()) ? LicenseState.LAST : LicenseState.TERMINATED; } break; case LAST: if ((stencil.getLastLine() != null) && singleLine.equals(stencil.getLastLine())) { licenseState = LicenseState.COMPLETED; } else if ((singleLine.length() > 0) && (!singleLine.startsWith(stencil.getBeforeEachLine()))) { licenseState = LicenseState.TERMINATED; } else if ((singleLine.length() == 0) && stencil.willPrefixBlankLines()) { licenseState = LicenseState.TERMINATED; } break; default: throw new MojoFailureException("Unknown or inappropriate license seek state(" + licenseState.name() + ")"); } } else { fileWriter.write(singleLine); fileWriter.write(System.getProperty("line.separator")); } } if (licenseState.equals(LicenseState.COMPLETED) || ((singleLine != null) && (singleLine.length() == 0))) { do { singleLine = fileReader.readLine(); } while ((singleLine != null) && (singleLine.length() == 0)); } for (int count = 0; count < stencil.getBlankLinesBefore(); count++) { fileWriter.write(System.getProperty("line.separator")); } if (stencil.getFirstLine() != null) { fileWriter.write(stencil.getFirstLine()); fileWriter.write(System.getProperty("line.separator")); } for (String licenseLine : licenseArray) { if ((stencil.getBeforeEachLine() != null) && ((licenseLine.length() > 0) || stencil.willPrefixBlankLines())) { fileWriter.write(stencil.getBeforeEachLine()); } fileWriter.write(licenseLine); fileWriter.write(System.getProperty("line.separator")); } if (stencil.getLastLine() != null) { fileWriter.write(stencil.getLastLine()); fileWriter.write(System.getProperty("line.separator")); } for (int count = 0; count < stencil.getBlankLinesAfter(); count++) { fileWriter.write(System.getProperty("line.separator")); } if (singleLine != null) { fileWriter.write(singleLine); fileWriter.write(System.getProperty("line.separator")); } while ((charsRead = fileReader.read(buffer)) >= 0) { fileWriter.write(buffer, 0, charsRead); } fileWriter.close(); fileReader.close(); if (!licensedFile.delete()) { throw new MojoFailureException("Unable to delete file(" + licensedFile.getAbsolutePath() + ")"); } } catch (Exception exception) { tempFile.delete(); throw new MojoExecutionException("Exception during license processing", exception); } if (!tempFile.renameTo(licensedFile)) { throw new MojoFailureException("Unable to rename temp file(" + tempFile.getAbsolutePath() + ") to processed file(" + licensedFile.getAbsolutePath() + ")"); } } catch (MojoExecutionException mojoExecutionException) { throw mojoExecutionException; } catch (Exception exception) { throw new MojoExecutionException("Exception during license processing", exception); } } }
public void execute(final ConsoleClient client, Scanner scanner) throws CommandArgException { try { Connection conn = Connection.connect(new InetSocketAddress(host(scanner), port(scanner)), new FixMessageParser(), new Connection.Callback() { @Override public void messages(Connection conn, Iterator<Message> messages) { while (messages.hasNext()) { Message msg = messages.next(); client.getSession().receive(conn, msg, new DefaultMessageVisitor() { @Override public void defaultAction(fixengine.messages.Message message) { logger.info(message.toString()); } }); } } @Override public void idle(Connection conn) { client.getSession().keepAlive(conn); } @Override public void closed(Connection conn) { } }); client.setConnection(conn); Session session = new Session(getHeartBtInt(), getConfig(), client.getSessionStore()) { @Override protected boolean checkSeqResetSeqNum() { return false; } }; client.setSession(session); session.logon(conn); client.getEvents().register(conn); } catch (IOException e) { throw new RuntimeException(e); } }
public void execute(final ConsoleClient client, Scanner scanner) throws CommandArgException { try { Connection conn = Connection.connect(new InetSocketAddress(host(scanner), port(scanner)), new FixMessageParser(), new Connection.Callback() { @Override public void messages(Connection conn, Iterator<Message> messages) { while (messages.hasNext()) { Message msg = messages.next(); client.getSession().receive(conn, msg, new DefaultMessageVisitor() { @Override public void defaultAction(fixengine.messages.Message message) { logger.info(message.toString()); } }); } } @Override public void idle(Connection conn) { client.getSession().keepAlive(conn); } @Override public void closed(Connection conn) { } }); client.setConnection(conn); Session session = new Session(getHeartBtInt(), getConfig(), client.getSessionStore(), client.getMessageFactory()) { @Override protected boolean checkSeqResetSeqNum() { return false; } }; client.setSession(session); session.logon(conn); client.getEvents().register(conn); } catch (IOException e) { throw new RuntimeException(e); } }
public void processMessage(Privmsg privmsg) { String[] params = privmsg.getMessage().split(" "); if (params.length == 0) { privmsg.send("Version: " + version); } else { privmsg.send("Version: " + version + ", last commit \"" + commitMessage + "\" by " + commitAuthor + ", " + commitTime); } }
public void processMessage(Privmsg privmsg) { String[] params = privmsg.getMessage().split(" "); if (params.length == 1) { privmsg.send("Version: " + version); } else { privmsg.send("Version: " + version + ", last commit \"" + commitMessage + "\" by " + commitAuthor + ", " + commitTime); } }
private boolean parse(final Nodes root) throws Exception { final String pth = text("@FilePath", root); final String outname = text("@name", root); if(single != null && !outname.startsWith(single)) return true; Performance perf = new Performance(); if(verbose) Util.out("- " + outname); boolean inspect = false; boolean correct = true; final Nodes nodes = states(root); for(int n = 0; n < nodes.size(); ++n) { final Nodes state = new Nodes(nodes.nodes[n], nodes.data); final String inname = text("*:query/@name", state); context.query = IO.get(queries + pth + inname + IO.XQSUFFIX); final String in = read(context.query); String er = null; ItemIter iter = null; boolean doc = true; final Nodes cont = nodes("*:contextItem", state); Nodes curr = null; if(cont.size() != 0) { final Data d = Check.check(context, srcs.get(string(data.atom(cont.nodes[0])))); curr = new Nodes(d.doc(), d); curr.doc = true; } context.prop.set(Prop.QUERYINFO, compile); final QueryProcessor xq = new QueryProcessor(in, curr, context); context.prop.set(Prop.QUERYINFO, false); final ArrayOutput ao = new ArrayOutput(); final TokenBuilder files = new TokenBuilder(); try { files.add(file(nodes("*:input-file", state), nodes("*:input-file/@variable", state), xq, n == 0)); files.add(file(nodes("*:defaultCollection", state), null, xq, n == 0)); var(nodes("*:input-URI", state), nodes("*:input-URI/@variable", state), xq); eval(nodes("*:input-query/@name", state), nodes("*:input-query/@variable", state), pth, xq); parse(xq, state); for(final int p : nodes("*:module", root).nodes) { final String ns = text("@namespace", new Nodes(p, data)); final String f = mods.get(string(data.atom(p))) + IO.XQSUFFIX; xq.module(ns, f); } final SerializerProp sp = new SerializerProp(); sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ? DataText.YES : DataText.NO); final XMLSerializer xml = new XMLSerializer(ao, sp); iter = ItemIter.get(xq.iter()); Item it; while((it = iter.next()) != null) { doc &= it.type == Type.DOC; it.serialize(xml); } xml.close(); } catch(final Exception ex) { if(!(ex instanceof QueryException || ex instanceof IOException)) { System.err.println("\n*** " + outname + " ***"); System.err.println(in + "\n"); ex.printStackTrace(); } er = ex.getMessage(); if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1); if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2"); } if(compile) { Util.errln("---------------------------------------------------------"); Util.err(xq.info()); Util.errln(in); } final Nodes outFiles = nodes("*:output-file/text()", state); final Nodes cmpFiles = nodes("*:output-file/@compare", state); boolean xml = false; boolean frag = false; final TokenList result = new TokenList(); for(int o = 0; o < outFiles.size(); ++o) { final String resFile = string(data.atom(outFiles.nodes[o])); final IO exp = IO.get(expected + pth + resFile); result.add(read(exp)); final byte[] type = data.atom(cmpFiles.nodes[o]); xml |= eq(type, XML); frag |= eq(type, FRAGMENT); } String expError = text("*:expected-error/text()", state); final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX); if(files.size() != 0) { log.append(" ["); log.append(files); log.append("]"); } log.append(NL); log.append(norm(in)); log.append(NL); final String logStr = log.toString(); final boolean print = currTime || !logStr.contains("current-"); boolean correctError = false; if(er != null && (outFiles.size() == 0 || !expError.isEmpty())) { expError = error(pth + outname, expError); final String code = er.substring(0, Math.min(8, er.length())); for(final String e : SLASH.split(expError)) { if(code.equals(e)) { correctError = true; break; } } } if(correctError) { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(er)); logOK.append(NL); logOK.append(NL); addLog(pth, outname + ".log", er); } ++ok; } else if(er == null) { int s = -1; final int rs = result.size(); while(++s < rs) { inspect |= s < cmpFiles.nodes.length && eq(data.atom(cmpFiles.nodes[s]), INSPECT); final byte[] res = result.get(s), actual = ao.toArray(); if(res.length == ao.size() && eq(res, actual)) break; if(xml || frag) { iter.reset(); String ri = string(res).trim(); if(!doc) { if(ri.startsWith("<?xml")) ri = ri.replaceAll("^<.*?>\\s*", ""); ri = "<X>" + ri + "</X>"; } try { final Data rdata = CreateDB.xml(IO.get(ri), context); final ItemIter ir = new ItemIter(); for(int pre = doc ? 0 : 2; pre < rdata.meta.size;) { ir.add(new DBNode(rdata, pre)); pre += rdata.size(pre, rdata.kind(pre)); } boolean eq = FNSimple.deep(null, iter, ir); if(!eq && !doc) { ir.reset(); final Data adata = CreateDB.xml(IO.get("<X>" + string(actual) + "</X>"), context); final ItemIter ia = new ItemIter(); for(int pre = 2; pre < adata.meta.size;) { ia.add(new DBNode(adata, pre)); pre += adata.size(pre, adata.kind(pre)); } eq = FNSimple.deep(null, ia, ir); } if(!eq && debug) { iter.reset(); ir.reset(); final XMLSerializer ser = new XMLSerializer(System.out); Item it; Util.outln(NL + "=== " + testid + " ==="); while((it = ir.next()) != null) it.serialize(ser); Util.outln(NL + "=== " + NAME + " ==="); while((it = iter.next()) != null) it.serialize(ser); Util.outln(); } rdata.close(); if(eq) break; } catch(final IOException ex) { } catch(final Throwable ex) { ex.printStackTrace(); } } } if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) { if(print) { if(outFiles.size() == 0) result.add(error(pth + outname, expError)); logErr.append(logStr); logErr.append("[" + testid + " ] "); logErr.append(norm(string(result.get(0)))); logErr.append(NL); logErr.append("[Wrong] "); logErr.append(norm(ao.toString())); logErr.append(NL); logErr.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } correct = false; ++err; } else { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(ao.toString())); logOK.append(NL); logOK.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } ++ok; } } else { if(outFiles.size() == 0 || !expError.isEmpty()) { if(print) { logOK2.append(logStr); logOK2.append("[" + testid + " ] "); logOK2.append(norm(expError)); logOK2.append(NL); logOK2.append("[Rght?] "); logOK2.append(norm(er)); logOK2.append(NL); logOK2.append(NL); addLog(pth, outname + ".log", er); } ++ok2; } else { if(print) { logErr2.append(logStr); logErr2.append("[" + testid + " ] "); logErr2.append(norm(string(result.get(0)))); logErr2.append(NL); logErr2.append("[Wrong] "); logErr2.append(norm(er)); logErr2.append(NL); logErr2.append(NL); addLog(pth, outname + ".log", er); } correct = false; ++err2; } } if(curr != null) Close.close(context, curr.data); xq.close(); } if(reporting) { logReport.append(" <test-case name=\""); logReport.append(outname); logReport.append("\" result='"); logReport.append(correct ? "pass" : "fail"); if(inspect) logReport.append("' todo='inspect"); logReport.append("'/>"); logReport.append(NL); } if(verbose) { final long t = perf.getTime(); if(t > 100000000) Util.out(": " + Performance.getTimer(t, 1)); Util.outln(); } return single == null || !outname.equals(single); }
private boolean parse(final Nodes root) throws Exception { final String pth = text("@FilePath", root); final String outname = text("@name", root); if(single != null && !outname.startsWith(single)) return true; Performance perf = new Performance(); if(verbose) Util.out("- " + outname); boolean inspect = false; boolean correct = true; final Nodes nodes = states(root); for(int n = 0; n < nodes.size(); ++n) { final Nodes state = new Nodes(nodes.nodes[n], nodes.data); final String inname = text("*:query/@name", state); context.query = IO.get(queries + pth + inname + IO.XQSUFFIX); final String in = read(context.query); String er = null; ItemIter iter = null; boolean doc = true; final Nodes cont = nodes("*:contextItem", state); Nodes curr = null; if(cont.size() != 0) { final Data d = Check.check(context, srcs.get(string(data.atom(cont.nodes[0])))); curr = new Nodes(d.doc(), d); curr.root = true; } context.prop.set(Prop.QUERYINFO, compile); final QueryProcessor xq = new QueryProcessor(in, curr, context); context.prop.set(Prop.QUERYINFO, false); final ArrayOutput ao = new ArrayOutput(); final TokenBuilder files = new TokenBuilder(); try { files.add(file(nodes("*:input-file", state), nodes("*:input-file/@variable", state), xq, n == 0)); files.add(file(nodes("*:defaultCollection", state), null, xq, n == 0)); var(nodes("*:input-URI", state), nodes("*:input-URI/@variable", state), xq); eval(nodes("*:input-query/@name", state), nodes("*:input-query/@variable", state), pth, xq); parse(xq, state); for(final int p : nodes("*:module", root).nodes) { final String ns = text("@namespace", new Nodes(p, data)); final String f = mods.get(string(data.atom(p))) + IO.XQSUFFIX; xq.module(ns, f); } final SerializerProp sp = new SerializerProp(); sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ? DataText.YES : DataText.NO); final XMLSerializer xml = new XMLSerializer(ao, sp); iter = ItemIter.get(xq.iter()); Item it; while((it = iter.next()) != null) { doc &= it.type == Type.DOC; it.serialize(xml); } xml.close(); } catch(final Exception ex) { if(!(ex instanceof QueryException || ex instanceof IOException)) { System.err.println("\n*** " + outname + " ***"); System.err.println(in + "\n"); ex.printStackTrace(); } er = ex.getMessage(); if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1); if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2"); } if(compile) { Util.errln("---------------------------------------------------------"); Util.err(xq.info()); Util.errln(in); } final Nodes outFiles = nodes("*:output-file/text()", state); final Nodes cmpFiles = nodes("*:output-file/@compare", state); boolean xml = false; boolean frag = false; final TokenList result = new TokenList(); for(int o = 0; o < outFiles.size(); ++o) { final String resFile = string(data.atom(outFiles.nodes[o])); final IO exp = IO.get(expected + pth + resFile); result.add(read(exp)); final byte[] type = data.atom(cmpFiles.nodes[o]); xml |= eq(type, XML); frag |= eq(type, FRAGMENT); } String expError = text("*:expected-error/text()", state); final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX); if(files.size() != 0) { log.append(" ["); log.append(files); log.append("]"); } log.append(NL); log.append(norm(in)); log.append(NL); final String logStr = log.toString(); final boolean print = currTime || !logStr.contains("current-"); boolean correctError = false; if(er != null && (outFiles.size() == 0 || !expError.isEmpty())) { expError = error(pth + outname, expError); final String code = er.substring(0, Math.min(8, er.length())); for(final String e : SLASH.split(expError)) { if(code.equals(e)) { correctError = true; break; } } } if(correctError) { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(er)); logOK.append(NL); logOK.append(NL); addLog(pth, outname + ".log", er); } ++ok; } else if(er == null) { int s = -1; final int rs = result.size(); while(++s < rs) { inspect |= s < cmpFiles.nodes.length && eq(data.atom(cmpFiles.nodes[s]), INSPECT); final byte[] res = result.get(s), actual = ao.toArray(); if(res.length == ao.size() && eq(res, actual)) break; if(xml || frag) { iter.reset(); String ri = string(res).trim(); if(!doc) { if(ri.startsWith("<?xml")) ri = ri.replaceAll("^<.*?>\\s*", ""); ri = "<X>" + ri + "</X>"; } try { final Data rdata = CreateDB.xml(IO.get(ri), context); final ItemIter ir = new ItemIter(); for(int pre = doc ? 0 : 2; pre < rdata.meta.size;) { ir.add(new DBNode(rdata, pre)); pre += rdata.size(pre, rdata.kind(pre)); } boolean eq = FNSimple.deep(null, iter, ir); if(!eq && !doc) { ir.reset(); final Data adata = CreateDB.xml(IO.get("<X>" + string(actual) + "</X>"), context); final ItemIter ia = new ItemIter(); for(int pre = 2; pre < adata.meta.size;) { ia.add(new DBNode(adata, pre)); pre += adata.size(pre, adata.kind(pre)); } eq = FNSimple.deep(null, ia, ir); } if(!eq && debug) { iter.reset(); ir.reset(); final XMLSerializer ser = new XMLSerializer(System.out); Item it; Util.outln(NL + "=== " + testid + " ==="); while((it = ir.next()) != null) it.serialize(ser); Util.outln(NL + "=== " + NAME + " ==="); while((it = iter.next()) != null) it.serialize(ser); Util.outln(); } rdata.close(); if(eq) break; } catch(final IOException ex) { } catch(final Throwable ex) { ex.printStackTrace(); } } } if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) { if(print) { if(outFiles.size() == 0) result.add(error(pth + outname, expError)); logErr.append(logStr); logErr.append("[" + testid + " ] "); logErr.append(norm(string(result.get(0)))); logErr.append(NL); logErr.append("[Wrong] "); logErr.append(norm(ao.toString())); logErr.append(NL); logErr.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } correct = false; ++err; } else { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(ao.toString())); logOK.append(NL); logOK.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } ++ok; } } else { if(outFiles.size() == 0 || !expError.isEmpty()) { if(print) { logOK2.append(logStr); logOK2.append("[" + testid + " ] "); logOK2.append(norm(expError)); logOK2.append(NL); logOK2.append("[Rght?] "); logOK2.append(norm(er)); logOK2.append(NL); logOK2.append(NL); addLog(pth, outname + ".log", er); } ++ok2; } else { if(print) { logErr2.append(logStr); logErr2.append("[" + testid + " ] "); logErr2.append(norm(string(result.get(0)))); logErr2.append(NL); logErr2.append("[Wrong] "); logErr2.append(norm(er)); logErr2.append(NL); logErr2.append(NL); addLog(pth, outname + ".log", er); } correct = false; ++err2; } } if(curr != null) Close.close(context, curr.data); xq.close(); } if(reporting) { logReport.append(" <test-case name=\""); logReport.append(outname); logReport.append("\" result='"); logReport.append(correct ? "pass" : "fail"); if(inspect) logReport.append("' todo='inspect"); logReport.append("'/>"); logReport.append(NL); } if(verbose) { final long t = perf.getTime(); if(t > 100000000) Util.out(": " + Performance.getTimer(t, 1)); Util.outln(); } return single == null || !outname.equals(single); }
protected void handleEndTag(EndTag endTag) { RULE_TYPE ruleType = RULE_TYPE.RULE_NOT_FOUND; if (ruleState.isExludedState()) { addToDocumentPart(endTag.toString()); updateEndTagRuleState(endTag); return; } ruleType = updateEndTagRuleState(endTag); switch (ruleType) { case INLINE_EXCLUDED_ELEMENT: eventBuilder.endCode(endTag.toString()); break; case INLINE_ELEMENT: if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeOuterData(endTag.toString()); eventBuilder.appendCodeData(endTag.toString()); break; } if (canStartNewTextUnit()) { startTextUnit(); } addCodeToCurrentTextUnit(endTag); break; case GROUP_ELEMENT: endGroup(new GenericSkeleton(endTag.toString())); break; case EXCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case INCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case TEXT_UNIT_ELEMENT: if (pcdataSubfilter != null && isInsideTextRun()) { ITextUnit pcdata = popTempEvent().getTextUnit(); String parentId = eventBuilder.findMostRecentParentId(); pcdataSubfilter.close(); parentId = (parentId == null ? getDocumentId().getLastId() : parentId); SubFilterEventConverter converter = new SubFilterEventConverter(parentId, new GenericSkeleton(((GenericSkeleton)pcdata.getSkeleton()).getFirstPart().toString()), new GenericSkeleton(endTag.toString())); ((AbstractFilter)pcdataSubfilter).setParentId(parentId); pcdataSubfilter.open(new RawDocument(pcdata.getSource().toString(), getSrcLoc())); int tuChildCount = 0; while (pcdataSubfilter.hasNext()) { Event event = converter.convertEvent(pcdataSubfilter.next()); if ("okf_html".equals(getConfig().getGlobalPCDATASubfilter())) { switch(event.getEventType()) { case DOCUMENT_PART: DocumentPart dp = event.getDocumentPart(); dp.setSkeleton(new GenericSkeleton(Util.escapeToXML(dp.getSkeleton().toString(), 0, true, null))); break; case TEXT_UNIT: ITextUnit tu = event.getTextUnit(); if (tu.getName() == null) { String parentName = eventBuilder.findMostRecentTextUnitName(); if (parentName != null) { parentName = parentName + "-" + Integer.toString(++tuChildCount); } tu.setName(parentName); } GenericSkeleton s = (GenericSkeleton)tu.getSkeleton(); for (GenericSkeletonPart p : s.getParts()) { if (p.getParent() == null) { p.setData(Util.escapeToXML(p.getData().toString(), 0, true, null)); } } tu.setSkeleton(s); List<Code> codes = tu.getSource().getFirstContent().getCodes(); for (Code c : codes) { c.setData(Util.escapeToXML(c.getData(), 0, true, null)); if (c.hasOuterData()) { c.setOuterData(Util.escapeToXML(c.getOuterData(), 0, true, null)); } } TextFragment f = new TextFragment(Util.escapeToXML(tu.getSource().getFirstContent().getCodedText(), 0, true, null), codes); tu.setSourceContent(f); break; } } eventBuilder.addFilterEvent(event); } pcdataSubfilter.close(); } else { endTextUnit(new GenericSkeleton(endTag.toString())); } break; default: addToDocumentPart(endTag.toString()); break; } if (getConfig().isRuleType(endTag.getName(), RULE_TYPE.PRESERVE_WHITESPACE)) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); } else if (ruleState.peekPreserverWhitespaceRule().ruleName.equalsIgnoreCase(endTag.getName())) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); } }
protected void handleEndTag(EndTag endTag) { RULE_TYPE ruleType = RULE_TYPE.RULE_NOT_FOUND; if (ruleState.isExludedState()) { addToDocumentPart(endTag.toString()); updateEndTagRuleState(endTag); return; } ruleType = updateEndTagRuleState(endTag); switch (ruleType) { case INLINE_EXCLUDED_ELEMENT: eventBuilder.endCode(endTag.toString()); break; case INLINE_ELEMENT: if (ruleState.isInlineExcludedState()) { eventBuilder.appendCodeOuterData(endTag.toString()); eventBuilder.appendCodeData(endTag.toString()); break; } if (canStartNewTextUnit()) { startTextUnit(); } addCodeToCurrentTextUnit(endTag); break; case GROUP_ELEMENT: endGroup(new GenericSkeleton(endTag.toString())); break; case EXCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case INCLUDED_ELEMENT: addToDocumentPart(endTag.toString()); break; case TEXT_UNIT_ELEMENT: if (pcdataSubfilter != null && isInsideTextRun()) { ITextUnit pcdata = popTempEvent().getTextUnit(); String parentId = eventBuilder.findMostRecentParentId(); pcdataSubfilter.close(); parentId = (parentId == null ? getDocumentId().getLastId() : parentId); SubFilterEventConverter converter = new SubFilterEventConverter(parentId, new GenericSkeleton(((GenericSkeleton)pcdata.getSkeleton()).getFirstPart().toString()), new GenericSkeleton(endTag.toString())); ((AbstractFilter)pcdataSubfilter).setParentId(parentId); pcdataSubfilter.open(new RawDocument(pcdata.getSource().toString(), getSrcLoc())); int tuChildCount = 0; while (pcdataSubfilter.hasNext()) { Event event = converter.convertEvent(pcdataSubfilter.next()); if ("okf_html".equals(getConfig().getGlobalPCDATASubfilter())) { switch(event.getEventType()) { case DOCUMENT_PART: DocumentPart dp = event.getDocumentPart(); dp.setSkeleton(new GenericSkeleton(Util.escapeToXML(dp.getSkeleton().toString(), 0, true, null))); break; case TEXT_UNIT: ITextUnit tu = event.getTextUnit(); if (tu.getName() == null) { String parentName = eventBuilder.findMostRecentTextUnitName(); if (parentName != null) { parentName = parentName + "-" + Integer.toString(++tuChildCount); } tu.setName(parentName); } GenericSkeleton s = (GenericSkeleton)tu.getSkeleton(); if (s != null) { for (GenericSkeletonPart p : s.getParts()) { if (p.getParent() == null) { p.setData(Util.escapeToXML(p.getData().toString(), 0, true, null)); } } tu.setSkeleton(s); } List<Code> codes = tu.getSource().getFirstContent().getCodes(); for (Code c : codes) { c.setData(Util.escapeToXML(c.getData(), 0, true, null)); if (c.hasOuterData()) { c.setOuterData(Util.escapeToXML(c.getOuterData(), 0, true, null)); } } TextFragment f = new TextFragment(Util.escapeToXML(tu.getSource().getFirstContent().getCodedText(), 0, true, null), codes); tu.setSourceContent(f); break; } } eventBuilder.addFilterEvent(event); } pcdataSubfilter.close(); } else { endTextUnit(new GenericSkeleton(endTag.toString())); } break; default: addToDocumentPart(endTag.toString()); break; } if (getConfig().isRuleType(endTag.getName(), RULE_TYPE.PRESERVE_WHITESPACE)) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); } else if (ruleState.peekPreserverWhitespaceRule().ruleName.equalsIgnoreCase(endTag.getName())) { ruleState.popPreserverWhitespaceRule(); setPreserveWhitespace(ruleState.isPreserveWhitespaceState()); } }
public static void main(String[] args) { System.out.println("Hello ACP"); }
public static void main(String[] args) { System.out.println("Hello"); }
public void onEntitySpawn(EntityJoinWorldEvent event) { Entity entity = event.entity; if (!(entity instanceof EntityLiving)) return; EntityAITasks tasks = ObfuscationReflectionHelper.getPrivateValue(EntityLiving.class, ((EntityLiving)entity), new String[] { "tasks" }); if (entity instanceof EntityChicken) { tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 0, false)); } if (entity instanceof EntitySheep) { tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 1, false)); } if (entity instanceof EntityPig) { tasks.addTask(4, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 2, false)); } if (entity instanceof EntityCow) { tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 3, false)); } }
public void onEntitySpawn(EntityJoinWorldEvent event) { Entity entity = event.entity; if (!(entity instanceof EntityLiving)) return; EntityAITasks tasks = ObfuscationReflectionHelper.getPrivateValue(EntityLiving.class, ((EntityLiving)entity), new String[] { "field_75732_c" }); if (entity instanceof EntityChicken) { tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 0, false)); } if (entity instanceof EntitySheep) { tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 1, false)); } if (entity instanceof EntityPig) { tasks.addTask(4, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 2, false)); } if (entity instanceof EntityCow) { tasks.addTask(3, new EntityAITemptArmor((EntityCreature)entity, 1F, BOPItemHelper.get("flowerBand"), 3, false)); } }
public T next() { if(firstNext == null && secondNext != null) { return getAndNextSecond(); } else if (firstNext != null && secondNext == null) { return getAndNextFirst(); } else if (firstNext == null && secondNext == null) { throw new NoSuchElementException(); } int res = comparator.compare(firstNext, secondNext); if(res < 0) { return getAndNextFirst(); } else if (res > 0) { return getAndNextSecond(); } T merged = merger.merge(getAndNextFirst(), getAndNextSecond()); while (firstNext != null && comparator.compare(merged, firstNext) == 0) { merged = merger.merge(merged, getAndNextFirst()); } while (firstNext != null && comparator.compare(merged, secondNext) == 0) { merged = merger.merge(merged, getAndNextSecond()); } return merged; }
public T next() { if(firstNext == null && secondNext != null) { return getAndNextSecond(); } else if (firstNext != null && secondNext == null) { return getAndNextFirst(); } else if (firstNext == null && secondNext == null) { throw new NoSuchElementException(); } int res = comparator.compare(firstNext, secondNext); if(res < 0) { return getAndNextFirst(); } else if (res > 0) { return getAndNextSecond(); } T merged = merger.merge(getAndNextFirst(), getAndNextSecond()); while (firstNext != null && comparator.compare(merged, firstNext) == 0) { merged = merger.merge(merged, getAndNextFirst()); } while (secondNext != null && comparator.compare(merged, secondNext) == 0) { merged = merger.merge(merged, getAndNextSecond()); } return merged; }
public void setup() { VizModel vizModel = VizController.getInstance().getVizModel(); adjustTextCheckbox.setSelected(vizModel.isAdjustByText()); adjustTextCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setAdjustByText(adjustTextCheckbox.isSelected()); } }); final DefaultComboBoxModel comboModel = new DefaultComboBoxModel(); final ModelClass nodeClass = VizController.getInstance().getModelClassLibrary().getNodeClass(); for (Modeler modeler : nodeClass.getModelers()) { comboModel.addElement(modeler); } comboModel.setSelectedItem(nodeClass.getCurrentModeler()); shapeCombo.setModel(comboModel); shapeCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (nodeClass.getCurrentModeler() == comboModel.getSelectedItem()) { return; } VizModel vizModel = VizController.getInstance().getVizModel(); NodeModeler modeler = (NodeModeler) comboModel.getSelectedItem(); if (modeler.is3d() && !vizModel.isUse3d()) { String msg = NbBundle.getMessage(NodeSettingsPanel.class, "NodeSettingsPanel.defaultShape.message3d"); if (JOptionPane.showConfirmDialog(WindowManager.getDefault().getMainWindow(), msg, NbBundle.getMessage(NodeSettingsPanel.class, "NodeSettingsPanel.defaultShape.message.title"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { vizModel.setUse3d(true); nodeClass.setCurrentModeler(modeler); } } else if (!modeler.is3d() && vizModel.isUse3d()) { String msg = NbBundle.getMessage(NodeSettingsPanel.class, "NodeSettingsPanel.defaultShape.message2d"); if (JOptionPane.showConfirmDialog(WindowManager.getDefault().getMainWindow(), msg, NbBundle.getMessage(NodeSettingsPanel.class, "NodeSettingsPanel.defaultShape.message.title"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { vizModel.setUse3d(false); nodeClass.setCurrentModeler(modeler); } } else { nodeClass.setCurrentModeler(modeler); } } }); showHullsCheckbox.setSelected(vizModel.isShowHulls()); showHullsCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setShowHulls(showHullsCheckbox.isSelected()); } }); vizModel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("nodeModeler")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("init")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("adjustByText")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("showHulls")) { refreshSharedConfig(); } } }); refreshSharedConfig(); }
public void setup() { VizModel vizModel = VizController.getInstance().getVizModel(); adjustTextCheckbox.setSelected(vizModel.isAdjustByText()); adjustTextCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setAdjustByText(adjustTextCheckbox.isSelected()); } }); final DefaultComboBoxModel comboModel = new DefaultComboBoxModel(); final ModelClass nodeClass = VizController.getInstance().getModelClassLibrary().getNodeClass(); for (Modeler modeler : nodeClass.getModelers()) { comboModel.addElement(modeler); } comboModel.setSelectedItem(nodeClass.getCurrentModeler()); shapeCombo.setModel(comboModel); shapeCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (nodeClass.getCurrentModeler() == comboModel.getSelectedItem()) { return; } VizModel vizModel = VizController.getInstance().getVizModel(); NodeModeler modeler = (NodeModeler) comboModel.getSelectedItem(); if (modeler.is3d() && !vizModel.isUse3d()) { vizModel.setUse3d(true); nodeClass.setCurrentModeler(modeler); } else if (!modeler.is3d() && vizModel.isUse3d()) { vizModel.setUse3d(false); nodeClass.setCurrentModeler(modeler); } else { nodeClass.setCurrentModeler(modeler); } } }); showHullsCheckbox.setSelected(vizModel.isShowHulls()); showHullsCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { VizModel vizModel = VizController.getInstance().getVizModel(); vizModel.setShowHulls(showHullsCheckbox.isSelected()); } }); vizModel.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("nodeModeler")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("init")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("adjustByText")) { refreshSharedConfig(); } else if (evt.getPropertyName().equals("showHulls")) { refreshSharedConfig(); } } }); refreshSharedConfig(); }
public Object track(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class.cast(point.getSignature()).getMethod(); final Step step = method.getAnnotation(Step.class); final String label = Integer.toString( Math.abs(StepAspect.RND.nextInt()) ); final ImmutableMap.Builder<String, Object> args = new ImmutableMap.Builder<String, Object>() .put("this", new StepAspect.Open(point.getThis())) .put("args", point.getArgs()); final String before; if (step.before().isEmpty()) { before = String.format( "%s#%s()", method.getDeclaringClass().getCanonicalName(), method.getName() ); } else { before = new Vext(step.before()).print(args.build()); } new XemblyLine( new Directives() .xpath("/snapshot") .addIfAbsent("steps").strict(1) .add("step").strict(1) .attr("id", label) .attr("class", method.getDeclaringClass().getCanonicalName()) .attr("method", method.getName()) .add("start").set(new Time().toString()).up() .add("summary") .set(before) ).log(); try { final Object result = point.proceed(); if (result != null) { args.put("result", result); } this.mark(label, Level.INFO); new XemblyLine( new Directives() .xpath(String.format("//step[@id=%s]/summary", label)) .strict(1) .set(new Vext(step.value()).print(args.build())) ).log(); return result; } catch (Throwable ex) { this.mark(label, Level.SEVERE); new XemblyLine( new Directives() .xpath(String.format("/snapshot/steps/step[@id=%s]", label)) .add("exception") .set(ExceptionUtils.getRootCauseMessage(ex)) ).log(); throw ex; } finally { new XemblyLine( new Directives() .xpath(String.format("/snapshot/steps/step[@id=%s]", label)) .strict(1) .add("finish").set(new Time().toString()) ).log(); } }
public Object track(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class.cast(point.getSignature()).getMethod(); final Step step = method.getAnnotation(Step.class); final String label = Integer.toString( Math.abs(StepAspect.RND.nextInt()) ); final ImmutableMap.Builder<String, Object> args = new ImmutableMap.Builder<String, Object>() .put("this", new StepAspect.Open(point.getThis())) .put("args", point.getArgs()); final String before; if (step.before().isEmpty()) { before = String.format( "%s#%s()", method.getDeclaringClass().getCanonicalName(), method.getName() ); } else { before = new Vext(step.before()).print(args.build()); } new XemblyLine( new Directives() .xpath("/snapshot") .addIfAbsent("steps").strict(1) .add("step").strict(1) .attr("id", label) .attr("class", method.getDeclaringClass().getCanonicalName()) .attr("method", method.getName()) .add("start").set(new Time().toString()).up() .add("summary") .set(before) ).log(); final long start = System.currentTimeMillis(); try { final Object result = point.proceed(); if (result != null) { args.put("result", result); } this.mark(label, Level.INFO); new XemblyLine( new Directives() .xpath(String.format("//step[@id=%s]/summary", label)) .strict(1) .set(new Vext(step.value()).print(args.build())) ).log(); return result; } catch (Throwable ex) { this.mark(label, Level.SEVERE); new XemblyLine( new Directives() .xpath(String.format("/snapshot/steps/step[@id=%s]", label)) .add("exception") .set(ExceptionUtils.getRootCauseMessage(ex)) ).log(); throw ex; } finally { new XemblyLine( new Directives() .xpath(String.format("/snapshot/steps/step[@id=%s]", label)) .strict(1) .add("finish").set(new Time().toString()).up() .add("duration") .set(Long.toString(System.currentTimeMillis() - start)) ).log(); } }
private Graph parseFile( String fileName ) { Graph graph = new Graph(); graph.setFileKey( fileName ); SAXBuilder parser = new SAXBuilder( "org.apache.crimson.parser.XMLReaderImpl", false ); try { logger.debug( "Parsing file: " + fileName ); Document doc = parser.build( fileName ); Iterator<Object> iter_node = doc.getDescendants( new org.jdom.filter.ElementFilter( "node" ) ); while ( iter_node.hasNext() ) { Object o = iter_node.next(); if ( o instanceof org.jdom.Element ) { org.jdom.Element element = (org.jdom.Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { logger.debug( " Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } Iterator<Object> iterUMLNoteIter = element.getDescendants( new org.jdom.filter.ElementFilter( "UMLNoteNode" ) ); if ( iterUMLNoteIter.hasNext() ) { logger.debug( " Excluded node: UMLNoteNode" ); continue; } logger.debug( " id: " + element.getAttributeValue( "id" ) ); Vertex currentVertex = null; Iterator<Object> iterNodeLabel = element.getDescendants( new org.jdom.filter.ElementFilter( "NodeLabel" ) ); while ( iterNodeLabel.hasNext() ) { Object o2 = iterNodeLabel.next(); if ( o2 instanceof org.jdom.Element ) { org.jdom.Element nodeLabel = (org.jdom.Element)o2; logger.debug( " Full name: '" + nodeLabel.getQualifiedName() + "'" ); logger.debug( " Name: '" + nodeLabel.getTextTrim() + "'" ); Vertex v = new Vertex(); graph.addVertex( v ); currentVertex = v; v.setIdKey( element.getAttributeValue( "id" ) ); v.setVisitedKey( new Integer( 0 ) ); v.setFileKey( fileName ); v.setFullLabelKey( nodeLabel.getTextTrim() ); v.setIndexKey( new Integer( getNewVertexAndEdgeIndex() ) ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find() ) { label = m.group( 1 ); if ( label.length() <= 0 ) { throw new RuntimeException( "Vertex is missing its label in file: '" + fileName + "'" ); } if ( label.matches( ".*[\\s].*" ) ) { throw new RuntimeException( "Vertex has a label '" + label + "', containing whitespaces in file: '" + fileName + "'" ); } if ( Keywords.isKeyWord( label ) ) { throw new RuntimeException( "Vertex has a label '" + label + "', which is a reserved keyword, in file: '" + fileName + "'" ); } v.setLabelKey( label ); } else { throw new RuntimeException( "Label must be defined in file: '" + fileName + "'" ); } logger.debug( " Added vertex: '" + v.getLabelKey() + "', with id: " + v.getIndexKey() ); p = Pattern.compile( "\\n(MERGE)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.setMergeKey( true ); logger.debug( " Found MERGE for vertex: " + label ); } p = Pattern.compile( "\\n(NO_MERGE)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.setNoMergeKey( true ); logger.debug( " Found NO_MERGE for vertex: " + label ); } p = Pattern.compile( "\\n(BLOCKED)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { logger.debug( " Found BLOCKED. This vetex will be removed from the graph: " + label ); v.setBlockedKey( true ); } p = Pattern.compile( "\\n(INDEX=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { String index_key = m.group( 2 ); logger.debug( " Found INDEX. This vertex will use the INDEX key: " + index_key ); v.setIndexKey( new Integer( index_key ) ); } p = Pattern.compile( "\\n(REQTAG=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { String value = m.group( 2 ); p = Pattern.compile( "([^,]+)", Pattern.MULTILINE ); m = p.matcher( value ); String reqtags = ""; while ( m.find() ) { String reqtag = m.group( 1 ); reqtag = reqtag.trim(); logger.debug( " Found REQTAG: " + reqtag ); if ( reqtags.length() == 0 ) { reqtags = reqtag; } else { reqtags += "," + reqtag; } } v.setReqTagKey( reqtags ); } } } Iterator<Object> iterImage = element.getDescendants( new org.jdom.filter.ElementFilter( "Image" ) ); while ( iterImage.hasNext() && currentVertex != null) { Object o2 = iterImage.next(); if ( o2 instanceof org.jdom.Element ) { org.jdom.Element image = (org.jdom.Element)o2; if ( image.getAttributeValue( "href" ) != null ) { logger.debug( " Image: '" + image.getAttributeValue( "href" ) + "'" ); currentVertex.setImageKey( image.getAttributeValue( "href" ) ); } } } Iterator<Object> iterGeometry = element.getDescendants( new org.jdom.filter.ElementFilter( "Geometry" ) ); while ( iterGeometry.hasNext() && currentVertex != null) { Object o2 = iterGeometry.next(); if ( o2 instanceof org.jdom.Element ) { org.jdom.Element geometry = (org.jdom.Element)o2; logger.debug( " width: '" + geometry.getAttributeValue( "width" ) + "'" ); logger.debug( " height: '" + geometry.getAttributeValue( "height" ) + "'" ); logger.debug( " x position: '" + geometry.getAttributeValue( "x" ) + "'" ); logger.debug( " y position: '" + geometry.getAttributeValue( "y" ) + "'" ); currentVertex.setWidth( Float.parseFloat( geometry.getAttributeValue( "width" ) ) ); currentVertex.setHeight( Float.parseFloat( geometry.getAttributeValue( "height" ) ) ); currentVertex.setLocation( new Point2D.Float( Float.parseFloat( geometry.getAttributeValue( "x" ) ), Float.parseFloat( geometry.getAttributeValue( "y" ) ) ) ); } } Iterator<Object> iterFill = element.getDescendants( new org.jdom.filter.ElementFilter( "Fill" ) ); while ( iterFill.hasNext() && currentVertex != null ) { Object o2 = iterFill.next(); if ( o2 instanceof org.jdom.Element ) { org.jdom.Element fill = (org.jdom.Element)o2; logger.debug( " fill color: '" + fill.getAttributeValue( "color" ) + "'" ); currentVertex.setFillColor( new Color( Integer.parseInt(fill.getAttributeValue( "color" ).replace("#", ""), 16) ) ); } } } } Object[] vertices = graph.getVertices().toArray(); Iterator<Object> iter_edge = doc.getDescendants( new org.jdom.filter.ElementFilter( "edge" ) ); while ( iter_edge.hasNext() ) { Object o = iter_edge.next(); if ( o instanceof org.jdom.Element ) { org.jdom.Element element = (org.jdom.Element)o; logger.debug( " id: " + element.getAttributeValue( "id" ) ); Iterator<Object> iter2 = element.getDescendants( new org.jdom.filter.ElementFilter( "EdgeLabel" ) ); org.jdom.Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof org.jdom.Element ) { edgeLabel = (org.jdom.Element)o2; logger.debug( " Full name: '" + edgeLabel.getQualifiedName() + "'" ); logger.debug( " Name: '" + edgeLabel.getTextTrim() + "'" ); } } logger.debug( " source: " + element.getAttributeValue( "source" ) ); logger.debug( " target: " + element.getAttributeValue( "target" ) ); Vertex source = null; Vertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { Vertex vertex = (Vertex)vertices[ i ]; if ( vertex.getIdKey().equals( element.getAttributeValue( "source" ) ) && vertex.getFileKey().equals( fileName ) ) { source = vertex; } if ( vertex.getIdKey().equals( element.getAttributeValue( "target" ) ) && vertex.getFileKey().equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: '" + element.getAttributeValue( "source" ) + "' In file '" + fileName + "'"; logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: '" + element.getAttributeValue( "target" ) + "' In file '" + fileName + "'"; logger.error( msg ); throw new RuntimeException( msg ); } Edge e = new Edge(); e.setIdKey( element.getAttributeValue( "id" ) ); e.setFileKey( fileName ); e.setIndexKey( new Integer( getNewVertexAndEdgeIndex() ) ); if ( !graph.addEdge( e, source, dest ) ) { String msg = "Failed adding edge: " + e + ", to graph: " + graph; logger.error( msg ); throw new RuntimeException( msg ); } if ( edgeLabel != null ) { String str = edgeLabel.getText(); e.setFullLabelKey( str ); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); Pattern firstLinePattern = Pattern.compile( "\\[(.*)\\]", Pattern.MULTILINE ); Matcher firstLineMatcher = firstLinePattern.matcher( label ); if ( firstLineMatcher.find() ) { String guard = firstLineMatcher.group( 1 ); e.setGuardKey( guard ); logger.debug( " Found guard = '" + guard + "' for edge id: " + edgeLabel.getQualifiedName() ); } if(label.indexOf("/")>0) { String actionPart = label.substring(label.indexOf("/")+1); firstLinePattern = Pattern.compile( ".*$", Pattern.MULTILINE ); firstLineMatcher = firstLinePattern.matcher( actionPart ); if ( firstLineMatcher.find() ) { String actions = firstLineMatcher.group( 0 ).trim(); e.setActionsKey( actions ); logger.debug( " Found actions: '" + actions + "' for edge id: " + edgeLabel.getQualifiedName() ); } } firstLinePattern = Pattern.compile( "^(\\w+)\\s?([^/^\\[]+)?", Pattern.MULTILINE ); firstLineMatcher = firstLinePattern.matcher( label ); if ( firstLineMatcher.find() ) { String label_key = firstLineMatcher.group( 1 ); if ( Keywords.isKeyWord( label_key ) ) { throw new RuntimeException( "Edge has a label '" + label + "', which is a reserved keyword, in file: '" + fileName + "'" ); } e.setLabelKey( label_key ); logger.debug( " Found label = '" + label_key + "' for edge id: " + edgeLabel.getQualifiedName() ); String parameter = firstLineMatcher.group( 2 ); if ( parameter != null ) { parameter = parameter.trim(); e.setParameterKey( parameter ); logger.debug( " Found parameter = '" + parameter + "' for edge id: " + edgeLabel.getQualifiedName() ); } } } else { throw new RuntimeException( "Label for edge must be defined in file '" + fileName + "'" ); } p = Pattern.compile( "\\n(weight\\s*=\\s*(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); logger.debug( " Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() + " In file '" + fileName + "'" ); } e.setWeightKey( weight ); } p = Pattern.compile( "\\n(BLOCKED)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { logger.debug( " Found BLOCKED. This edge will be removed from the graph: " + label ); e.setBlockedKey( true ); } p = Pattern.compile( "\\n(BACKTRACK)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { logger.debug( " Found BACKTRACK for edge: " + label ); e.setBacktrackKey( true ); } p = Pattern.compile( "\\n(INDEX=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { String index_key = m.group( 2 ); logger.debug( " Found INDEX. This edge will use the INDEX key: " + index_key ); e.setIndexKey( new Integer( index_key ) ); } p = Pattern.compile( "\\n(REQTAG=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { String value = m.group( 2 ); p = Pattern.compile( "([^,]+)", Pattern.MULTILINE ); m = p.matcher( value ); String reqtags = ""; while ( m.find() ) { String reqtag = m.group( 1 ); reqtag = reqtag.trim(); logger.debug( " Found REQTAG: " + reqtag ); if ( reqtags.length() == 0 ) { reqtags = reqtag; } else { reqtags += "," + reqtag; } } e.setReqTagKey( reqtags ); } } e.setVisitedKey( new Integer( 0 ) ); logger.debug( " Added edge: '" + e.getLabelKey() + "', with id: " + e.getIndexKey() ); } } } catch ( JDOMException e ) { logger.error( e ); throw new RuntimeException( "Could not parse file: '" + fileName + "'" ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Could not parse file: '" + fileName + "'" ); } logger.debug( "Finished parsing graph: " + graph ); removeBlockedEntities( graph ); logger.debug( "Graph after removing BLOCKED entities: " + graph ); return graph; }
private Graph parseFile( String fileName ) { Graph graph = new Graph(); graph.setFileKey( fileName ); SAXBuilder parser = new SAXBuilder( "org.apache.crimson.parser.XMLReaderImpl", false ); try { logger.debug( "Parsing file: " + fileName ); Document doc = parser.build( fileName ); Iterator<Object> iter_node = doc.getDescendants( new org.jdom.filter.ElementFilter( "node" ) ); while ( iter_node.hasNext() ) { Object o = iter_node.next(); if ( o instanceof org.jdom.Element ) { org.jdom.Element element = (org.jdom.Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { logger.debug( " Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } Iterator<Object> iterUMLNoteIter = element.getDescendants( new org.jdom.filter.ElementFilter( "UMLNoteNode" ) ); if ( iterUMLNoteIter.hasNext() ) { logger.debug( " Excluded node: UMLNoteNode" ); continue; } logger.debug( " id: " + element.getAttributeValue( "id" ) ); Vertex currentVertex = null; Iterator<Object> iterNodeLabel = element.getDescendants( new org.jdom.filter.ElementFilter( "NodeLabel" ) ); while ( iterNodeLabel.hasNext() ) { Object o2 = iterNodeLabel.next(); if ( o2 instanceof org.jdom.Element ) { org.jdom.Element nodeLabel = (org.jdom.Element)o2; logger.debug( " Full name: '" + nodeLabel.getQualifiedName() + "'" ); logger.debug( " Name: '" + nodeLabel.getTextTrim() + "'" ); Vertex v = new Vertex(); graph.addVertex( v ); currentVertex = v; v.setIdKey( element.getAttributeValue( "id" ) ); v.setVisitedKey( new Integer( 0 ) ); v.setFileKey( fileName ); v.setFullLabelKey( nodeLabel.getTextTrim() ); v.setIndexKey( new Integer( getNewVertexAndEdgeIndex() ) ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find() ) { label = m.group( 1 ); if ( label.length() <= 0 ) { throw new RuntimeException( "Vertex is missing its label in file: '" + fileName + "'" ); } if ( label.matches( ".*[\\s].*" ) ) { throw new RuntimeException( "Vertex has a label '" + label + "', containing whitespaces in file: '" + fileName + "'" ); } if ( Keywords.isKeyWord( label ) ) { throw new RuntimeException( "Vertex has a label '" + label + "', which is a reserved keyword, in file: '" + fileName + "'" ); } v.setLabelKey( label ); } else { throw new RuntimeException( "Label must be defined in file: '" + fileName + "'" ); } logger.debug( " Added vertex: '" + v.getLabelKey() + "', with id: " + v.getIndexKey() ); p = Pattern.compile( "\\n(MERGE)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.setMergeKey( true ); logger.debug( " Found MERGE for vertex: " + label ); } p = Pattern.compile( "\\n(NO_MERGE)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.setNoMergeKey( true ); logger.debug( " Found NO_MERGE for vertex: " + label ); } p = Pattern.compile( "\\n(BLOCKED)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { logger.debug( " Found BLOCKED. This vetex will be removed from the graph: " + label ); v.setBlockedKey( true ); } p = Pattern.compile( "\\n(INDEX=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { String index_key = m.group( 2 ); logger.debug( " Found INDEX. This vertex will use the INDEX key: " + index_key ); v.setIndexKey( new Integer( index_key ) ); } p = Pattern.compile( "\\n(REQTAG=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { String value = m.group( 2 ); p = Pattern.compile( "([^,]+)", Pattern.MULTILINE ); m = p.matcher( value ); String reqtags = ""; while ( m.find() ) { String reqtag = m.group( 1 ); reqtag = reqtag.trim(); logger.debug( " Found REQTAG: " + reqtag ); if ( reqtags.length() == 0 ) { reqtags = reqtag; } else { reqtags += "," + reqtag; } } v.setReqTagKey( reqtags ); } } } Iterator<Object> iterImage = element.getDescendants( new org.jdom.filter.ElementFilter( "Image" ) ); while ( iterImage.hasNext() && currentVertex != null) { Object o2 = iterImage.next(); if ( o2 instanceof org.jdom.Element ) { org.jdom.Element image = (org.jdom.Element)o2; if ( image.getAttributeValue( "href" ) != null ) { logger.debug( " Image: '" + image.getAttributeValue( "href" ) + "'" ); currentVertex.setImageKey( image.getAttributeValue( "href" ) ); } } } Iterator<Object> iterGeometry = element.getDescendants( new org.jdom.filter.ElementFilter( "Geometry" ) ); while ( iterGeometry.hasNext() && currentVertex != null) { Object o2 = iterGeometry.next(); if ( o2 instanceof org.jdom.Element ) { org.jdom.Element geometry = (org.jdom.Element)o2; logger.debug( " width: '" + geometry.getAttributeValue( "width" ) + "'" ); logger.debug( " height: '" + geometry.getAttributeValue( "height" ) + "'" ); logger.debug( " x position: '" + geometry.getAttributeValue( "x" ) + "'" ); logger.debug( " y position: '" + geometry.getAttributeValue( "y" ) + "'" ); currentVertex.setWidth( Float.parseFloat( geometry.getAttributeValue( "width" ) ) ); currentVertex.setHeight( Float.parseFloat( geometry.getAttributeValue( "height" ) ) ); currentVertex.setLocation( new Point2D.Float( Float.parseFloat( geometry.getAttributeValue( "x" ) ), Float.parseFloat( geometry.getAttributeValue( "y" ) ) ) ); } } Iterator<Object> iterFill = element.getDescendants( new org.jdom.filter.ElementFilter( "Fill" ) ); while ( iterFill.hasNext() && currentVertex != null ) { Object o2 = iterFill.next(); if ( o2 instanceof org.jdom.Element ) { org.jdom.Element fill = (org.jdom.Element)o2; logger.debug( " fill color: '" + fill.getAttributeValue( "color" ) + "'" ); currentVertex.setFillColor( new Color( Integer.parseInt(fill.getAttributeValue( "color" ).replace("#", ""), 16) ) ); } } } } Object[] vertices = graph.getVertices().toArray(); Iterator<Object> iter_edge = doc.getDescendants( new org.jdom.filter.ElementFilter( "edge" ) ); while ( iter_edge.hasNext() ) { Object o = iter_edge.next(); if ( o instanceof org.jdom.Element ) { org.jdom.Element element = (org.jdom.Element)o; logger.debug( " id: " + element.getAttributeValue( "id" ) ); Iterator<Object> iter2 = element.getDescendants( new org.jdom.filter.ElementFilter( "EdgeLabel" ) ); org.jdom.Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof org.jdom.Element ) { edgeLabel = (org.jdom.Element)o2; logger.debug( " Full name: '" + edgeLabel.getQualifiedName() + "'" ); logger.debug( " Name: '" + edgeLabel.getTextTrim() + "'" ); } } logger.debug( " source: " + element.getAttributeValue( "source" ) ); logger.debug( " target: " + element.getAttributeValue( "target" ) ); Vertex source = null; Vertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { Vertex vertex = (Vertex)vertices[ i ]; if ( vertex.getIdKey().equals( element.getAttributeValue( "source" ) ) && vertex.getFileKey().equals( fileName ) ) { source = vertex; } if ( vertex.getIdKey().equals( element.getAttributeValue( "target" ) ) && vertex.getFileKey().equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: '" + element.getAttributeValue( "source" ) + "' In file '" + fileName + "'"; logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: '" + element.getAttributeValue( "target" ) + "' In file '" + fileName + "'"; logger.error( msg ); throw new RuntimeException( msg ); } Edge e = new Edge(); e.setIdKey( element.getAttributeValue( "id" ) ); e.setFileKey( fileName ); e.setIndexKey( new Integer( getNewVertexAndEdgeIndex() ) ); if ( !graph.addEdge( e, source, dest ) ) { String msg = "Failed adding edge: " + e + ", to graph: " + graph; logger.error( msg ); throw new RuntimeException( msg ); } if ( edgeLabel != null ) { String str = edgeLabel.getText(); e.setFullLabelKey( str ); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); Pattern firstLinePattern = Pattern.compile( "\\[(.*)\\]\\s*/|\\[(.*)\\]\\s*$", Pattern.MULTILINE ); Matcher firstLineMatcher = firstLinePattern.matcher( label ); if ( firstLineMatcher.find() ) { String guard = firstLineMatcher.group( 1 ); if ( guard == null ) { guard = firstLineMatcher.group( 2 ); } e.setGuardKey( guard ); logger.debug( " Found guard = '" + guard + "' for edge id: " + edgeLabel.getQualifiedName() ); } if(label.indexOf("/")>0) { String actionPart = label.substring(label.indexOf("/")+1); firstLinePattern = Pattern.compile( ".*$", Pattern.MULTILINE ); firstLineMatcher = firstLinePattern.matcher( actionPart ); if ( firstLineMatcher.find() ) { String actions = firstLineMatcher.group( 0 ).trim(); e.setActionsKey( actions ); logger.debug( " Found actions: '" + actions + "' for edge id: " + edgeLabel.getQualifiedName() ); } } firstLinePattern = Pattern.compile( "^(\\w+)\\s?([^/^\\[]+)?", Pattern.MULTILINE ); firstLineMatcher = firstLinePattern.matcher( label ); if ( firstLineMatcher.find() ) { String label_key = firstLineMatcher.group( 1 ); if ( Keywords.isKeyWord( label_key ) ) { throw new RuntimeException( "Edge has a label '" + label + "', which is a reserved keyword, in file: '" + fileName + "'" ); } e.setLabelKey( label_key ); logger.debug( " Found label = '" + label_key + "' for edge id: " + edgeLabel.getQualifiedName() ); String parameter = firstLineMatcher.group( 2 ); if ( parameter != null ) { parameter = parameter.trim(); e.setParameterKey( parameter ); logger.debug( " Found parameter = '" + parameter + "' for edge id: " + edgeLabel.getQualifiedName() ); } } } else { throw new RuntimeException( "Label for edge must be defined in file '" + fileName + "'" ); } p = Pattern.compile( "\\n(weight\\s*=\\s*(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); logger.debug( " Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() + " In file '" + fileName + "'" ); } e.setWeightKey( weight ); } p = Pattern.compile( "\\n(BLOCKED)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { logger.debug( " Found BLOCKED. This edge will be removed from the graph: " + label ); e.setBlockedKey( true ); } p = Pattern.compile( "\\n(BACKTRACK)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { logger.debug( " Found BACKTRACK for edge: " + label ); e.setBacktrackKey( true ); } p = Pattern.compile( "\\n(INDEX=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { String index_key = m.group( 2 ); logger.debug( " Found INDEX. This edge will use the INDEX key: " + index_key ); e.setIndexKey( new Integer( index_key ) ); } p = Pattern.compile( "\\n(REQTAG=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { String value = m.group( 2 ); p = Pattern.compile( "([^,]+)", Pattern.MULTILINE ); m = p.matcher( value ); String reqtags = ""; while ( m.find() ) { String reqtag = m.group( 1 ); reqtag = reqtag.trim(); logger.debug( " Found REQTAG: " + reqtag ); if ( reqtags.length() == 0 ) { reqtags = reqtag; } else { reqtags += "," + reqtag; } } e.setReqTagKey( reqtags ); } } e.setVisitedKey( new Integer( 0 ) ); logger.debug( " Added edge: '" + e.getLabelKey() + "', with id: " + e.getIndexKey() ); } } } catch ( JDOMException e ) { logger.error( e ); throw new RuntimeException( "Could not parse file: '" + fileName + "'" ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Could not parse file: '" + fileName + "'" ); } logger.debug( "Finished parsing graph: " + graph ); removeBlockedEntities( graph ); logger.debug( "Graph after removing BLOCKED entities: " + graph ); return graph; }
public void execute(final InputWindow origin, final boolean isSilent, final String... args) { if (args.length < 2) { showUsage(origin, isSilent, "alias", "<name> <command>"); return; } for (Action alias : AliasWrapper.getAliasWrapper().getActions()) { if (AliasWrapper.getCommandName(alias).equalsIgnoreCase(args[0])) { sendLine(origin, isSilent, FORMAT_ERROR, "Alias '" + args[0] + "' already exists."); return; } } final Alias myAlias = new Alias(args[0]); myAlias.setResponse(new String[]{implodeArgs(1, args)}); myAlias.createAction().save(); sendLine(origin, isSilent, FORMAT_OUTPUT, "Alias '" + args[0] + "' created."); }
public void execute(final InputWindow origin, final boolean isSilent, final String... args) { if (args.length < 2) { showUsage(origin, isSilent, "alias", "<name> <command>"); return; } for (Action alias : AliasWrapper.getAliasWrapper().getActions()) { if (AliasWrapper.getCommandName(alias).substring(1).equalsIgnoreCase(args[0])) { sendLine(origin, isSilent, FORMAT_ERROR, "Alias '" + args[0] + "' already exists."); return; } } final Alias myAlias = new Alias(args[0]); myAlias.setResponse(new String[]{implodeArgs(1, args)}); myAlias.createAction().save(); sendLine(origin, isSilent, FORMAT_OUTPUT, "Alias '" + args[0] + "' created."); }
public void testYoYo() throws ExecutionException, InterruptedException, TimeoutException { ServiceLocator basicLocator = Utilities.getServiceLocator("AsyncRLSTest.basicYoYo", UpRecorder.class, DownRecorder.class, LevelFiveService_1.class, LevelFiveService_2.class, LevelTenService_1.class, LevelFifteenService_1.class, LevelFifteenService_2.class, LevelTwentyService_1.class); UpRecorder upRecorder = basicLocator.getService(UpRecorder.class); Assert.assertNotNull(upRecorder); upRecorder.getRecordsAndPurge(); DownRecorder downRecorder = basicLocator.getService(DownRecorder.class); Assert.assertNotNull(downRecorder); downRecorder.getRecordsAndPurge(); RunLevelController controller = basicLocator.getService(RunLevelController.class); RunLevelFuture future = controller.proceedToAsync(TWENTY); future.get(20, TimeUnit.SECONDS); List<String> records = upRecorder.getRecordsAndPurge(); Assert.assertEquals(6, records.size()); String recordA = records.get(0); String recordB = records.get(1); Assert.assertNotSame(recordA, recordB); Assert.assertTrue(recordA.equals(LEVEL_FIVE_1) || recordA.equals(LEVEL_FIVE_2)); Assert.assertTrue(recordB.equals(LEVEL_FIVE_1) || recordB.equals(LEVEL_FIVE_2)); recordA = records.get(2); Assert.assertEquals(LEVEL_TEN_1, recordA); recordA = records.get(3); recordB = records.get(4); Assert.assertNotSame(recordA, recordB); Assert.assertTrue(recordA.equals(LEVEL_FIFTEEN_1) || recordA.equals(LEVEL_FIFTEEN_2)); Assert.assertTrue(recordB.equals(LEVEL_FIFTEEN_1) || recordB.equals(LEVEL_FIFTEEN_2)); recordA = records.get(5); Assert.assertEquals(LEVEL_TWENTY_1, recordA); future = controller.proceedToAsync(TEN); future.get(20, TimeUnit.SECONDS); List<String> recordsDown = downRecorder.getRecordsAndPurge(); Assert.assertNotNull(recordsDown); Assert.assertEquals(3, recordsDown.size()); Assert.assertEquals(records.get(5), recordsDown.get(0)); Assert.assertEquals(records.get(4), recordsDown.get(1)); Assert.assertEquals(records.get(3), recordsDown.get(2)); future = controller.proceedToAsync(FIFTEEN); future.get(20, TimeUnit.SECONDS); records = upRecorder.getRecordsAndPurge(); Assert.assertEquals(2, records.size()); recordA = records.get(0); recordB = records.get(1); Assert.assertNotSame(recordA, recordB); Assert.assertTrue(recordA.equals(LEVEL_FIFTEEN_1) || recordA.equals(LEVEL_FIFTEEN_2)); Assert.assertTrue(recordB.equals(LEVEL_FIFTEEN_1) || recordB.equals(LEVEL_FIFTEEN_2)); future = controller.proceedToAsync(FIVE); future.get(20, TimeUnit.SECONDS); recordsDown = downRecorder.getRecordsAndPurge(); Assert.assertNotNull(recordsDown); Assert.assertEquals(3, recordsDown.size()); future = controller.proceedToAsync(ZERO); future.get(20, TimeUnit.SECONDS); recordsDown = downRecorder.getRecordsAndPurge(); Assert.assertNotNull(recordsDown); Assert.assertEquals(2, recordsDown.size()); }
public void testYoYo() throws ExecutionException, InterruptedException, TimeoutException { ServiceLocator basicLocator = Utilities.getServiceLocator("AsyncRLSTest.basicYoYo", UpRecorder.class, DownRecorder.class, LevelFiveService_1.class, LevelFiveService_2.class, LevelTenService_1.class, LevelFifteenService_1.class, LevelFifteenService_2.class, LevelTwentyService_1.class); UpRecorder upRecorder = basicLocator.getService(UpRecorder.class); Assert.assertNotNull(upRecorder); upRecorder.getRecordsAndPurge(); DownRecorder downRecorder = basicLocator.getService(DownRecorder.class); Assert.assertNotNull(downRecorder); downRecorder.getRecordsAndPurge(); RunLevelController controller = basicLocator.getService(RunLevelController.class); RunLevelFuture future = controller.proceedToAsync(TWENTY); future.get(20, TimeUnit.SECONDS); List<String> records = upRecorder.getRecordsAndPurge(); Assert.assertEquals(6, records.size()); String recordA = records.get(0); String recordB = records.get(1); Assert.assertNotSame(recordA, recordB); Assert.assertTrue(recordA.equals(LEVEL_FIVE_1) || recordA.equals(LEVEL_FIVE_2)); Assert.assertTrue(recordB.equals(LEVEL_FIVE_1) || recordB.equals(LEVEL_FIVE_2)); recordA = records.get(2); Assert.assertEquals(LEVEL_TEN_1, recordA); recordA = records.get(3); recordB = records.get(4); Assert.assertNotSame(recordA, recordB); Assert.assertTrue(recordA.equals(LEVEL_FIFTEEN_1) || recordA.equals(LEVEL_FIFTEEN_2)); Assert.assertTrue(recordB.equals(LEVEL_FIFTEEN_1) || recordB.equals(LEVEL_FIFTEEN_2)); recordA = records.get(5); Assert.assertEquals(LEVEL_TWENTY_1, recordA); future = controller.proceedToAsync(TEN); future.get(20, TimeUnit.SECONDS); List<String> recordsDown = downRecorder.getRecordsAndPurge(); Assert.assertNotNull(recordsDown); Assert.assertEquals(3, recordsDown.size()); Assert.assertEquals(records.get(5), recordsDown.get(0)); if (records.get(4).equals(recordsDown.get(1))) { Assert.assertEquals(records.get(3),recordsDown.get(2)); } else if (records.get(4).equals(recordsDown.get(2))) { Assert.assertEquals(records.get(3), recordsDown.get(1)); } else { Assert.fail("records(4) must be match either " + recordsDown.get(1) + " or " + recordsDown.get(2)); } future = controller.proceedToAsync(FIFTEEN); future.get(20, TimeUnit.SECONDS); records = upRecorder.getRecordsAndPurge(); Assert.assertEquals(2, records.size()); recordA = records.get(0); recordB = records.get(1); Assert.assertNotSame(recordA, recordB); Assert.assertTrue(recordA.equals(LEVEL_FIFTEEN_1) || recordA.equals(LEVEL_FIFTEEN_2)); Assert.assertTrue(recordB.equals(LEVEL_FIFTEEN_1) || recordB.equals(LEVEL_FIFTEEN_2)); future = controller.proceedToAsync(FIVE); future.get(20, TimeUnit.SECONDS); recordsDown = downRecorder.getRecordsAndPurge(); Assert.assertNotNull(recordsDown); Assert.assertEquals(3, recordsDown.size()); future = controller.proceedToAsync(ZERO); future.get(20, TimeUnit.SECONDS); recordsDown = downRecorder.getRecordsAndPurge(); Assert.assertNotNull(recordsDown); Assert.assertEquals(2, recordsDown.size()); }
public ContactEdit() { super(); super.initWidget( p ); FlexTable base = new FlexTable(); base.setWidth("100%"); base.setStyleName("example-ContactEdit"); base.setWidget(0,0, new Label("First Name:") ); base.setWidget(0,1, firstName ); base.setWidget(1,0, new Label("LastName:") ); base.setWidget(1,1, lastName ); base.setWidget(2, 0, new Label("Notes:") ); base.getFlexCellFormatter().setColSpan(2,0, 2); base.setWidget(3, 0, notes ); base.getFlexCellFormatter().setColSpan(3,0, 2 ); p.add( base ); p.add( new Label("Addresses:") ); addressCols[0] = new Field( "type", "Type" ); addressCols[1] = new Field( "address1", "Address" ); addressCols[2] = new Field( "address2", "" ); addressCols[3] = new Field( "city", "City"); addressCols[4] = new Field( "state", "State" ); addressCols[5] = new Field( "zip", "Zip" ); factory.add( StateLookup.class, new BoundWidgetProvider(){ public BoundWidget get() { Label label = new Label(); label.setRenderer( new Renderer(){ public Object render(Object o) { return o == null ? "" : ((StateLookup) o).code; } }); return label; } }); factory.add( TypeLookup.class, new BoundWidgetProvider(){ public BoundWidget get() { TextBox label = new TextBox(); label.setRenderer( new Renderer(){ public Object render(Object o) { return o == null ? "" : ((TypeLookup) o).name; } }); return label; } }); factory.add( String.class, BoundWidgetTypeFactory.LABEL_PROVIDER ); factory.add( Address.class, new BoundWidgetProvider(){ public BoundWidget get() { AddressEdit e = new AddressEdit(); e.setAction( new AddressEditAction() ); return e; } }); addresses = new BoundTable( BoundTable.HEADER_MASK + BoundTable.SORT_MASK + BoundTable.NO_SELECT_CELL_MASK + BoundTable.NO_SELECT_COL_MASK + BoundTable.INSERT_WIDGET_MASK , factory ); addresses.setColumns( addressCols ); addresses.setWidth("500px"); p.add( addresses ); p.add( this.newAddress ); p.add( new Label( "Phone Numbers: ") ); phoneCols[0] = new Column("type", "Type"); phoneCols[1] = new Column("number", "Number" ); BoundWidgetTypeFactory phoneFactory = new BoundWidgetTypeFactory(true); phoneFactory.add( TypeLookup.class, TypeSelectorProvider.INSTANCE ); this.phoneNumbers = new BoundTable( BoundTable.HEADER_MASK + BoundTable.SORT_MASK + BoundTable.NO_SELECT_CELL_MASK + BoundTable.NO_SELECT_COL_MASK, phoneFactory ); phoneNumbers.setColumns( phoneCols ); p.add( this.phoneNumbers ); p.add( this.newPhone ); }
public ContactEdit() { super(); super.initWidget( p ); FlexTable base = new FlexTable(); base.setWidth("100%"); base.setStyleName("example-ContactEdit"); base.setWidget(0,0, new Label("First Name:") ); base.setWidget(0,1, firstName ); base.setWidget(1,0, new Label("LastName:") ); base.setWidget(1,1, lastName ); base.setWidget(2, 0, new Label("Notes:") ); base.getFlexCellFormatter().setColSpan(2,0, 2); base.setWidget(3, 0, notes ); base.getFlexCellFormatter().setColSpan(3,0, 2 ); p.add( base ); p.add( new Label("Addresses:") ); addressCols[0] = new Field( "type", "Type" ); addressCols[1] = new Field( "address1", "Address" ); addressCols[2] = new Field( "address2", "" ); addressCols[3] = new Field( "city", "City"); addressCols[4] = new Field( "state", "State" ); addressCols[5] = new Field( "zip", "Zip" ); factory.add( StateLookup.class, new BoundWidgetProvider(){ public BoundWidget get() { Label label = new Label(); label.setRenderer( new Renderer(){ public Object render(Object o) { return o == null ? "" : ((StateLookup) o).code; } }); return label; } }); factory.add( TypeLookup.class, new BoundWidgetProvider(){ public BoundWidget get() { TextBox label = new TextBox(); label.setRenderer( new Renderer(){ public Object render(Object o) { return o == null ? "" : ((TypeLookup) o).name; } }); return label; } }); factory.add( String.class, BoundWidgetTypeFactory.LABEL_PROVIDER ); factory.add( Address.class, new BoundWidgetProvider(){ public BoundWidget get() { AddressEdit e = new AddressEdit(); e.setAction( new AddressEditAction() ); return e; } }); addresses = new BoundTable( BoundTable.HEADER_MASK + BoundTable.SORT_MASK + BoundTable.NO_SELECT_CELL_MASK + BoundTable.NO_SELECT_COL_MASK + BoundTable.INSERT_WIDGET_MASK , factory ); addresses.setColumns( addressCols ); addresses.setWidth("500px"); p.add( addresses ); p.add( this.newAddress ); p.add( new Label( "Phone Numbers: ") ); phoneCols[0] = new Field("type", "Type"); phoneCols[1] = new Field("number", "Number" ); BoundWidgetTypeFactory phoneFactory = new BoundWidgetTypeFactory(true); phoneFactory.add( TypeLookup.class, TypeSelectorProvider.INSTANCE ); this.phoneNumbers = new BoundTable( BoundTable.HEADER_MASK + BoundTable.SORT_MASK + BoundTable.NO_SELECT_CELL_MASK + BoundTable.NO_SELECT_COL_MASK, phoneFactory ); phoneNumbers.setColumns( phoneCols ); p.add( this.phoneNumbers ); p.add( this.newPhone ); }
private void initPd() { Resources res = act.getResources(); File patch = null; try { PdBase.subscribe("android"); patch = registerResource(R.raw.main, PD, res); registerResource(R.raw.grain, PD, res); registerResource(R.raw.grainvoice, PD, res); registerResource(R.raw.simplereverb, PD, res); registerResource(R.raw.velocity_synth, PD, res); registerResource(R.raw.velocity_synth1, PD, res); registerResource(R.raw.velocity_synth2, PD, res); registerSoundResource(R.raw.vowels, res); registerSoundResource(R.raw.violin, res); registerSoundResource(R.raw.guitar, res); registerSoundResource(R.raw.menchoir, res); registerSoundResource(R.raw.icke, res); PdBase.openPatch(patch); String name = res.getString(R.string.app_name); pdService.initAudio(-1, -1, -1, -1); pdService.startAudio(new Intent(act, ZenBoxActivity.class), R.drawable.icon, name, name); } catch (IOException e) { Log.e(TAG, e.toString()); } }
private void initPd() { Resources res = act.getResources(); File patch = null; try { PdBase.subscribe("android"); patch = registerResource(R.raw.main, PD, res); registerResource(R.raw.grain, PD, res); registerResource(R.raw.grainvoice, PD, res); registerResource(R.raw.simplereverb, PD, res); registerResource(R.raw.velocity_synth, PD, res); registerResource(R.raw.velocity_synth1, PD, res); registerResource(R.raw.velocity_synth2, PD, res); registerSoundResource(R.raw.vowels, res); registerSoundResource(R.raw.violin, res); registerSoundResource(R.raw.guitar, res); registerSoundResource(R.raw.menchoir, res); registerSoundResource(R.raw.icke, res); PdBase.openPatch(patch); String name = res.getString(R.string.app_name); pdService.initAudio(-1, -1, -1, -1); sendSetFileName(samples.get(0)); pdService.startAudio(new Intent(act, ZenBoxActivity.class), R.drawable.icon, name, name); } catch (IOException e) { Log.e(TAG, e.toString()); } }
void initPaints(Context ctx) { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); int opacity = sharedPrefs.getInt("small_widget_opacity", 80); opacity = (255 * opacity) / 100; m_paintBackground.setStyle(Paint.Style.FILL); m_paintBackground.setColor(Color.BLACK); m_paintBackground.setStrokeWidth(STROKE_WIDTH); m_paintBackground.setAlpha(opacity); m_paint[0] = new Paint(); m_paint[0].setStyle(Paint.Style.FILL); m_paint[0].setColor(Color.BLUE); m_paint[0].setStrokeWidth(STROKE_WIDTH); m_paint[0].setAlpha(opacity); m_paint[1] = new Paint(); m_paint[1].setStyle(Paint.Style.FILL); m_paint[1].setColor(Color.YELLOW); m_paint[1].setStrokeWidth(STROKE_WIDTH); m_paint[1].setAlpha(opacity); m_paint[2] = new Paint(); m_paint[2].setStyle(Paint.Style.FILL); m_paint[2].setColor(Color.GREEN); m_paint[2].setStrokeWidth(STROKE_WIDTH); m_paint[2].setAlpha(opacity); m_paint[3] = new Paint(); m_paint[3].setStyle(Paint.Style.FILL); m_paint[3].setColor(Color.RED); m_paint[3].setStrokeWidth(STROKE_WIDTH); m_paint[3].setAlpha(opacity); m_paint[4] = new Paint(); m_paint[4].setStyle(Paint.Style.FILL); m_paint[4].setColor(Color.MAGENTA); m_paint[4].setStrokeWidth(STROKE_WIDTH); m_paint[4].setAlpha(opacity); m_paint[5] = new Paint(); m_paint[5].setStyle(Paint.Style.FILL); m_paint[5].setColor(Color.CYAN); m_paint[5].setStrokeWidth(STROKE_WIDTH); m_paint[5].setAlpha(opacity); }
void initPaints(Context ctx) { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); int opacity = sharedPrefs.getInt("small_widget_opacity", 80); opacity = (255 * opacity) / 100; m_paintBackground.setStyle(Paint.Style.FILL); m_paintBackground.setColor(Color.BLACK); m_paintBackground.setStrokeWidth(STROKE_WIDTH); m_paintBackground.setAlpha(opacity); m_paint[0] = new Paint(); m_paint[0].setStyle(Paint.Style.FILL); m_paint[0].setColor(Color.BLUE); m_paint[0].setStrokeWidth(STROKE_WIDTH); m_paint[0].setAlpha(opacity); m_paint[1] = new Paint(); m_paint[1].setStyle(Paint.Style.FILL); m_paint[1].setColor(Color.GREEN); m_paint[1].setStrokeWidth(STROKE_WIDTH); m_paint[1].setAlpha(opacity); m_paint[2] = new Paint(); m_paint[2].setStyle(Paint.Style.FILL); m_paint[2].setColor(Color.YELLOW); m_paint[2].setStrokeWidth(STROKE_WIDTH); m_paint[2].setAlpha(opacity); m_paint[3] = new Paint(); m_paint[3].setStyle(Paint.Style.FILL); m_paint[3].setColor(Color.WHITE); m_paint[3].setStrokeWidth(STROKE_WIDTH); m_paint[3].setAlpha(opacity); m_paint[4] = new Paint(); m_paint[4].setStyle(Paint.Style.FILL); m_paint[4].setColor(Color.MAGENTA); m_paint[4].setStrokeWidth(STROKE_WIDTH); m_paint[4].setAlpha(opacity); m_paint[5] = new Paint(); m_paint[5].setStyle(Paint.Style.FILL); m_paint[5].setColor(Color.CYAN); m_paint[5].setStrokeWidth(STROKE_WIDTH); m_paint[5].setAlpha(opacity); }
public Identifier(FilePosition pos, String name) { super(pos); if (!(name == null || "".equals(name) || ParserBase.isQuasiIdentifier(name))) { throw new IllegalArgumentException("Invalid identifier " + name); } this.name = name; }
public Identifier(FilePosition pos, String name) { super(pos); if (!(name == null || "".equals(name) || ParserBase.isQuasiIdentifier(name)) || (name != null && name.length() > 1024)) { throw new IllegalArgumentException("Invalid identifier " + name); } this.name = name; }
public void testRedirect() throws Exception { Component clientComponent = new Component(); Component proxyComponent = new Component(); Component originComponent = new Component(); clientComponent.getClients().add(Protocol.HTTP); proxyComponent.getClients().add(Protocol.HTTP); String target = "http://localhost:9090{rr}"; Redirector proxy = new Redirector(proxyComponent.getContext(), target, Redirector.MODE_DISPATCHER); Restlet trace = new Restlet(originComponent.getContext()) { public void handle(Request request, Response response) { String message = "Resource URI: " + request.getResourceRef() + '\n' + "Base URI: " + request.getResourceRef().getBaseRef() + '\n' + "Remaining part: " + request.getResourceRef().getRemainingPart() + '\n' + "Method name: " + request.getMethod() + '\n'; response.setEntity(new StringRepresentation(message, MediaType.TEXT_PLAIN)); } }; proxyComponent.getDefaultHost().attach("", proxy); originComponent.getDefaultHost().attach("", trace); proxyComponent.getServers().add(Protocol.HTTP, 8182); originComponent.getServers().add(Protocol.HTTP, 9090); originComponent.start(); proxyComponent.start(); clientComponent.start(); Context context = clientComponent.getContext(); String uri = "http://localhost:8080/?foo=bar"; testCall(context, Method.GET, uri); testCall(context, Method.DELETE, uri); uri = "http://localhost:8080/abcd/efgh/ijkl?foo=bar&foo=beer"; testCall(context, Method.GET, uri); testCall(context, Method.DELETE, uri); uri = "http://localhost:8080/v1/client/kwse/CnJlNUQV9%252BNNqbUf7Lhs2BYEK2Y%253D/user/johnm/uVGYTDK4kK4zsu96VHGeTCzfwso%253D/"; testCall(context, Method.GET, uri); clientComponent.stop(); originComponent.stop(); proxyComponent.stop(); }
public void testRedirect() throws Exception { Component clientComponent = new Component(); Component proxyComponent = new Component(); Component originComponent = new Component(); clientComponent.getClients().add(Protocol.HTTP); proxyComponent.getClients().add(Protocol.HTTP); String target = "http://localhost:9090{rr}"; Redirector proxy = new Redirector(proxyComponent.getContext(), target, Redirector.MODE_DISPATCHER); Restlet trace = new Restlet(originComponent.getContext()) { public void handle(Request request, Response response) { String message = "Resource URI: " + request.getResourceRef() + '\n' + "Base URI: " + request.getResourceRef().getBaseRef() + '\n' + "Remaining part: " + request.getResourceRef().getRemainingPart() + '\n' + "Method name: " + request.getMethod() + '\n'; response.setEntity(new StringRepresentation(message, MediaType.TEXT_PLAIN)); } }; proxyComponent.getDefaultHost().attach("", proxy); originComponent.getDefaultHost().attach("", trace); proxyComponent.getServers().add(Protocol.HTTP, 8182); originComponent.getServers().add(Protocol.HTTP, 9090); originComponent.start(); proxyComponent.start(); clientComponent.start(); Context context = clientComponent.getContext(); String uri = "http://localhost:8182/?foo=bar"; testCall(context, Method.GET, uri); testCall(context, Method.DELETE, uri); uri = "http://localhost:8182/abcd/efgh/ijkl?foo=bar&foo=beer"; testCall(context, Method.GET, uri); testCall(context, Method.DELETE, uri); uri = "http://localhost:8182/v1/client/kwse/CnJlNUQV9%252BNNqbUf7Lhs2BYEK2Y%253D/user/johnm/uVGYTDK4kK4zsu96VHGeTCzfwso%253D/"; testCall(context, Method.GET, uri); clientComponent.stop(); originComponent.stop(); proxyComponent.stop(); }
public void commandAction(Command c, Displayable d) { updateLastUserActionTime(); try { if((keyboardLocked) && (d != null)) { keyPressed(0); return; } if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD]) || (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD]) || (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD]) || (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) { int panX = 0; int panY = 0; int courseDiff = 0; int backLightLevelDiff = 0; if (c == CMDS[PAN_LEFT25_CMD]) { panX = -25; } else if (c == CMDS[PAN_RIGHT25_CMD]) { panX = 25; } else if (c == CMDS[PAN_UP25_CMD]) { panY = -25; } else if (c == CMDS[PAN_DOWN25_CMD]) { panY = 25; } else if (c == CMDS[PAN_LEFT2_CMD]) { if (TrackPlayer.isPlaying) { TrackPlayer.slower(); } else if (manualRotationMode) { courseDiff=-5; } else { panX = -2; } backLightLevelDiff = -25; } else if (c == CMDS[PAN_RIGHT2_CMD]) { if (TrackPlayer.isPlaying) { TrackPlayer.faster(); } else if (manualRotationMode) { courseDiff=5; } else { panX = 2; } backLightLevelDiff = 25; } else if (c == CMDS[PAN_UP2_CMD]) { if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) { RouteInstructions.toNextInstruction(1); } else { panY = -2; } } else if (c == CMDS[PAN_DOWN2_CMD]) { if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) { RouteInstructions.toNextInstruction(-1); } else { panY = 2; } } if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) { Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false); lastBackLightOnTime = System.currentTimeMillis(); Configuration.addToBackLightLevel(backLightLevelDiff); parent.showBackLightLevel(); } else if (imageCollector != null) { if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) { if (compassDeviation == 360) { compassDeviation = 0; } else { compassDeviation += courseDiff; compassDeviation %= 360; if (course < 0) { course += 360; } } } else { if (courseDiff == 360) { course = 0; } else { course += courseDiff; course %= 360; if (course < 0) { course += 360; } } if (panX != 0 || panY != 0) { gpsRecenter = false; } } imageCollector.getCurrentProjection().pan(center, panX, panY); } gpsRecenter = false; return; } if (c == CMDS[EXIT_CMD]) { if (Legend.isValid && gpx.isRecordingTrk()) { alert(Locale.get("trace.RecordMode"), Locale.get("trace.PleaseStopRecording") , 2500); return; } if (Legend.isValid) { pause(); } parent.exit(); return; } if (c == CMDS[START_RECORD_CMD]) { try { gpx.newTrk(false); alert(Locale.get("trace.GpsRecording"), Locale.get("trace.StartingToRecord"), 1250); } catch (RuntimeException e) { receiveMessage(e.getMessage()); } recordingsMenu = null; return; } if (c == CMDS[STOP_RECORD_CMD]) { gpx.saveTrk(false); alert(Locale.get("trace.GpsRecording"), Locale.get("trace.StoppingToRecord"), 1250); recordingsMenu = null; return; } if (c == CMDS[MANAGE_TRACKS_CMD]) { if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) { alert(Locale.get("trace.RecordMode"), Locale.get("trace.YouNeedStopRecording") , 4000); return; } GuiGpx guiGpx = new GuiGpx(this); guiGpx.show(); return; } if (c == CMDS[REFRESH_CMD]) { repaint(); return; } if (c == CMDS[CONNECT_GPS_CMD]) { if (locationProducer == null) { if (TrackPlayer.isPlaying) { TrackPlayer.getInstance().stop(); alert(Locale.get("trace.Trackplayer"), Locale.get("trace.PlayingStopped"), 2500); } Thread thread = new Thread(this,"LocationProducer init"); thread.start(); } return; } if (c == CMDS[DISCONNECT_GPS_CMD]) { if (locationProducer != null) { locationProducer.close(); } return; } if (c == CMDS[TOGGLE_GPS_CMD]) { if (isGpsConnected()) { commandAction(DISCONNECT_GPS_CMD); } else { commandAction(CONNECT_GPS_CMD); } return; } if (c == CMDS[SEARCH_CMD]) { GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT); guiSearch.show(); return; } if (c == CMDS[ENTER_WAYP_CMD]) { if (gpx.isLoadingWaypoints()) { showAlertLoadingWpt(); } else { GuiWaypointEnter gwpe = new GuiWaypointEnter(this); gwpe.show(); } return; } if (c == CMDS[MANAGE_WAYP_CMD]) { if (gpx.isLoadingWaypoints()) { showAlertLoadingWpt(); } else { GuiWaypoint gwp = new GuiWaypoint(this); gwp.show(); } return; } if (c == CMDS[MAPFEATURES_CMD]) { GuiMapFeatures gmf = new GuiMapFeatures(this); gmf.show(); repaint(); return; } if (c == CMDS[OVERVIEW_MAP_CMD]) { GuiOverviewElements ovEl = new GuiOverviewElements(this); ovEl.show(); repaint(); return; } if (c == CMDS[SEND_MESSAGE_CMD]) { GuiSendMessage sendMsg = new GuiSendMessage(this); sendMsg.show(); repaint(); return; } if (c == CMDS[RECORDINGS_CMD]) { if (recordingsMenu == null) { boolean hasJSR120 = Configuration.hasDeviceJSR120(); int noElements = 5; noElements += 2; if (hasJSR120) { noElements++; } int idx = 0; String[] elements; if (gpx.isRecordingTrk()) { noElements++; elements = new String[noElements]; recordingsMenuCmds = new int[noElements]; recordingsMenuCmds[idx] = STOP_RECORD_CMD; elements[idx++] = Locale.get("trace.StopGpxTracklog"); if (gpx.isRecordingTrkSuspended()) { recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD; elements[idx++] = Locale.get("trace.ResumeRecording"); } else { recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD; elements[idx++] = Locale.get("trace.SuspendRecording"); } } else { elements = new String[noElements]; recordingsMenuCmds = new int[noElements]; recordingsMenuCmds[idx] = START_RECORD_CMD; elements[idx++] = Locale.get("trace.StartGpxTracklog"); } recordingsMenuCmds[idx] = SAVE_WAYP_CMD; elements[idx++] = Locale.get("trace.SaveWaypoint"); recordingsMenuCmds[idx] = ENTER_WAYP_CMD; elements[idx++] = Locale.get("trace.EnterWaypoint"); recordingsMenuCmds[idx] = MANAGE_TRACKS_CMD; elements[idx++] = Locale.get("trace.ManageTracks"); recordingsMenuCmds[idx] = MANAGE_WAYP_CMD; elements[idx++] = Locale.get("trace.ManageWaypoints"); recordingsMenuCmds[idx] = CAMERA_CMD; elements[idx++] = Locale.get("trace.TakePictures"); if (audioRec.isRecording()) { recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC; elements[idx++] = Locale.get("trace.StopAudioRecording"); } else { recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC; elements[idx++] = Locale.get("trace.StartAudioRecording"); } if (hasJSR120) { recordingsMenuCmds[idx] = SEND_MESSAGE_CMD; elements[idx++] = Locale.get("trace.SendSMSMapPos"); } recordingsMenu = new List(Locale.get("trace.Recordings"), Choice.IMPLICIT, elements, null); recordingsMenu.addCommand(CMDS[OK_CMD]); recordingsMenu.addCommand(CMDS[BACK_CMD]); recordingsMenu.setSelectCommand(CMDS[OK_CMD]); parent.show(recordingsMenu); recordingsMenu.setCommandListener(this); } if (recordingsMenu != null) { recordingsMenu.setSelectedIndex(0, true); parent.show(recordingsMenu); } return; } if (c == CMDS[ROUTINGS_CMD]) { if (routingsMenu == null) { String[] elements = new String[4]; if (routeCalc || route != null) { elements[0] = Locale.get("trace.StopRouting"); } else { elements[0] = Locale.get("trace.CalculateRoute"); } elements[1] = Locale.get("trace.SetDestination"); elements[2] = Locale.get("trace.ShowDestination"); elements[3] = Locale.get("trace.ClearDestination"); routingsMenu = new List(Locale.get("trace.Routing2"), Choice.IMPLICIT, elements, null); routingsMenu.addCommand(CMDS[OK_CMD]); routingsMenu.addCommand(CMDS[BACK_CMD]); routingsMenu.setSelectCommand(CMDS[OK_CMD]); routingsMenu.setCommandListener(this); } if (routingsMenu != null) { routingsMenu.setSelectedIndex(0, true); parent.show(routingsMenu); } return; } if (c == CMDS[SAVE_WAYP_CMD]) { if (gpx.isLoadingWaypoints()) { showAlertLoadingWpt(); } else { PositionMark posMark = null; if (gpsRecenter) { posMark = new PositionMark(center.radlat, center.radlon, (int)pos.altitude, pos.timeMillis, (byte)-1, (byte)-1, (byte)-1, (byte)-1); } else { posMark = new PositionMark(center.radlat, center.radlon, PositionMark.INVALID_ELEVATION, pos.timeMillis, (byte)-1, (byte)-1, (byte)-1, (byte)-1); } showGuiWaypointSave(posMark); } return; } if (c == CMDS[ONLINE_INFO_CMD]) { Position oPos = new Position(center.radlat, center.radlon, 0.0f, 0.0f, 0.0f, 0, 0); GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc); gWeb.show(); alert(Locale.get("trace.NoOnlineCapa"), Locale.get("trace.SetAppGeneric") + Locale.get("trace.PropertiesFile"), Alert.FOREVER); } if (c == CMDS[BACK_CMD]) { show(); return; } if (c == CMDS[OK_CMD]) { if (d == recordingsMenu) { int recCmd = recordingsMenu.getSelectedIndex(); if (recCmd >= 0 && recCmd < recordingsMenuCmds.length) { recCmd = recordingsMenuCmds[recCmd]; if (recCmd == STOP_RECORD_CMD) { commandAction(STOP_RECORD_CMD); if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) { show(); } } else if (recCmd == START_RECORD_CMD) { commandAction(START_RECORD_CMD); if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) { show(); } } else if (recCmd == TOGGLE_RECORDING_SUSP_CMD) { commandAction(TOGGLE_RECORDING_SUSP_CMD); show(); } else { commandAction(recCmd); } } } else if (d == routingsMenu) { show(); switch (routingsMenu.getSelectedIndex()) { case 0: { if (routeCalc || route != null) { commandAction(ROUTING_STOP_CMD); } else { commandAction(ROUTING_START_WITH_MODE_SELECT_CMD); } break; } case 1: { commandAction(SET_DEST_CMD); break; } case 2: { commandAction(SHOW_DEST_CMD); break; } case 3: { commandAction(CLEAR_DEST_CMD); break; } } } return; } if (c == CMDS[CAMERA_CMD]) { try { Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera"); Object GuiCameraObject = GuiCameraClass.newInstance(); GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject; cam.init(this); cam.show(); } catch (ClassNotFoundException cnfe) { logger.exception(Locale.get("trace.YourPhoneNoCamSupport"), cnfe); } return; } if (c == CMDS[TOGGLE_AUDIO_REC]) { if (audioRec.isRecording()) { audioRec.stopRecord(); } else { audioRec.startRecorder(); } recordingsMenu = null; return; } if (c == CMDS[ROUTING_TOGGLE_CMD]) { if (routeCalc || route != null) { commandAction(ROUTING_STOP_CMD); } else { commandAction(ROUTING_START_WITH_MODE_SELECT_CMD); } return; } if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) { gpsRecenter = true; gpsRecenterInvalid = true; gpsRecenterStale = true; GuiRoute guiRoute = new GuiRoute(this, false); if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) { commandAction(ROUTING_START_CMD); } else { guiRoute.show(); } return; } if (c == CMDS[ROUTING_START_CMD]) { if (! routeCalc || RouteLineProducer.isRunning()) { routeCalc = true; if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) { stopImageCollector(); } RouteInstructions.resetOffRoute(route, center); RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon); logger.info("Routing source: " + routeSource); routeNodes=new Vector(); routeEngine = new Routing(this); routeEngine.solve(routeSource, dest); } routingsMenu = null; return; } if (c == CMDS[ROUTING_STOP_CMD]) { NoiseMaker.stopPlayer(); if (routeCalc) { if (routeEngine != null) { routeEngine.cancelRouting(); } alert(Locale.get("trace.RouteCalculation"), Locale.get("trace.Cancelled"), 1500); } else { alert(Locale.get("trace.Routing"), Locale.get("generic.Off"), 750); } endRouting(); routingsMenu = null; synchronized (this) { if (imageCollector != null) { imageCollector.newDataReady(); } } routingsMenu = null; return; } if (c == CMDS[ZOOM_IN_CMD]) { scale = scale / 1.5f; autoZoomed = false; return; } if (c == CMDS[ZOOM_OUT_CMD]) { scale = scale * 1.5f; autoZoomed = false; return; } if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) { manualRotationMode = !manualRotationMode; if (manualRotationMode) { if (hasPointerEvents()) { alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ChangeCourse"), 3000); } else { alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ChangeCourseWithLeftRightKeys"), 3000); } } else { alert(Locale.get("trace.ManualRotation"), Locale.get("generic.Off"), 750); } return; } if (c == CMDS[TOGGLE_OVERLAY_CMD]) { showAddons++; repaint(); return; } if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) { Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, !(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)), false); lastBackLightOnTime = System.currentTimeMillis(); parent.showBackLightLevel(); return; } if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) { boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN); Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false); setFullScreenMode(fullScreen); return; } if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) { if (manualRotationMode) { if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) { compassDeviation = 0; } else { course = 0; } alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750); } else { alert(Locale.get("guidiscover.MapProjection"), ProjFactory.nextProj(), 750); } synchronized (this) { if (imageCollector != null) { imageCollector.newDataReady(); } } return; } if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) { keyboardLocked = !keyboardLocked; if (keyboardLocked) { keyPressed(0); } else { alert(Locale.get("trace.GpsMid"), hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked") : Locale.get("trace.KeysUnlocked"), 1000); } return; } if (c == CMDS[TOGGLE_RECORDING_CMD]) { if ( gpx.isRecordingTrk() ) { commandAction(STOP_RECORD_CMD); } else { commandAction(START_RECORD_CMD); } return; } if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) { if (gpx.isRecordingTrk()) { if ( gpx.isRecordingTrkSuspended() ) { alert(Locale.get("trace.GpsRecording"), Locale.get("trace.ResumingRecording"), 1000); gpx.resumeTrk(); } else { alert(Locale.get("trace.GpsRecording"), Locale.get("trace.SuspendingRecording"), 1000); gpx.suspendTrk(); } } recordingsMenu = null; return; } if (c == CMDS[RECENTER_GPS_CMD]) { gpsRecenter = true; gpsRecenterInvalid = true; gpsRecenterStale = true; autoZoomed = true; if (pos.latitude != 0.0f) { receivePosition(pos); } newDataReady(); return; } if (c == CMDS[SHOW_DEST_CMD]) { if (dest != null) { gpsRecenter = false; prevPositionNode = center.copy(); center.setLatLonRad(dest.lat, dest.lon); movedAwayFromDest = false; updatePosition(); } else { alert(Locale.get("trace.ShowDestination"), Locale.get("trace.DestinationNotSpecifiedYet"), 3000); } return; } if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) { if (prevPositionNode != null) { gpsRecenter = false; center.setLatLon(prevPositionNode); updatePosition(); } } if (c == CMDS[DATASCREEN_CMD]) { showNextDataScreen(DATASCREEN_NONE); return; } if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) { showIconMenu(); return; } if (c == CMDS[SETUP_CMD]) { new GuiDiscover(parent); return; } if (c == CMDS[ABOUT_CMD]) { new Splash(parent, GpsMid.initDone); return; } if (c == CMDS[CELLID_LOCATION_CMD]) { if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) { locationProducer.triggerPositionUpdate(); newDataReady(); } else { if (cellIDLocationProducer == null) { cellIDLocationProducer = new SECellId(); if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) { logger.info("Failed to initialise CellID location producer"); } } if (cellIDLocationProducer != null) { cellIDLocationProducer.triggerPositionUpdate(); newDataReady(); } } return; } if (c == CMDS[MANUAL_LOCATION_CMD]) { Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD, center.radlon / MoreMath.FAC_DECTORAD, PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1, System.currentTimeMillis(), Position.TYPE_MANUAL); gpsRecenter = true; autoZoomed = true; receivePosition(setpos); receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0); newDataReady(); return; } if (! routeCalc) { if (c == CMDS[RETRIEVE_XML]) { if (Legend.enableEdits) { if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) { parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER); } if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) { EditableWay eway = (EditableWay)pc.actualWay; GuiOsmWayDisplay guiWay = new GuiOsmWayDisplay(eway, pc.actualSingleTile, this); guiWay.show(); guiWay.refresh(); } } else { parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER); } } if (c == CMDS[EDIT_ENTITY]) { if (Legend.enableEdits) { GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY); guiSearch.show(); return; } else { parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER); } } if (c == CMDS[RETRIEVE_NODE]) { if (Legend.enableEdits) { GuiOsmPoiDisplay guiNode = new GuiOsmPoiDisplay(-1, null, center.radlat, center.radlon, this); guiNode.show(); guiNode.refresh(); } else { logger.error(Locale.get("trace.EditingIsNotEnabled")); } } if (c == CMDS[EDIT_ADDR_CMD]) { if (Legend.enableEdits) { String streetName = ""; if ((pc != null) && (pc.actualWay != null)) { streetName = getName(pc.actualWay.nameIdx); } GuiOsmAddrDisplay guiAddr = new GuiOsmAddrDisplay(-1, streetName, null, center.radlat, center.radlon, this); guiAddr.show(); } else { logger.error(Locale.get("trace.EditingIsNotEnabled")); } } if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) { alert("No online capabilites", Locale.get("trace.SetAppGeneric") + Locale.get("trace.PropertiesFile"), Alert.FOREVER); } if (c == CMDS[SET_DEST_CMD]) { RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon); setDestination(pm1); return; } if (c == CMDS[CLEAR_DEST_CMD]) { setDestination(null); return; } } else { alert(Locale.get("trace.Error"), Locale.get("trace.CurrentlyInRouteCalculation"), 2000); } } catch (Exception e) { logger.exception(Locale.get("trace.InTraceCommandAction"), e); } } private void startImageCollector() throws Exception { logger.info("Starting ImageCollector"); Images images = new Images(); pc = new PaintContext(this, images); imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images); pc.center = center.copy(); pc.scale = scale; pc.xSize = this.getWidth(); pc.ySize = this.getHeight(); } private void stopImageCollector(){ logger.info("Stopping ImageCollector"); cleanup(); if (imageCollector != null ) { imageCollector.stop(); imageCollector=null; } System.gc(); } public void startup() throws Exception { namesThread = new Names(); urlsThread = new Urls(); new DictReader(this); if (Legend.isValid) { while (!baseTilesRead) { try { Thread.sleep(250); } catch (InterruptedException e1) { } } } if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) { Thread thread = new Thread(this, "Trace"); thread.start(); } tileReader = new QueueDataReader(this); dictReader = new QueueDictReader(this); this.gpx = new Gpx(); this.audioRec = new AudioRecorder(); setDict(gpx, (byte)5); startImageCollector(); recreateTraceLayout(); } public void shutdown() { if (gpx != null) { gpx.saveTrk(true); } logger.debug("Shutdown: stopImageCollector"); stopImageCollector(); if (namesThread != null) { logger.debug("Shutdown: namesThread"); namesThread.stop(); namesThread = null; } if (urlsThread != null) { urlsThread.stop(); urlsThread = null; } if (dictReader != null) { logger.debug("Shutdown: dictReader"); dictReader.shutdown(); dictReader = null; } if (tileReader != null) { logger.debug("Shutdown: tileReader"); tileReader.shutdown(); tileReader = null; } if (locationProducer != null) { logger.debug("Shutdown: locationProducer"); locationProducer.close(); } if (TrackPlayer.isPlaying) { logger.debug("Shutdown: TrackPlayer"); TrackPlayer.getInstance().stop(); } } public void sizeChanged(int w, int h) { updateLastUserActionTime(); if (imageCollector != null) { logger.info("Size of Canvas changed to " + w + "|" + h); stopImageCollector(); try { startImageCollector(); imageCollector.resume(); imageCollector.newDataReady(); } catch (Exception e) { logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector"), e); } updatePosition(); } tl = new TraceLayout(0, 0, w, h); } protected void paint(Graphics g) { logger.debug("Drawing Map screen"); try { int yc = 1; int la = 18; getPC(); g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]); g.fillRect(0, 0, this.getWidth(), this.getHeight()); pc.g = g; if (imageCollector != null) { Node drawnCenter = imageCollector.paint(pc); if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null) { pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2); int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2); if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs && Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs ) { ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan); } } } else { tl.ele[TraceLayout.WAYNAME].setText(" "); } if (dest != null) { float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon); atDest = (distance < 25); if (atDest) { if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) { GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1); } } else if (!movedAwayFromDest) { movedAwayFromDest = true; } } speeding = false; int maxSpeed = 0; if (gpsRecenter && actualSpeedLimitWay != null) { maxSpeed = actualSpeedLimitWay.getMaxSpeed(); if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER) && (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) { maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter(); } if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) { speeding = true; } } if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) { if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) { lastTimeOfSpeedingSound = System.currentTimeMillis(); GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound()); } } g.setColor(Legend.COLOR_MAP_TEXT); switch (showAddons) { case 1: yc = showMemory(g, yc, la); break; case 2: yc = showConnectStatistics(g, yc, la); break; default: showAddons = 0; if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) { if (pc != null) { tl.calcScaleBarWidth(pc); tl.ele[TraceLayout.SCALEBAR].setText(" "); } } setPointOfTheCompass(); } showMovement(g); LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION]; LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT]; if (gpx.isRecordingTrk()) { if (gpx.isRecordingTrkSuspended()) { eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); } else { eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); } eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")); } if (TrackPlayer.isPlaying) { eSolution.setText(Locale.get("trace.Replay")); } else { if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID || solution == LocationMsgReceiver.STATUS_MANUAL)) { eSolution.setText(Locale.get("solution.Off")); } else { eSolution.setText(solutionStr); } } LayoutElement e = tl.ele[TraceLayout.CELLID]; if (SECellLocLogger.isCellIDLogging() > 0) { if (SECellLocLogger.isCellIDLogging() == 2) { e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); } else { e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); } e.setText(Locale.get("trace.cellIDs")); } e = tl.ele[TraceLayout.AUDIOREC]; if (audioRec.isRecording()) { e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); e.setText(Locale.get("trace.AudioRec")); } if (pc != null) { showDestination(pc); } if (speed > 0 && Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) { if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) { tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")); } else { tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph")); } } if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP) && locationProducer != null && LocationMsgReceiverList.isPosValid(solution) ) { tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE)); } if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) ) && Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) { e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE]; e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]); double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon); e.setText(Locale.get("trace.Air") + showDistance((int) distLine, DISTANCE_AIR)); } if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) { e = tl.ele[TraceLayout.CURRENT_TIME]; e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true)); tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e); } setSpeedingSign(maxSpeed); if (hasPointerEvents()) { tl.ele[TraceLayout.ZOOM_IN].setText("+"); tl.ele[TraceLayout.ZOOM_OUT].setText("-"); tl.ele[TraceLayout.RECENTER_GPS].setText("|"); e = tl.ele[TraceLayout.SHOW_DEST]; if (atDest && prevPositionNode != null) { e.setText("<"); e.setActionID(SHOW_PREVIOUS_POSITION_CMD); } else { e.setText(">"); e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) ); } tl.ele[TraceLayout.RECORDINGS].setText("*"); tl.ele[TraceLayout.SEARCH].setText("_"); } e = tl.ele[TraceLayout.TITLEBAR]; if (currentTitleMsgOpenCount != 0) { e.setText(currentTitleMsg); synchronized (this) { if (setTitleMsgTimeout != 0) { TimerTask timerT = new TimerTask() { public synchronized void run() { currentTitleMsgOpenCount--; lastTitleMsg = currentTitleMsg; if (currentTitleMsgOpenCount == 0) { logger.debug("clearing title"); repaint(); } } }; GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout); setTitleMsgTimeout = 0; } } } tl.paint(g); if (currentAlertsOpenCount > 0) { showCurrentAlert(g); } } catch (Exception e) { logger.silentexception("Unhandled exception in the paint code", e); } } public void showGuiWaypointSave(PositionMark posMark) { if (guiWaypointSave == null) { guiWaypointSave = new GuiWaypointSave(this); } if (guiWaypointSave != null) { guiWaypointSave.setData(posMark); guiWaypointSave.show(); } } private void showAlertLoadingWpt() { alert("Way points", "Way points are not ready yet.", 3000); } private void showCurrentAlert(Graphics g) { Font font = g.getFont(); Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize()); int fontHeight = font.getHeight(); int y = titleFont.getHeight() + 2 + fontHeight; int extraWidth = font.charWidth('W'); int alertWidth = titleFont.stringWidth(currentAlertTitle); int maxWidth = getWidth() - extraWidth; for (int i = 0; i <= 1; i++) { int nextSpaceAt = 0; int prevSpaceAt = 0; int start = 0; do { int width = 0; while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) { prevSpaceAt = nextSpaceAt; nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt); if (nextSpaceAt == -1) { nextSpaceAt = currentAlertMessage.length(); } width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start); nextSpaceAt++; } nextSpaceAt--; while (width > maxWidth) { if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) { nextSpaceAt = prevSpaceAt; } else { nextSpaceAt--; } width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start); } if (alertWidth < width ) { alertWidth = width; } if (i==1) { g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start, getWidth()/2, y, Graphics.TOP|Graphics.HCENTER); } y += fontHeight; start = nextSpaceAt; } while (nextSpaceAt < currentAlertMessage.length() ); if (i == 0) { alertWidth += extraWidth; int alertHeight = y; int alertTop = (getHeight() - alertHeight) /2; int alertLeft = (getWidth() - alertWidth) / 2; g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]); g.fillRect(alertLeft, alertTop, alertWidth, alertHeight); g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]); g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3); g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]); g.setStrokeStyle(Graphics.SOLID); g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); y = alertTop + 2; g.setFont(titleFont); g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]); g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER); g.setFont(font); y += (fontHeight * 3 / 2); } } synchronized (this) { if (setAlertTimeout != 0) { TimerTask timerT = new TimerTask() { public synchronized void run() { currentAlertsOpenCount--; if (currentAlertsOpenCount == 0) { logger.debug("clearing alert"); repaint(); } } }; GpsMid.getTimer().schedule(timerT, setAlertTimeout); setAlertTimeout = 0; } } } private void setSpeedingSign(int maxSpeed) { if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL) && ( speeding || (System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000 ) ) { if (speeding) { speedingSpeedLimit = maxSpeed; startTimeOfSpeedingSign = System.currentTimeMillis(); } if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) { tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit)); } else { tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f))); } } else { startTimeOfSpeedingSign = 0; } } private void getPC() { pc.course = course; pc.scale = scale; pc.center = center.copy(); pc.dest = dest; } public void cleanup() { namesThread.cleanup(); urlsThread.cleanup(); tileReader.incUnusedCounter(); dictReader.incUnusedCounter(); } public void searchNextRoutableWay(RoutePositionMark pm) throws Exception { PaintContext pc = new PaintContext(this, null); pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE; pc.xSize = 100; pc.ySize = 100; Projection p; do { p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize); pc.setP(p); for (int i=0; i<4; i++) { tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT); } if (pc.actualRoutableWay != null) { break; } pc.xSize += 100; pc.ySize += 100; } while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); Way w = pc.actualRoutableWay; pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon); } private void setPointOfTheCompass() { String c = ""; if (ProjFactory.getProj() != ProjFactory.NORTH_UP && Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) { c = Configuration.getCompassDirection(course); } if (tl.bigOnScreenButtons && c.length() <= 1) { if (ProjFactory.getProj() == ProjFactory.NORTH_UP) { c = "(" + Configuration.getCompassDirection(0) + ")"; } else { c = " " + c + " "; } } tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c); } private int showConnectStatistics(Graphics g, int yc, int la) { g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]); GsmCell cell = null; if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) { cell = CellIdProvider.getInstance().obtainCachedCellID(); } Compass compass = null; if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) { compass = CompassProvider.getInstance().obtainCachedCompass(); } if (cell == null) { g.drawString("No Cell ID available", 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } else { g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } if (compass == null) { g.drawString("No compass direction available", 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } else { g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } if (statRecord == null) { g.drawString("No stats yet", 0, yc, Graphics.TOP | Graphics.LEFT); return yc+la; } for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) { g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("Count : " + collected, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; return yc; } public void showDestination(PaintContext pc) { if ( pc.getP() == null || imageCollector == null ) return; try { if (dest != null) { pc.getP().forward(dest.lat, dest.lon, pc.lineP2); int x = pc.lineP2.x - imageCollector.xScreenOverscan; int y = pc.lineP2.y - imageCollector.yScreenOverscan; pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS); pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]); if (dest.displayName != null) { pc.g.drawString(dest.displayName, x, y+8, Graphics.TOP | Graphics.HCENTER); } pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]); pc.g.setStrokeStyle(Graphics.SOLID); pc.g.drawLine( pc.getP().getImageCenter().x - imageCollector.xScreenOverscan, pc.getP().getImageCenter().y - imageCollector.yScreenOverscan,x, y); } } catch (Exception e) { if (imageCollector == null) { logger.silentexception("No ImageCollector", e); } e.printStackTrace(); } } public void showMovement(Graphics g) { if ( pc.getP() == null ) return; IntPoint centerP = null; try { if (imageCollector != null) { g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]); centerP = pc.getP().getImageCenter(); int centerX = centerP.x - imageCollector.xScreenOverscan; int centerY = centerP.y - imageCollector.yScreenOverscan; int posX, posY; if (!gpsRecenter) { IntPoint p1 = new IntPoint(0, 0); pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD), (pos.longitude * MoreMath.FAC_DECTORAD), p1); posX = p1.getX()-imageCollector.xScreenOverscan; posY = p1.getY()-imageCollector.yScreenOverscan; } else { posX = centerX; posY = centerY; } g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]); float radc = course * MoreMath.FAC_DECTORAD; int px = posX + (int) (Math.sin(radc) * 20); int py = posY - (int) (Math.cos(radc) * 20); if (!gpsRecenter || gpsRecenterInvalid) { g.drawLine(centerX, centerY - 12, centerX, centerY + 12); g.drawLine(centerX - 12, centerY, centerX + 12, centerY); g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360); } if (! gpsRecenterInvalid) { pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS); g.drawRect(posX - 4, posY - 4, 8, 8); g.drawLine(posX, posY, px, py); } } } catch (Exception e) { if (imageCollector == null) { logger.silentexception("No ImageCollector", e); } if (centerP == null) { logger.silentexception("No centerP", e); } e.printStackTrace(); } } public void showNextDataScreen(int currentScreen) { switch (currentScreen) { case DATASCREEN_TACHO: if (guiTrip == null) { guiTrip = new GuiTrip(this); } if (guiTrip != null) { guiTrip.show(); } break; case DATASCREEN_TRIP: if (guiSatellites == null) { guiSatellites = new GuiSatellites(this, locationProducer); } if (guiSatellites != null) { guiSatellites.show(); } break; case DATASCREEN_SATS: this.show(); break; case DATASCREEN_NONE: default: if (guiTacho == null) { guiTacho = new GuiTacho(this); } if (guiTacho != null) { guiTacho.show(); } break; } } public int showMemory(Graphics g, int yc, int la) { g.setColor(0); g.drawString(Locale.get("trace.Freemem") + runtime.freeMemory(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.Totmem") + runtime.totalMemory(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.Percent") + (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.ThreadsRunning") + Thread.activeCount(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.Names") + namesThread.getNameCount(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.SingleT") + tileReader.getLivingTilesCount() + "/" + tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.FileT") + dictReader.getLivingTilesCount() + "/" + dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.LastMsg") + lastTitleMsg, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString( Locale.get("trace.at") + lastTitleMsgClock, 0, yc, Graphics.TOP | Graphics.LEFT ); return (yc); } private void updatePosition() { if (pc != null) { pc.center = center.copy(); pc.scale = scale; pc.course=course; repaint(); if (locationUpdateListeners != null && !TrackPlayer.isPlaying) { synchronized (locationUpdateListeners) { for (int i = 0; i < locationUpdateListeners.size(); i++) { ((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated(); } } } } } public synchronized void receivePosition(float lat, float lon, float scale) { logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " + (lon * MoreMath.FAC_RADTODEC)); gpsRecenter = false; center.setLatLonRad(lat, lon); this.scale = scale; updatePosition(); } public synchronized void receiveCompassStatus(int status) { } public synchronized void receiveCompass(float direction) { logger.debug("Got compass reading: " + direction); compassDirection = (int) direction; compassDeviated = ((int) direction + compassDeviation + 360) % 360; } public static void updateLastUserActionTime() { lastUserActionTime = System.currentTimeMillis(); } public static long getDurationSinceLastUserActionTime() { return System.currentTimeMillis() - lastUserActionTime; } public void updateCourse(int newcourse) { coursegps = newcourse; if ((newcourse - course)> 180) { course = course + 360; } if ((course-newcourse)> 180) { newcourse = newcourse + 360; } if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) { course = newcourse; } else { course = course + ((newcourse - course)*3)/4 + 360; } while (course > 360) { course -= 360; } } public synchronized void receivePosition(Position pos) { logger.info("New position: " + pos); collected++; if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 && getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs() && isShown() ) { gpsRecenter = true; } if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) { if (pos.type == Position.TYPE_GPS_LASTKNOWN) { if (this.pos.type == Position.TYPE_CELLID) { return; } gpsRecenterInvalid = false; gpsRecenterStale = true; } } this.pos = pos; if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) { gpsRecenterInvalid = false; gpsRecenterStale = false; } if (gpsRecenter) { center.setLatLonDeg(pos.latitude, pos.longitude); speed = (int) (pos.speed * 3.6f); fspeed = pos.speed * 3.6f; if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && !Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) { if (thirdPrevCourse != -1) { updateCourse((int) pos.course); thirdPrevCourse = secondPrevCourse; secondPrevCourse = prevCourse; } else if (prevCourse == -1) { if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } prevCourse = (int) pos.course; } else if (secondPrevCourse == -1) { if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) { secondPrevCourse = prevCourse; } if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } } else { if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) { thirdPrevCourse = secondPrevCourse; secondPrevCourse = prevCourse; updateCourse((int) pos.course); } else { secondPrevCourse = -1; if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } } } prevCourse = (int) pos.course; } else { if (thirdPrevCourse != -1) { if ((Math.abs(prevCourse - secondPrevCourse) < 15 || Math.abs(prevCourse - secondPrevCourse) > 345) && (Math.abs(thirdPrevCourse - secondPrevCourse) < 15 || Math.abs(thirdPrevCourse - secondPrevCourse) > 345)) { } else { updateCourse(thirdPrevCourse); } } prevCourse = -1; secondPrevCourse = -1; thirdPrevCourse = -1; if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } } } if (gpx.isRecordingTrk()) { try { if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179 && pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) { } else { gpx.addTrkPt(pos); } } catch (Exception e) { receiveMessage(e.getMessage()); } } altitude = (int) (pos.altitude); if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM) && gpsRecenter && (isGpsConnected() || TrackPlayer.isPlaying) && autoZoomed && pc.getP() != null && pos.speed != Float.NaN && pos.speed != 0 ) { final float minimumScale = Configuration.getRealBaseScale() / 1.5f; final int minimumSpeed = 20; final float maximumScale = Configuration.getRealBaseScale() * 1.5f; final int maximumSpeed = 160; int speedForScale = speed; float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed); if (newScale < minimumScale) { newScale = minimumScale; } else if (newScale > maximumScale) { newScale = maximumScale; } if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) { float newScale2 = newScale; newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f); newScale = Math.max(newScale2, newScale / 1.5f); } scale = newScale; } updatePosition(); } public synchronized Position getCurrentPosition() { return this.pos; } public synchronized void receiveMessage(String s) { logger.info("Setting title: " + s); currentTitleMsg = s; synchronized (this) { if (setTitleMsgTimeout == 0) { currentTitleMsgOpenCount++; } setTitleMsgTimeout = 3000; } lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false); repaint(); } public void receiveSatellites(Satellite[] sats) { } public synchronized void alert(String title, String message, int timeout) { logger.info("Showing trace alert: " + title + ": " + message); if (timeout == Alert.FOREVER) { timeout = 10000; } currentAlertTitle = title; currentAlertMessage = message; synchronized (this) { if (setAlertTimeout == 0) { currentAlertsOpenCount++; } setAlertTimeout = timeout; } repaint(); } public MIDlet getParent() { return parent; } protected void pointerPressed(int x, int y) { updateLastUserActionTime(); long currTime = System.currentTimeMillis(); pointerDragged = false; pointerDraggedMuch = false; pointerActionDone = false; centerPointerPressedN = center.copy(); if (imageCollector != null) { panProjection=imageCollector.getCurrentProjection(); pickPointStart=panProjection.inverse(x,y, pickPointStart); } else { panProjection = null; } int touchedElementId = tl.getElementIdAtPointer(x, y); if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU) && tl.isAnyActionIdAtPointer(x, y) ) { tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId)); repaint(); } if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) { doubleTap(x, y); return; } pressedPointerTime = currTime; Trace.touchX = x; Trace.touchY = y; if (keyboardLocked) { keyPressed(0); return; } longTapTimerTask = new TimerTask() { public void run() { if (!pointerActionDone) { if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){ longTap(); } } } }; try { GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY); } catch (Exception e) { logger.error(Locale.get("trace.NoLongTapTimerTask") + e.toString()); } } protected void pointerReleased(int x, int y) { if (longTapTimerTask != null) { longTapTimerTask.cancel(); } if (tl.getTouchedElement() != null) { tl.clearTouchedElement(); repaint(); } if (!pointerActionDone && !keyboardLocked) { touchReleaseX = x; touchReleaseY = y; singleTapTimerTask = new TimerTask() { public void run() { if (!keyboardLocked) { singleTap(touchReleaseX, touchReleaseY); } } }; try { GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY); } catch (Exception e) { logger.error(Locale.get("trace.NoSingleTapTimerTask") + e.toString()); } if (pointerDragged) { pointerDragged(x , y); return; } } } protected void pointerDragged (int x, int y) { updateLastUserActionTime(); LayoutElement e = tl.getElementAtPointer(x, y); if (tl.getTouchedElement() != e) { if (longTapTimerTask != null) { longTapTimerTask.cancel(); } tl.clearTouchedElement(); repaint(); } if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) { tl.setTouchedElement(e); repaint(); } if (pointerActionDone) { return; } if (Math.abs(x - Trace.touchX) > 8 || Math.abs(y - Trace.touchY) > 8 ) { pointerDraggedMuch = true; pressedPointerTime = 0; } if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) { if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU && x - touchX > getWidth() / 4 ) { commandAction(TOGGLE_KEY_LOCK_CMD); pointerActionDone = true; } return; } if (keyboardLocked) { return; } pointerDragged = true; if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) { return; } if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) { pickPointEnd=panProjection.inverse(x,y, pickPointEnd); center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat); center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon); imageCollector.newDataReady(); gpsRecenter = false; } } private void singleTap(int x, int y) { pointerActionDone = true; if (tl.getElementIdAtPointer(touchX, touchY) < 0) { if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) { if (pointerDraggedMuch) { return; } logger.debug("single tap map"); if (!tl.bigOnScreenButtons) { tl.setOnScreenButtonSize(true); final long BIGBUTTON_DURATION = 5000; bigButtonTimerTask = new TimerTask() { public void run() { if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) { tl.setOnScreenButtonSize(false); requestRedraw(); bigButtonTimerTask.cancel(); } } }; try { GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500); } catch (Exception e) { logger.error("Error scheduling bigButtonTimerTask: " + e.toString()); } } } repaint(); } else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) { tl.clearTouchedElement(); int actionId = tl.getActionIdAtPointer(x, y); if (actionId > 0) { logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY); if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) { if (actionId == ZOOM_IN_CMD) { actionId = PAN_RIGHT2_CMD; } else if (actionId == ZOOM_OUT_CMD) { actionId = PAN_LEFT2_CMD; } } else if (manualRotationMode) { if (actionId == ZOOM_IN_CMD) { actionId = PAN_LEFT2_CMD; } else if (actionId == ZOOM_OUT_CMD) { actionId = PAN_RIGHT2_CMD; } } else if (TrackPlayer.isPlaying) { if (actionId == ZOOM_IN_CMD) { actionId = PAN_RIGHT2_CMD; } else if (actionId == ZOOM_OUT_CMD) { actionId = PAN_LEFT2_CMD; } } commandAction(actionId); repaint(); } } } private void doubleTap(int x, int y) { if (tl.getElementIdAtPointer(touchX, touchY) < 0) { if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) { if (singleTapTimerTask != null) { singleTapTimerTask.cancel(); } if (pointerDraggedMuch) { return; } logger.debug("double tap map"); pointerActionDone = true; commandAction(ZOOM_IN_CMD); } repaint(); return; } else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){ int actionId = tl.getActionIdDoubleAtPointer(x, y); logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x); if (actionId > 0) { if (singleTapTimerTask != null) { singleTapTimerTask.cancel(); } pointerActionDone = true; commandAction(actionId); tl.clearTouchedElement(); repaint(); return; } else { singleTap(x, y); } } } private void longTap() { if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) { if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) { pointerActionDone = true; logger.debug("long tap map"); pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd); center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat); center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon); Position oPos = new Position(center.radlat, center.radlon, 0.0f, 0.0f, 0.0f, 0, 0); imageCollector.newDataReady(); gpsRecenter = false; commandAction(ONLINE_INFO_CMD); } return; } else { int actionId = tl.getActionIdLongAtPointer(touchX, touchY); if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) { tl.clearTouchedElement(); repaint(); pointerActionDone = true; logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY); commandAction(actionId); } } } public Command getDataScreenCommand() { return CMDS[DATASCREEN_CMD]; } public Tile getDict(byte zl) { return tiles[zl]; } public void setDict(Tile dict, byte zl) { tiles[zl] = dict; if (zl == 0) { Configuration.getStartupPos(center); if (center.radlat == 0.0f && center.radlon == 0.0f) { dict.getCenter(center); } if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) { Node destNode = new Node(); Configuration.getDestPos(destNode); setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon)); } if (pc != null) { pc.center = center.copy(); pc.scale = scale; pc.course = course; } } updatePosition(); } public void setBaseTilesRead(boolean read) { baseTilesRead = read; } public void receiveStatistics(int[] statRecord, byte quality) { this.btquality = quality; this.statRecord = statRecord; repaint(); } public synchronized void locationDecoderEnd() { logger.info("enter locationDecoderEnd"); if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) { if (Legend.isValid) { GpsMid.mNoiseMaker.playSound("DISCONNECT"); } } removeCommand(CMDS[DISCONNECT_GPS_CMD]); if (locationProducer == null) { logger.info("leave locationDecoderEnd no producer"); return; } locationProducer = null; notify(); addCommand(CMDS[CONNECT_GPS_CMD]); logger.info("end locationDecoderEnd"); } public void receiveStatus(byte status, int satsReceived) { if (status != LocationMsgReceiver.STATUS_ON && status != LocationMsgReceiver.STATUS_2D && status != LocationMsgReceiver.STATUS_3D && status != LocationMsgReceiver.STATUS_DGPS) { prevCourse = -1; secondPrevCourse = -1; thirdPrevCourse = -1; } solution = status; solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived); repaint(); if (locationUpdateListeners != null && !TrackPlayer.isPlaying) { synchronized (locationUpdateListeners) { for (int i = 0; i < locationUpdateListeners.size(); i++) { ((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated(); } } } } public String getName(int idx) { if (idx < 0) { return null; } return namesThread.getName(idx); } public String getUrl(int idx) { if (idx < 0) { return null; } return urlsThread.getUrl(idx); } public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) { return namesThread.fulltextSearch(snippet, cmi); } public void requestRedraw() { repaint(); } public void newDataReady() { if (imageCollector != null) { imageCollector.newDataReady(); } } public void show() { Legend.freeDrawnWayAndAreaSearchImages(); GpsMid.getInstance().show(this); setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)); updateLastUserActionTime(); repaint(); } public void recreateTraceLayout() { tl = new TraceLayout(0, 0, getWidth(), getHeight()); } public void resetSize() { sizeChanged(getWidth(), getHeight()); } public void locationDecoderEnd(String msg) { receiveMessage(msg); locationDecoderEnd(); } public PositionMark getDestination() { return dest; } public void setDestination(RoutePositionMark dest) { endRouting(); this.dest = dest; pc.dest = dest; if (dest != null) { logger.info("Setting destination to " + dest.toString()); if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) { commandAction(SHOW_DEST_CMD); } if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) { Configuration.setDestPos(new Node(dest.lat, dest.lon, true)); Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true); } movedAwayFromDest = false; } else { Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false); logger.info("Setting destination to null"); } } public void endRouting() { RouteInstructions.initialRecalcDone = false; RouteInstructions.icCountOffRouteDetected = 0; RouteInstructions.routeInstructionsHeight = 0; RouteInstructions.abortRouteLineProduction(); setRoute(null); setRouteNodes(null); } public void setRoute(Vector route) { synchronized(this) { this.route = route; } if (this.route != null) { RouteInstructions.resetOffRoute(this.route, center); if (ri == null) { ri = new RouteInstructions(this); } if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) { resumeImageCollectorAfterRouteCalc(); } ri.newRoute(this.route); oldRecalculationTime = System.currentTimeMillis(); } resumeImageCollectorAfterRouteCalc(); routeCalc=false; routeEngine=null; } private void resumeImageCollectorAfterRouteCalc() { try { if (imageCollector == null) { startImageCollector(); imageCollector.resume(); } else if (imageCollector != null) { imageCollector.newDataReady(); } repaint(); } catch (Exception e) { logger.exception(Locale.get("trace.InTraceResumeImageCollector"), e); } } public void dropCache() { tileReader.dropCache(); dictReader.dropCache(); System.gc(); namesThread.dropCache(); urlsThread.dropCache(); System.gc(); if (gpx != null) { gpx.dropCache(); } } public QueueDataReader getDataReader() { return tileReader; } public QueueDictReader getDictReader() { return dictReader; } public Vector getRouteNodes() { return routeNodes; } public void setRouteNodes(Vector routeNodes) { this.routeNodes = routeNodes; } protected void hideNotify() { logger.debug("Hide notify has been called, screen will no longer be updated"); if (imageCollector != null) { imageCollector.suspend(); } } protected void showNotify() { logger.debug("Show notify has been called, screen will be updated again"); if (imageCollector != null) { imageCollector.resume(); imageCollector.newDataReady(); } } public Vector getRoute() { return route; } public void actionCompleted() { boolean reAddCommands = true; if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) { addAllCommands(); } } public void showIconMenu() { if (traceIconMenu == null) { traceIconMenu = new TraceIconMenu(this, this); } traceIconMenu.show(); } public static void uncacheIconMenu() { if (traceIconMenu != null) { logger.trace("uncaching TraceIconMenu"); } traceIconMenu = null; } public void recreateAndShowIconMenu() { uncacheIconMenu(); showIconMenu(); } public void performIconAction(int actionId) { show(); updateLastUserActionTime(); if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) { logger.info("low mem: Uncaching traceIconMenu"); uncacheIconMenu(); } if (actionId != IconActionPerformer.BACK_ACTIONID) { commandAction(actionId); } } public static String showDistance(int meters) { return showDistance(meters, DISTANCE_GENERIC); } public static String showDistance(int meters, int type) { if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) { if (type == DISTANCE_UNKNOWN) { return "???" + Locale.get("guitacho.m"); } int MajorUnit = meters / 1000; int MinorUnit = meters % 1000; String MinorShort = Integer.toString((int)MinorUnit / 100); if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) { if (MajorUnit == 0) { return Integer.toString(MinorUnit) + Locale.get("guitacho.m"); } else { return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km"); } } else { return Integer.toString(meters) + Locale.get("guitacho.m"); } } else { if (type == DISTANCE_UNKNOWN) { return "???" + Locale.get("guitacho.yd"); } int MajorUnit = (int)(meters / 1609.344f); int MinorUnit = (int)(meters % 1609.344f + 0.5f); String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f)); if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) { if (MajorUnit == 0) { return Integer.toString(MinorUnit) + Locale.get("guitacho.yd"); } else { return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi"); } } else { return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd"); } } } }
public void commandAction(Command c, Displayable d) { updateLastUserActionTime(); try { if((keyboardLocked) && (d != null)) { keyPressed(0); return; } if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD]) || (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD]) || (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD]) || (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) { int panX = 0; int panY = 0; int courseDiff = 0; int backLightLevelDiff = 0; if (c == CMDS[PAN_LEFT25_CMD]) { panX = -25; } else if (c == CMDS[PAN_RIGHT25_CMD]) { panX = 25; } else if (c == CMDS[PAN_UP25_CMD]) { panY = -25; } else if (c == CMDS[PAN_DOWN25_CMD]) { panY = 25; } else if (c == CMDS[PAN_LEFT2_CMD]) { if (TrackPlayer.isPlaying) { TrackPlayer.slower(); } else if (manualRotationMode) { courseDiff=-5; } else { panX = -2; } backLightLevelDiff = -25; } else if (c == CMDS[PAN_RIGHT2_CMD]) { if (TrackPlayer.isPlaying) { TrackPlayer.faster(); } else if (manualRotationMode) { courseDiff=5; } else { panX = 2; } backLightLevelDiff = 25; } else if (c == CMDS[PAN_UP2_CMD]) { if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) { RouteInstructions.toNextInstruction(1); } else { panY = -2; } } else if (c == CMDS[PAN_DOWN2_CMD]) { if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) { RouteInstructions.toNextInstruction(-1); } else { panY = 2; } } if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) { Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false); lastBackLightOnTime = System.currentTimeMillis(); Configuration.addToBackLightLevel(backLightLevelDiff); parent.showBackLightLevel(); } else if (imageCollector != null) { if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) { if (compassDeviation == 360) { compassDeviation = 0; } else { compassDeviation += courseDiff; compassDeviation %= 360; if (course < 0) { course += 360; } } } else { if (courseDiff == 360) { course = 0; } else { course += courseDiff; course %= 360; if (course < 0) { course += 360; } } if (panX != 0 || panY != 0) { gpsRecenter = false; } } imageCollector.getCurrentProjection().pan(center, panX, panY); } gpsRecenter = false; return; } if (c == CMDS[EXIT_CMD]) { if (Legend.isValid && gpx.isRecordingTrk()) { alert(Locale.get("trace.RecordMode"), Locale.get("trace.PleaseStopRecording") , 2500); return; } if (Legend.isValid) { pause(); } parent.exit(); return; } if (c == CMDS[START_RECORD_CMD]) { try { gpx.newTrk(false); alert(Locale.get("trace.GpsRecording"), Locale.get("trace.StartingToRecord"), 1250); } catch (RuntimeException e) { receiveMessage(e.getMessage()); } recordingsMenu = null; return; } if (c == CMDS[STOP_RECORD_CMD]) { gpx.saveTrk(false); alert(Locale.get("trace.GpsRecording"), Locale.get("trace.StoppingToRecord"), 1250); recordingsMenu = null; return; } if (c == CMDS[MANAGE_TRACKS_CMD]) { if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) { alert(Locale.get("trace.RecordMode"), Locale.get("trace.YouNeedStopRecording") , 4000); return; } GuiGpx guiGpx = new GuiGpx(this); guiGpx.show(); return; } if (c == CMDS[REFRESH_CMD]) { repaint(); return; } if (c == CMDS[CONNECT_GPS_CMD]) { if (locationProducer == null) { if (TrackPlayer.isPlaying) { TrackPlayer.getInstance().stop(); alert(Locale.get("trace.Trackplayer"), Locale.get("trace.PlayingStopped"), 2500); } Thread thread = new Thread(this,"LocationProducer init"); thread.start(); } return; } if (c == CMDS[DISCONNECT_GPS_CMD]) { if (locationProducer != null) { locationProducer.close(); } return; } if (c == CMDS[TOGGLE_GPS_CMD]) { if (isGpsConnected()) { commandAction(DISCONNECT_GPS_CMD); } else { commandAction(CONNECT_GPS_CMD); } return; } if (c == CMDS[SEARCH_CMD]) { GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT); guiSearch.show(); return; } if (c == CMDS[ENTER_WAYP_CMD]) { if (gpx.isLoadingWaypoints()) { showAlertLoadingWpt(); } else { GuiWaypointEnter gwpe = new GuiWaypointEnter(this); gwpe.show(); } return; } if (c == CMDS[MANAGE_WAYP_CMD]) { if (gpx.isLoadingWaypoints()) { showAlertLoadingWpt(); } else { GuiWaypoint gwp = new GuiWaypoint(this); gwp.show(); } return; } if (c == CMDS[MAPFEATURES_CMD]) { GuiMapFeatures gmf = new GuiMapFeatures(this); gmf.show(); repaint(); return; } if (c == CMDS[OVERVIEW_MAP_CMD]) { GuiOverviewElements ovEl = new GuiOverviewElements(this); ovEl.show(); repaint(); return; } if (c == CMDS[SEND_MESSAGE_CMD]) { GuiSendMessage sendMsg = new GuiSendMessage(this); sendMsg.show(); repaint(); return; } if (c == CMDS[RECORDINGS_CMD]) { if (recordingsMenu == null) { boolean hasJSR120 = Configuration.hasDeviceJSR120(); int noElements = 5; noElements += 2; if (hasJSR120) { noElements++; } int idx = 0; String[] elements; if (gpx.isRecordingTrk()) { noElements++; elements = new String[noElements]; recordingsMenuCmds = new int[noElements]; recordingsMenuCmds[idx] = STOP_RECORD_CMD; elements[idx++] = Locale.get("trace.StopGpxTracklog"); if (gpx.isRecordingTrkSuspended()) { recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD; elements[idx++] = Locale.get("trace.ResumeRecording"); } else { recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD; elements[idx++] = Locale.get("trace.SuspendRecording"); } } else { elements = new String[noElements]; recordingsMenuCmds = new int[noElements]; recordingsMenuCmds[idx] = START_RECORD_CMD; elements[idx++] = Locale.get("trace.StartGpxTracklog"); } recordingsMenuCmds[idx] = SAVE_WAYP_CMD; elements[idx++] = Locale.get("trace.SaveWaypoint"); recordingsMenuCmds[idx] = ENTER_WAYP_CMD; elements[idx++] = Locale.get("trace.EnterWaypoint"); recordingsMenuCmds[idx] = MANAGE_TRACKS_CMD; elements[idx++] = Locale.get("trace.ManageTracks"); recordingsMenuCmds[idx] = MANAGE_WAYP_CMD; elements[idx++] = Locale.get("trace.ManageWaypoints"); recordingsMenuCmds[idx] = CAMERA_CMD; elements[idx++] = Locale.get("trace.TakePictures"); if (audioRec.isRecording()) { recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC; elements[idx++] = Locale.get("trace.StopAudioRecording"); } else { recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC; elements[idx++] = Locale.get("trace.StartAudioRecording"); } if (hasJSR120) { recordingsMenuCmds[idx] = SEND_MESSAGE_CMD; elements[idx++] = Locale.get("trace.SendSMSMapPos"); } recordingsMenu = new List(Locale.get("trace.Recordings"), Choice.IMPLICIT, elements, null); recordingsMenu.addCommand(CMDS[OK_CMD]); recordingsMenu.addCommand(CMDS[BACK_CMD]); recordingsMenu.setSelectCommand(CMDS[OK_CMD]); parent.show(recordingsMenu); recordingsMenu.setCommandListener(this); } if (recordingsMenu != null) { recordingsMenu.setSelectedIndex(0, true); parent.show(recordingsMenu); } return; } if (c == CMDS[ROUTINGS_CMD]) { if (routingsMenu == null) { String[] elements = new String[4]; if (routeCalc || route != null) { elements[0] = Locale.get("trace.StopRouting"); } else { elements[0] = Locale.get("trace.CalculateRoute"); } elements[1] = Locale.get("trace.SetDestination"); elements[2] = Locale.get("trace.ShowDestination"); elements[3] = Locale.get("trace.ClearDestination"); routingsMenu = new List(Locale.get("trace.Routing2"), Choice.IMPLICIT, elements, null); routingsMenu.addCommand(CMDS[OK_CMD]); routingsMenu.addCommand(CMDS[BACK_CMD]); routingsMenu.setSelectCommand(CMDS[OK_CMD]); routingsMenu.setCommandListener(this); } if (routingsMenu != null) { routingsMenu.setSelectedIndex(0, true); parent.show(routingsMenu); } return; } if (c == CMDS[SAVE_WAYP_CMD]) { if (gpx.isLoadingWaypoints()) { showAlertLoadingWpt(); } else { PositionMark posMark = null; if (gpsRecenter) { posMark = new PositionMark(center.radlat, center.radlon, (int)pos.altitude, pos.timeMillis, (byte)-1, (byte)-1, (byte)-1, (byte)-1); } else { posMark = new PositionMark(center.radlat, center.radlon, PositionMark.INVALID_ELEVATION, pos.timeMillis, (byte)-1, (byte)-1, (byte)-1, (byte)-1); } showGuiWaypointSave(posMark); } return; } if (c == CMDS[ONLINE_INFO_CMD]) { Position oPos = new Position(center.radlat, center.radlon, 0.0f, 0.0f, 0.0f, 0, 0); GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc); gWeb.show(); alert(Locale.get("trace.NoOnlineCapa"), Locale.get("trace.SetAppGeneric") + Locale.get("trace.PropertiesFile"), Alert.FOREVER); } if (c == CMDS[BACK_CMD]) { show(); return; } if (c == CMDS[OK_CMD]) { if (d == recordingsMenu) { int recCmd = recordingsMenu.getSelectedIndex(); if (recCmd >= 0 && recCmd < recordingsMenuCmds.length) { recCmd = recordingsMenuCmds[recCmd]; if (recCmd == STOP_RECORD_CMD) { commandAction(STOP_RECORD_CMD); if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) { show(); } } else if (recCmd == START_RECORD_CMD) { commandAction(START_RECORD_CMD); if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) { show(); } } else if (recCmd == TOGGLE_RECORDING_SUSP_CMD) { commandAction(TOGGLE_RECORDING_SUSP_CMD); show(); } else { commandAction(recCmd); } } } else if (d == routingsMenu) { show(); switch (routingsMenu.getSelectedIndex()) { case 0: { if (routeCalc || route != null) { commandAction(ROUTING_STOP_CMD); } else { commandAction(ROUTING_START_WITH_MODE_SELECT_CMD); } break; } case 1: { commandAction(SET_DEST_CMD); break; } case 2: { commandAction(SHOW_DEST_CMD); break; } case 3: { commandAction(CLEAR_DEST_CMD); break; } } } return; } if (c == CMDS[CAMERA_CMD]) { try { Class GuiCameraClass = Class.forName("de.ueller.gpsmid.ui.GuiCamera"); Object GuiCameraObject = GuiCameraClass.newInstance(); GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject; cam.init(this); cam.show(); } catch (ClassNotFoundException cnfe) { logger.exception(Locale.get("trace.YourPhoneNoCamSupport"), cnfe); } return; } if (c == CMDS[TOGGLE_AUDIO_REC]) { if (audioRec.isRecording()) { audioRec.stopRecord(); } else { audioRec.startRecorder(); } recordingsMenu = null; return; } if (c == CMDS[ROUTING_TOGGLE_CMD]) { if (routeCalc || route != null) { commandAction(ROUTING_STOP_CMD); } else { commandAction(ROUTING_START_WITH_MODE_SELECT_CMD); } return; } if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) { gpsRecenter = true; gpsRecenterInvalid = true; gpsRecenterStale = true; GuiRoute guiRoute = new GuiRoute(this, false); if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) { commandAction(ROUTING_START_CMD); } else { guiRoute.show(); } return; } if (c == CMDS[ROUTING_START_CMD]) { if (! routeCalc || RouteLineProducer.isRunning()) { routeCalc = true; if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) { stopImageCollector(); } RouteInstructions.resetOffRoute(route, center); RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon); logger.info("Routing source: " + routeSource); routeNodes=new Vector(); routeEngine = new Routing(this); routeEngine.solve(routeSource, dest); } routingsMenu = null; return; } if (c == CMDS[ROUTING_STOP_CMD]) { NoiseMaker.stopPlayer(); if (routeCalc) { if (routeEngine != null) { routeEngine.cancelRouting(); } alert(Locale.get("trace.RouteCalculation"), Locale.get("trace.Cancelled"), 1500); } else { alert(Locale.get("trace.Routing"), Locale.get("generic.Off"), 750); } endRouting(); routingsMenu = null; synchronized (this) { if (imageCollector != null) { imageCollector.newDataReady(); } } routingsMenu = null; return; } if (c == CMDS[ZOOM_IN_CMD]) { scale = scale / 1.5f; autoZoomed = false; return; } if (c == CMDS[ZOOM_OUT_CMD]) { scale = scale * 1.5f; autoZoomed = false; return; } if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) { manualRotationMode = !manualRotationMode; if (manualRotationMode) { if (hasPointerEvents()) { alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ChangeCourse"), 3000); } else { alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ChangeCourseWithLeftRightKeys"), 3000); } } else { alert(Locale.get("trace.ManualRotation"), Locale.get("generic.Off"), 750); } return; } if (c == CMDS[TOGGLE_OVERLAY_CMD]) { showAddons++; repaint(); return; } if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) { Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, !(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)), false); lastBackLightOnTime = System.currentTimeMillis(); parent.showBackLightLevel(); return; } if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) { boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN); Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false); setFullScreenMode(fullScreen); return; } if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) { if (manualRotationMode) { if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) { compassDeviation = 0; } else { course = 0; } alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750); } else { alert(Locale.get("guidiscover.MapProjection"), ProjFactory.nextProj(), 750); } synchronized (this) { if (imageCollector != null) { imageCollector.newDataReady(); } } return; } if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) { keyboardLocked = !keyboardLocked; if (keyboardLocked) { keyPressed(0); } else { alert(Locale.get("trace.GpsMid"), hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked") : Locale.get("trace.KeysUnlocked"), 1000); } return; } if (c == CMDS[TOGGLE_RECORDING_CMD]) { if ( gpx.isRecordingTrk() ) { commandAction(STOP_RECORD_CMD); } else { commandAction(START_RECORD_CMD); } return; } if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) { if (gpx.isRecordingTrk()) { if ( gpx.isRecordingTrkSuspended() ) { alert(Locale.get("trace.GpsRecording"), Locale.get("trace.ResumingRecording"), 1000); gpx.resumeTrk(); } else { alert(Locale.get("trace.GpsRecording"), Locale.get("trace.SuspendingRecording"), 1000); gpx.suspendTrk(); } } recordingsMenu = null; return; } if (c == CMDS[RECENTER_GPS_CMD]) { gpsRecenter = true; gpsRecenterInvalid = true; gpsRecenterStale = true; autoZoomed = true; if (pos.latitude != 0.0f) { receivePosition(pos); } newDataReady(); return; } if (c == CMDS[SHOW_DEST_CMD]) { if (dest != null) { gpsRecenter = false; prevPositionNode = center.copy(); center.setLatLonRad(dest.lat, dest.lon); movedAwayFromDest = false; updatePosition(); } else { alert(Locale.get("trace.ShowDestination"), Locale.get("trace.DestinationNotSpecifiedYet"), 3000); } return; } if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) { if (prevPositionNode != null) { gpsRecenter = false; center.setLatLon(prevPositionNode); updatePosition(); } } if (c == CMDS[DATASCREEN_CMD]) { showNextDataScreen(DATASCREEN_NONE); return; } if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) { showIconMenu(); return; } if (c == CMDS[SETUP_CMD]) { new GuiDiscover(parent); return; } if (c == CMDS[ABOUT_CMD]) { new Splash(parent, GpsMid.initDone); return; } if (c == CMDS[CELLID_LOCATION_CMD]) { if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) { locationProducer.triggerPositionUpdate(); newDataReady(); } else { if (cellIDLocationProducer == null) { cellIDLocationProducer = new SECellId(); if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) { logger.info("Failed to initialise CellID location producer"); } } if (cellIDLocationProducer != null) { cellIDLocationProducer.triggerPositionUpdate(); newDataReady(); } } return; } if (c == CMDS[MANUAL_LOCATION_CMD]) { Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD, center.radlon / MoreMath.FAC_DECTORAD, PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1, System.currentTimeMillis(), Position.TYPE_MANUAL); gpsRecenter = true; autoZoomed = true; receivePosition(setpos); receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0); newDataReady(); return; } if (! routeCalc) { if (c == CMDS[RETRIEVE_XML]) { if (Legend.enableEdits) { if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) { parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER); } if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) { EditableWay eway = (EditableWay)pc.actualWay; GuiOsmWayDisplay guiWay = new GuiOsmWayDisplay(eway, pc.actualSingleTile, this); guiWay.show(); guiWay.refresh(); } } else { parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER); } } if (c == CMDS[EDIT_ENTITY]) { if (Legend.enableEdits) { GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY); guiSearch.show(); return; } else { parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER); } } if (c == CMDS[RETRIEVE_NODE]) { if (Legend.enableEdits) { GuiOsmPoiDisplay guiNode = new GuiOsmPoiDisplay(-1, null, center.radlat, center.radlon, this); guiNode.show(); guiNode.refresh(); } else { logger.error(Locale.get("trace.EditingIsNotEnabled")); } } if (c == CMDS[EDIT_ADDR_CMD]) { if (Legend.enableEdits) { String streetName = ""; if ((pc != null) && (pc.actualWay != null)) { streetName = getName(pc.actualWay.nameIdx); } GuiOsmAddrDisplay guiAddr = new GuiOsmAddrDisplay(-1, streetName, null, center.radlat, center.radlon, this); guiAddr.show(); } else { logger.error(Locale.get("trace.EditingIsNotEnabled")); } } if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) { alert("No online capabilites", Locale.get("trace.SetAppGeneric") + Locale.get("trace.PropertiesFile"), Alert.FOREVER); } if (c == CMDS[SET_DEST_CMD]) { RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon); setDestination(pm1); return; } if (c == CMDS[CLEAR_DEST_CMD]) { setDestination(null); return; } } else { alert(Locale.get("trace.Error"), Locale.get("trace.CurrentlyInRouteCalculation"), 2000); } } catch (Exception e) { logger.exception(Locale.get("trace.InTraceCommandAction"), e); } } private void startImageCollector() throws Exception { logger.info("Starting ImageCollector"); Images images = new Images(); pc = new PaintContext(this, images); imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images); pc.center = center.copy(); pc.scale = scale; pc.xSize = this.getWidth(); pc.ySize = this.getHeight(); } private void stopImageCollector(){ logger.info("Stopping ImageCollector"); cleanup(); if (imageCollector != null ) { imageCollector.stop(); imageCollector=null; } System.gc(); } public void startup() throws Exception { namesThread = new Names(); urlsThread = new Urls(); new DictReader(this); if (Legend.isValid) { while (!baseTilesRead) { try { Thread.sleep(250); } catch (InterruptedException e1) { } } } if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) { Thread thread = new Thread(this, "Trace"); thread.start(); } tileReader = new QueueDataReader(this); dictReader = new QueueDictReader(this); this.gpx = new Gpx(); this.audioRec = new AudioRecorder(); setDict(gpx, (byte)5); startImageCollector(); recreateTraceLayout(); } public void shutdown() { if (gpx != null) { gpx.saveTrk(true); } logger.debug("Shutdown: stopImageCollector"); stopImageCollector(); if (namesThread != null) { logger.debug("Shutdown: namesThread"); namesThread.stop(); namesThread = null; } if (urlsThread != null) { urlsThread.stop(); urlsThread = null; } if (dictReader != null) { logger.debug("Shutdown: dictReader"); dictReader.shutdown(); dictReader = null; } if (tileReader != null) { logger.debug("Shutdown: tileReader"); tileReader.shutdown(); tileReader = null; } if (locationProducer != null) { logger.debug("Shutdown: locationProducer"); locationProducer.close(); } if (TrackPlayer.isPlaying) { logger.debug("Shutdown: TrackPlayer"); TrackPlayer.getInstance().stop(); } } public void sizeChanged(int w, int h) { updateLastUserActionTime(); if (imageCollector != null) { logger.info("Size of Canvas changed to " + w + "|" + h); stopImageCollector(); try { startImageCollector(); imageCollector.resume(); imageCollector.newDataReady(); } catch (Exception e) { logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector"), e); } updatePosition(); } tl = new TraceLayout(0, 0, w, h); } protected void paint(Graphics g) { logger.debug("Drawing Map screen"); try { int yc = 1; int la = 18; getPC(); g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]); g.fillRect(0, 0, this.getWidth(), this.getHeight()); pc.g = g; if (imageCollector != null) { Node drawnCenter = imageCollector.paint(pc); if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null) { pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2); int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2); if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs && Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs ) { ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan); } } } else { tl.ele[TraceLayout.WAYNAME].setText(" "); } if (dest != null) { float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon); atDest = (distance < 25); if (atDest) { if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) { GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1); } } else if (!movedAwayFromDest) { movedAwayFromDest = true; } } speeding = false; int maxSpeed = 0; if (gpsRecenter && actualSpeedLimitWay != null) { maxSpeed = actualSpeedLimitWay.getMaxSpeed(); if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER) && (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) { maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter(); } if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) { speeding = true; } } if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) { if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) { lastTimeOfSpeedingSound = System.currentTimeMillis(); GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound()); } } g.setColor(Legend.COLOR_MAP_TEXT); switch (showAddons) { case 1: yc = showMemory(g, yc, la); break; case 2: yc = showConnectStatistics(g, yc, la); break; default: showAddons = 0; if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) { if (pc != null) { tl.calcScaleBarWidth(pc); tl.ele[TraceLayout.SCALEBAR].setText(" "); } } setPointOfTheCompass(); } showMovement(g); LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION]; LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT]; if (gpx.isRecordingTrk()) { if (gpx.isRecordingTrkSuspended()) { eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); } else { eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); } eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")); } if (TrackPlayer.isPlaying) { eSolution.setText(Locale.get("trace.Replay")); } else { if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID || solution == LocationMsgReceiver.STATUS_MANUAL)) { eSolution.setText(Locale.get("solution.Off")); } else { eSolution.setText(solutionStr); } } LayoutElement e = tl.ele[TraceLayout.CELLID]; if (SECellLocLogger.isCellIDLogging() > 0) { if (SECellLocLogger.isCellIDLogging() == 2) { e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); } else { e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); } e.setText(Locale.get("trace.cellIDs")); } e = tl.ele[TraceLayout.AUDIOREC]; if (audioRec.isRecording()) { e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); e.setText(Locale.get("trace.AudioRec")); } if (pc != null) { showDestination(pc); } if (speed > 0 && Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) { if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) { tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")); } else { tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph")); } } if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP) && locationProducer != null && LocationMsgReceiverList.isPosValid(solution) ) { tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE)); } if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) ) && Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) { e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE]; e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]); double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon); e.setText(Locale.get("trace.Air") + showDistance((int) distLine, DISTANCE_AIR)); } if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) { e = tl.ele[TraceLayout.CURRENT_TIME]; e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true)); tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e); } setSpeedingSign(maxSpeed); if (hasPointerEvents()) { tl.ele[TraceLayout.ZOOM_IN].setText("+"); tl.ele[TraceLayout.ZOOM_OUT].setText("-"); tl.ele[TraceLayout.RECENTER_GPS].setText("|"); e = tl.ele[TraceLayout.SHOW_DEST]; if (atDest && prevPositionNode != null) { e.setText("<"); e.setActionID(SHOW_PREVIOUS_POSITION_CMD); } else { e.setText(">"); e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) ); } tl.ele[TraceLayout.RECORDINGS].setText("*"); tl.ele[TraceLayout.SEARCH].setText("_"); } e = tl.ele[TraceLayout.TITLEBAR]; if (currentTitleMsgOpenCount != 0) { e.setText(currentTitleMsg); synchronized (this) { if (setTitleMsgTimeout != 0) { TimerTask timerT = new TimerTask() { public synchronized void run() { currentTitleMsgOpenCount--; lastTitleMsg = currentTitleMsg; if (currentTitleMsgOpenCount == 0) { logger.debug("clearing title"); repaint(); } } }; GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout); setTitleMsgTimeout = 0; } } } tl.paint(g); if (currentAlertsOpenCount > 0) { showCurrentAlert(g); } } catch (Exception e) { logger.silentexception("Unhandled exception in the paint code", e); } } public void showGuiWaypointSave(PositionMark posMark) { if (guiWaypointSave == null) { guiWaypointSave = new GuiWaypointSave(this); } if (guiWaypointSave != null) { guiWaypointSave.setData(posMark); guiWaypointSave.show(); } } private void showAlertLoadingWpt() { alert("Way points", "Way points are not ready yet.", 3000); } private void showCurrentAlert(Graphics g) { Font font = g.getFont(); Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize()); int fontHeight = font.getHeight(); int y = titleFont.getHeight() + 2 + fontHeight; int extraWidth = font.charWidth('W'); int alertWidth = titleFont.stringWidth(currentAlertTitle); int maxWidth = getWidth() - extraWidth; for (int i = 0; i <= 1; i++) { int nextSpaceAt = 0; int prevSpaceAt = 0; int start = 0; do { int width = 0; while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) { prevSpaceAt = nextSpaceAt; nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt); if (nextSpaceAt == -1) { nextSpaceAt = currentAlertMessage.length(); } width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start); nextSpaceAt++; } nextSpaceAt--; while (width > maxWidth) { if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) { nextSpaceAt = prevSpaceAt; } else { nextSpaceAt--; } width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start); } if (alertWidth < width ) { alertWidth = width; } if (i==1) { g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start, getWidth()/2, y, Graphics.TOP|Graphics.HCENTER); } y += fontHeight; start = nextSpaceAt; } while (nextSpaceAt < currentAlertMessage.length() ); if (i == 0) { alertWidth += extraWidth; int alertHeight = y; int alertTop = (getHeight() - alertHeight) /2; int alertLeft = (getWidth() - alertWidth) / 2; g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]); g.fillRect(alertLeft, alertTop, alertWidth, alertHeight); g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]); g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3); g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]); g.setStrokeStyle(Graphics.SOLID); g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); y = alertTop + 2; g.setFont(titleFont); g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]); g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER); g.setFont(font); y += (fontHeight * 3 / 2); } } synchronized (this) { if (setAlertTimeout != 0) { TimerTask timerT = new TimerTask() { public synchronized void run() { currentAlertsOpenCount--; if (currentAlertsOpenCount == 0) { logger.debug("clearing alert"); repaint(); } } }; GpsMid.getTimer().schedule(timerT, setAlertTimeout); setAlertTimeout = 0; } } } private void setSpeedingSign(int maxSpeed) { if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL) && ( speeding || (System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000 ) ) { if (speeding) { speedingSpeedLimit = maxSpeed; startTimeOfSpeedingSign = System.currentTimeMillis(); } if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) { tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit)); } else { tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f))); } } else { startTimeOfSpeedingSign = 0; } } private void getPC() { pc.course = course; pc.scale = scale; pc.center = center.copy(); pc.dest = dest; } public void cleanup() { namesThread.cleanup(); urlsThread.cleanup(); tileReader.incUnusedCounter(); dictReader.incUnusedCounter(); } public void searchNextRoutableWay(RoutePositionMark pm) throws Exception { PaintContext pc = new PaintContext(this, null); pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE; pc.xSize = 100; pc.ySize = 100; Projection p; do { p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize); pc.setP(p); for (int i=0; i<4; i++) { tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT); } if (pc.actualRoutableWay != null) { break; } pc.xSize += 100; pc.ySize += 100; } while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); Way w = pc.actualRoutableWay; pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon); } private void setPointOfTheCompass() { String c = ""; if (ProjFactory.getProj() != ProjFactory.NORTH_UP && Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) { c = Configuration.getCompassDirection(course); } if (tl.bigOnScreenButtons && c.length() <= 1) { if (ProjFactory.getProj() == ProjFactory.NORTH_UP) { c = "(" + Configuration.getCompassDirection(0) + ")"; } else { c = " " + c + " "; } } tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c); } private int showConnectStatistics(Graphics g, int yc, int la) { g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]); GsmCell cell = null; if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) { cell = CellIdProvider.getInstance().obtainCachedCellID(); } Compass compass = null; if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) { compass = CompassProvider.getInstance().obtainCachedCompass(); } if (cell == null) { g.drawString("No Cell ID available", 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } else { g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } if (compass == null) { g.drawString("No compass direction available", 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } else { g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } if (statRecord == null) { g.drawString("No stats yet", 0, yc, Graphics.TOP | Graphics.LEFT); return yc+la; } for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) { g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; } g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString("Count : " + collected, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; return yc; } public void showDestination(PaintContext pc) { if ( pc.getP() == null || imageCollector == null ) return; try { if (dest != null) { pc.getP().forward(dest.lat, dest.lon, pc.lineP2); int x = pc.lineP2.x - imageCollector.xScreenOverscan; int y = pc.lineP2.y - imageCollector.yScreenOverscan; pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS); pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]); if (dest.displayName != null) { pc.g.drawString(dest.displayName, x, y+8, Graphics.TOP | Graphics.HCENTER); } pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]); pc.g.setStrokeStyle(Graphics.SOLID); pc.g.drawLine( pc.getP().getImageCenter().x - imageCollector.xScreenOverscan, pc.getP().getImageCenter().y - imageCollector.yScreenOverscan,x, y); } } catch (Exception e) { if (imageCollector == null) { logger.silentexception("No ImageCollector", e); } e.printStackTrace(); } } public void showMovement(Graphics g) { if ( pc.getP() == null ) return; IntPoint centerP = null; try { if (imageCollector != null) { g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]); centerP = pc.getP().getImageCenter(); int centerX = centerP.x - imageCollector.xScreenOverscan; int centerY = centerP.y - imageCollector.yScreenOverscan; int posX, posY; if (!gpsRecenter) { IntPoint p1 = new IntPoint(0, 0); pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD), (pos.longitude * MoreMath.FAC_DECTORAD), p1); posX = p1.getX()-imageCollector.xScreenOverscan; posY = p1.getY()-imageCollector.yScreenOverscan; } else { posX = centerX; posY = centerY; } g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]); float radc = course * MoreMath.FAC_DECTORAD; int px = posX + (int) (Math.sin(radc) * 20); int py = posY - (int) (Math.cos(radc) * 20); if (!gpsRecenter || gpsRecenterInvalid) { g.drawLine(centerX, centerY - 12, centerX, centerY + 12); g.drawLine(centerX - 12, centerY, centerX + 12, centerY); g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360); } if (! gpsRecenterInvalid) { pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS); g.drawRect(posX - 4, posY - 4, 8, 8); g.drawLine(posX, posY, px, py); } } } catch (Exception e) { if (imageCollector == null) { logger.silentexception("No ImageCollector", e); } if (centerP == null) { logger.silentexception("No centerP", e); } e.printStackTrace(); } } public void showNextDataScreen(int currentScreen) { switch (currentScreen) { case DATASCREEN_TACHO: if (guiTrip == null) { guiTrip = new GuiTrip(this); } if (guiTrip != null) { guiTrip.show(); } break; case DATASCREEN_TRIP: if (guiSatellites == null) { guiSatellites = new GuiSatellites(this, locationProducer); } if (guiSatellites != null) { guiSatellites.show(); } break; case DATASCREEN_SATS: this.show(); break; case DATASCREEN_NONE: default: if (guiTacho == null) { guiTacho = new GuiTacho(this); } if (guiTacho != null) { guiTacho.show(); } break; } } public int showMemory(Graphics g, int yc, int la) { g.setColor(0); g.drawString(Locale.get("trace.Freemem") + runtime.freeMemory(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.Totmem") + runtime.totalMemory(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.Percent") + (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.ThreadsRunning") + Thread.activeCount(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.Names") + namesThread.getNameCount(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.SingleT") + tileReader.getLivingTilesCount() + "/" + tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.FileT") + dictReader.getLivingTilesCount() + "/" + dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString(Locale.get("trace.LastMsg") + lastTitleMsg, 0, yc, Graphics.TOP | Graphics.LEFT); yc += la; g.drawString( Locale.get("trace.at") + lastTitleMsgClock, 0, yc, Graphics.TOP | Graphics.LEFT ); return (yc); } private void updatePosition() { if (pc != null) { pc.center = center.copy(); pc.scale = scale; pc.course=course; repaint(); if (locationUpdateListeners != null && !TrackPlayer.isPlaying) { synchronized (locationUpdateListeners) { for (int i = 0; i < locationUpdateListeners.size(); i++) { ((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated(); } } } } } public synchronized void receivePosition(float lat, float lon, float scale) { logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " + (lon * MoreMath.FAC_RADTODEC)); gpsRecenter = false; center.setLatLonRad(lat, lon); this.scale = scale; updatePosition(); } public synchronized void receiveCompassStatus(int status) { } public synchronized void receiveCompass(float direction) { logger.debug("Got compass reading: " + direction); compassDirection = (int) direction; compassDeviated = ((int) direction + compassDeviation + 360) % 360; } public static void updateLastUserActionTime() { lastUserActionTime = System.currentTimeMillis(); } public static long getDurationSinceLastUserActionTime() { return System.currentTimeMillis() - lastUserActionTime; } public void updateCourse(int newcourse) { coursegps = newcourse; if ((newcourse - course)> 180) { course = course + 360; } if ((course-newcourse)> 180) { newcourse = newcourse + 360; } if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) { course = newcourse; } else { course = course + ((newcourse - course)*3)/4 + 360; } while (course > 360) { course -= 360; } } public synchronized void receivePosition(Position pos) { logger.info("New position: " + pos); collected++; if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 && getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs() && isShown() ) { gpsRecenter = true; } if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) { if (pos.type == Position.TYPE_GPS_LASTKNOWN) { if (this.pos.type == Position.TYPE_CELLID) { return; } gpsRecenterInvalid = false; gpsRecenterStale = true; } } this.pos = pos; if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) { gpsRecenterInvalid = false; gpsRecenterStale = false; } if (gpsRecenter) { center.setLatLonDeg(pos.latitude, pos.longitude); speed = (int) (pos.speed * 3.6f); fspeed = pos.speed * 3.6f; if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && !Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) { if (thirdPrevCourse != -1) { updateCourse((int) pos.course); thirdPrevCourse = secondPrevCourse; secondPrevCourse = prevCourse; } else if (prevCourse == -1) { if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } prevCourse = (int) pos.course; } else if (secondPrevCourse == -1) { if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) { secondPrevCourse = prevCourse; } if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } } else { if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) { thirdPrevCourse = secondPrevCourse; secondPrevCourse = prevCourse; updateCourse((int) pos.course); } else { secondPrevCourse = -1; if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } } } prevCourse = (int) pos.course; } else { if (thirdPrevCourse != -1) { if ((Math.abs(prevCourse - secondPrevCourse) < 15 || Math.abs(prevCourse - secondPrevCourse) > 345) && (Math.abs(thirdPrevCourse - secondPrevCourse) < 15 || Math.abs(thirdPrevCourse - secondPrevCourse) > 345)) { } else { updateCourse(thirdPrevCourse); } } prevCourse = -1; secondPrevCourse = -1; thirdPrevCourse = -1; if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) { updateCourse(compassDeviated); } } } if (gpx.isRecordingTrk()) { try { if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179 && pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) { } else { gpx.addTrkPt(pos); } } catch (Exception e) { receiveMessage(e.getMessage()); } } altitude = (int) (pos.altitude); if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM) && gpsRecenter && (isGpsConnected() || TrackPlayer.isPlaying) && autoZoomed && pc.getP() != null && pos.speed != Float.NaN && pos.speed != 0 ) { final float minimumScale = Configuration.getRealBaseScale() / 1.5f; final int minimumSpeed = 20; final float maximumScale = Configuration.getRealBaseScale() * 1.5f; final int maximumSpeed = 160; int speedForScale = speed; float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed); if (newScale < minimumScale) { newScale = minimumScale; } else if (newScale > maximumScale) { newScale = maximumScale; } if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) { float newScale2 = newScale; newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f); newScale = Math.max(newScale2, newScale / 1.5f); } scale = newScale; } updatePosition(); } public synchronized Position getCurrentPosition() { return this.pos; } public synchronized void receiveMessage(String s) { logger.info("Setting title: " + s); currentTitleMsg = s; synchronized (this) { if (setTitleMsgTimeout == 0) { currentTitleMsgOpenCount++; } setTitleMsgTimeout = 3000; } lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false); repaint(); } public void receiveSatellites(Satellite[] sats) { } public synchronized void alert(String title, String message, int timeout) { logger.info("Showing trace alert: " + title + ": " + message); if (timeout == Alert.FOREVER) { timeout = 10000; } currentAlertTitle = title; currentAlertMessage = message; synchronized (this) { if (setAlertTimeout == 0) { currentAlertsOpenCount++; } setAlertTimeout = timeout; } repaint(); } public MIDlet getParent() { return parent; } protected void pointerPressed(int x, int y) { updateLastUserActionTime(); long currTime = System.currentTimeMillis(); pointerDragged = false; pointerDraggedMuch = false; pointerActionDone = false; centerPointerPressedN = center.copy(); if (imageCollector != null) { panProjection=imageCollector.getCurrentProjection(); pickPointStart=panProjection.inverse(x,y, pickPointStart); } else { panProjection = null; } int touchedElementId = tl.getElementIdAtPointer(x, y); if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU) && tl.isAnyActionIdAtPointer(x, y) ) { tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId)); repaint(); } if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) { doubleTap(x, y); return; } pressedPointerTime = currTime; Trace.touchX = x; Trace.touchY = y; if (keyboardLocked) { keyPressed(0); return; } longTapTimerTask = new TimerTask() { public void run() { if (!pointerActionDone) { if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){ longTap(); } } } }; try { GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY); } catch (Exception e) { logger.error(Locale.get("trace.NoLongTapTimerTask") + e.toString()); } } protected void pointerReleased(int x, int y) { if (longTapTimerTask != null) { longTapTimerTask.cancel(); } if (tl.getTouchedElement() != null) { tl.clearTouchedElement(); repaint(); } if (!pointerActionDone && !keyboardLocked) { touchReleaseX = x; touchReleaseY = y; singleTapTimerTask = new TimerTask() { public void run() { if (!keyboardLocked) { singleTap(touchReleaseX, touchReleaseY); } } }; try { GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY); } catch (Exception e) { logger.error(Locale.get("trace.NoSingleTapTimerTask") + e.toString()); } if (pointerDragged) { pointerDragged(x , y); return; } } } protected void pointerDragged (int x, int y) { updateLastUserActionTime(); LayoutElement e = tl.getElementAtPointer(x, y); if (tl.getTouchedElement() != e) { if (longTapTimerTask != null) { longTapTimerTask.cancel(); } tl.clearTouchedElement(); repaint(); } if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) { tl.setTouchedElement(e); repaint(); } if (pointerActionDone) { return; } if (Math.abs(x - Trace.touchX) > 8 || Math.abs(y - Trace.touchY) > 8 ) { pointerDraggedMuch = true; pressedPointerTime = 0; } if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) { if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU && x - touchX > getWidth() / 4 ) { commandAction(TOGGLE_KEY_LOCK_CMD); pointerActionDone = true; } return; } if (keyboardLocked) { return; } pointerDragged = true; if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) { return; } if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) { pickPointEnd=panProjection.inverse(x,y, pickPointEnd); center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat); center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon); imageCollector.newDataReady(); gpsRecenter = false; } } private void singleTap(int x, int y) { pointerActionDone = true; if (tl.getElementIdAtPointer(touchX, touchY) < 0) { if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) { if (pointerDraggedMuch) { return; } logger.debug("single tap map"); if (!tl.bigOnScreenButtons) { tl.setOnScreenButtonSize(true); final long BIGBUTTON_DURATION = 5000; bigButtonTimerTask = new TimerTask() { public void run() { if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) { tl.setOnScreenButtonSize(false); requestRedraw(); bigButtonTimerTask.cancel(); } } }; try { GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500); } catch (Exception e) { logger.error("Error scheduling bigButtonTimerTask: " + e.toString()); } } } repaint(); } else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) { tl.clearTouchedElement(); int actionId = tl.getActionIdAtPointer(x, y); if (actionId > 0) { logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY); if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) { if (actionId == ZOOM_IN_CMD) { actionId = PAN_RIGHT2_CMD; } else if (actionId == ZOOM_OUT_CMD) { actionId = PAN_LEFT2_CMD; } } else if (manualRotationMode) { if (actionId == ZOOM_IN_CMD) { actionId = PAN_LEFT2_CMD; } else if (actionId == ZOOM_OUT_CMD) { actionId = PAN_RIGHT2_CMD; } } else if (TrackPlayer.isPlaying) { if (actionId == ZOOM_IN_CMD) { actionId = PAN_RIGHT2_CMD; } else if (actionId == ZOOM_OUT_CMD) { actionId = PAN_LEFT2_CMD; } } commandAction(actionId); repaint(); } } } private void doubleTap(int x, int y) { if (tl.getElementIdAtPointer(touchX, touchY) < 0) { if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) { if (singleTapTimerTask != null) { singleTapTimerTask.cancel(); } if (pointerDraggedMuch) { return; } logger.debug("double tap map"); pointerActionDone = true; commandAction(ZOOM_IN_CMD); } repaint(); return; } else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){ int actionId = tl.getActionIdDoubleAtPointer(x, y); logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x); if (actionId > 0) { if (singleTapTimerTask != null) { singleTapTimerTask.cancel(); } pointerActionDone = true; commandAction(actionId); tl.clearTouchedElement(); repaint(); return; } else { singleTap(x, y); } } } private void longTap() { if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) { if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) { pointerActionDone = true; logger.debug("long tap map"); pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd); center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat); center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon); Position oPos = new Position(center.radlat, center.radlon, 0.0f, 0.0f, 0.0f, 0, 0); imageCollector.newDataReady(); gpsRecenter = false; commandAction(ONLINE_INFO_CMD); } return; } else { int actionId = tl.getActionIdLongAtPointer(touchX, touchY); if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) { tl.clearTouchedElement(); repaint(); pointerActionDone = true; logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY); commandAction(actionId); } } } public Command getDataScreenCommand() { return CMDS[DATASCREEN_CMD]; } public Tile getDict(byte zl) { return tiles[zl]; } public void setDict(Tile dict, byte zl) { tiles[zl] = dict; if (zl == 0) { Configuration.getStartupPos(center); if (center.radlat == 0.0f && center.radlon == 0.0f) { dict.getCenter(center); } if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) { Node destNode = new Node(); Configuration.getDestPos(destNode); setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon)); } if (pc != null) { pc.center = center.copy(); pc.scale = scale; pc.course = course; } } updatePosition(); } public void setBaseTilesRead(boolean read) { baseTilesRead = read; } public void receiveStatistics(int[] statRecord, byte quality) { this.btquality = quality; this.statRecord = statRecord; repaint(); } public synchronized void locationDecoderEnd() { logger.info("enter locationDecoderEnd"); if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) { if (Legend.isValid) { GpsMid.mNoiseMaker.playSound("DISCONNECT"); } } removeCommand(CMDS[DISCONNECT_GPS_CMD]); if (locationProducer == null) { logger.info("leave locationDecoderEnd no producer"); return; } locationProducer = null; notify(); addCommand(CMDS[CONNECT_GPS_CMD]); logger.info("end locationDecoderEnd"); } public void receiveStatus(byte status, int satsReceived) { if (status != LocationMsgReceiver.STATUS_ON && status != LocationMsgReceiver.STATUS_2D && status != LocationMsgReceiver.STATUS_3D && status != LocationMsgReceiver.STATUS_DGPS) { prevCourse = -1; secondPrevCourse = -1; thirdPrevCourse = -1; } solution = status; solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived); repaint(); if (locationUpdateListeners != null && !TrackPlayer.isPlaying) { synchronized (locationUpdateListeners) { for (int i = 0; i < locationUpdateListeners.size(); i++) { ((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated(); } } } } public String getName(int idx) { if (idx < 0) { return null; } return namesThread.getName(idx); } public String getUrl(int idx) { if (idx < 0) { return null; } return urlsThread.getUrl(idx); } public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) { return namesThread.fulltextSearch(snippet, cmi); } public void requestRedraw() { repaint(); } public void newDataReady() { if (imageCollector != null) { imageCollector.newDataReady(); } } public void show() { Legend.freeDrawnWayAndAreaSearchImages(); GpsMid.getInstance().show(this); setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)); updateLastUserActionTime(); repaint(); } public void recreateTraceLayout() { tl = new TraceLayout(0, 0, getWidth(), getHeight()); } public void resetSize() { sizeChanged(getWidth(), getHeight()); } public void locationDecoderEnd(String msg) { receiveMessage(msg); locationDecoderEnd(); } public PositionMark getDestination() { return dest; } public void setDestination(RoutePositionMark dest) { endRouting(); this.dest = dest; pc.dest = dest; if (dest != null) { logger.info("Setting destination to " + dest.toString()); if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) { commandAction(SHOW_DEST_CMD); } if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) { Configuration.setDestPos(new Node(dest.lat, dest.lon, true)); Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true); } movedAwayFromDest = false; } else { Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false); logger.info("Setting destination to null"); } } public void endRouting() { RouteInstructions.initialRecalcDone = false; RouteInstructions.icCountOffRouteDetected = 0; RouteInstructions.routeInstructionsHeight = 0; RouteInstructions.abortRouteLineProduction(); setRoute(null); setRouteNodes(null); } public void setRoute(Vector route) { synchronized(this) { this.route = route; } if (this.route != null) { RouteInstructions.resetOffRoute(this.route, center); if (ri == null) { ri = new RouteInstructions(this); } if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) { resumeImageCollectorAfterRouteCalc(); } ri.newRoute(this.route); oldRecalculationTime = System.currentTimeMillis(); } resumeImageCollectorAfterRouteCalc(); routeCalc=false; routeEngine=null; } private void resumeImageCollectorAfterRouteCalc() { try { if (imageCollector == null) { startImageCollector(); imageCollector.resume(); } else if (imageCollector != null) { imageCollector.newDataReady(); } repaint(); } catch (Exception e) { logger.exception(Locale.get("trace.InTraceResumeImageCollector"), e); } } public void dropCache() { tileReader.dropCache(); dictReader.dropCache(); System.gc(); namesThread.dropCache(); urlsThread.dropCache(); System.gc(); if (gpx != null) { gpx.dropCache(); } } public QueueDataReader getDataReader() { return tileReader; } public QueueDictReader getDictReader() { return dictReader; } public Vector getRouteNodes() { return routeNodes; } public void setRouteNodes(Vector routeNodes) { this.routeNodes = routeNodes; } protected void hideNotify() { logger.debug("Hide notify has been called, screen will no longer be updated"); if (imageCollector != null) { imageCollector.suspend(); } } protected void showNotify() { logger.debug("Show notify has been called, screen will be updated again"); if (imageCollector != null) { imageCollector.resume(); imageCollector.newDataReady(); } } public Vector getRoute() { return route; } public void actionCompleted() { boolean reAddCommands = true; if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) { addAllCommands(); } } public void showIconMenu() { if (traceIconMenu == null) { traceIconMenu = new TraceIconMenu(this, this); } traceIconMenu.show(); } public static void uncacheIconMenu() { if (traceIconMenu != null) { logger.trace("uncaching TraceIconMenu"); } traceIconMenu = null; } public void recreateAndShowIconMenu() { uncacheIconMenu(); showIconMenu(); } public void performIconAction(int actionId) { show(); updateLastUserActionTime(); if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) { logger.info("low mem: Uncaching traceIconMenu"); uncacheIconMenu(); } if (actionId != IconActionPerformer.BACK_ACTIONID) { commandAction(actionId); } } public static String showDistance(int meters) { return showDistance(meters, DISTANCE_GENERIC); } public static String showDistance(int meters, int type) { if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) { if (type == DISTANCE_UNKNOWN) { return "???" + Locale.get("guitacho.m"); } int MajorUnit = meters / 1000; int MinorUnit = meters % 1000; String MinorShort = Integer.toString((int)MinorUnit / 100); if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) { if (MajorUnit == 0) { return Integer.toString(MinorUnit) + Locale.get("guitacho.m"); } else { return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km"); } } else { return Integer.toString(meters) + Locale.get("guitacho.m"); } } else { if (type == DISTANCE_UNKNOWN) { return "???" + Locale.get("guitacho.yd"); } int MajorUnit = (int)(meters / 1609.344f); int MinorUnit = (int)(meters % 1609.344f + 0.5f); String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f)); if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) { if (MajorUnit == 0) { return Integer.toString(MinorUnit) + Locale.get("guitacho.yd"); } else { return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi"); } } else { return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd"); } } } }
public void testDeployNonSnapshotRemoteRepo() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/NPandayIT0029" ); Verifier verifier = getVerifier( testDir ); verifier.executeGoal( "deploy" ); verifier.assertFilePresent( new File( testDir, getAssemblyFile( "NPandayIT0029", "1.0.0.0", "dll" ) ).getAbsolutePath() ); String path = "target/remoteSnapshotRepo/snapshots/NPandayIT0029/NPandayIT0029/1.0/NPandayIT0029-1.0"; verifier.assertFilePresent( new File( testDir, path + ".dll" ).getAbsolutePath() ); verifier.assertFilePresent( new File( testDir, path + ".pom" ).getAbsolutePath() ); verifier.verifyErrorFreeLog(); verifier.resetStreams(); }
public void testDeployNonSnapshotRemoteRepo() throws Exception { File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/NPandayIT0029" ); Verifier verifier = getVerifier( testDir ); verifier.executeGoal( "deploy" ); verifier.assertFilePresent( new File( testDir, getAssemblyFile( "NPandayIT0029", "1.0.0.0", "dll" ) ).getAbsolutePath() ); String path = "target/remoteRepo/NPandayIT0029/NPandayIT0029/1.0/NPandayIT0029-1.0"; verifier.assertFilePresent( new File( testDir, path + ".dll" ).getAbsolutePath() ); verifier.assertFilePresent( new File( testDir, path + ".pom" ).getAbsolutePath() ); verifier.verifyErrorFreeLog(); verifier.resetStreams(); }
public void test() { Callable<SystemInfo> processor = null; final String osSystem = System.getProperty("os.name"); if (osSystem.toLowerCase().indexOf("windows") > -1) { processor = new WindowSystemMonitorProcessor(); } else { processor = new LinuxSystemMonitorProcessor(); } try { processor.call(); } catch (Exception e) { e.printStackTrace(); } }
public void test() { Callable<SystemInfo> processor = null; final String osSystem = System.getProperty("os.name"); if (osSystem.toLowerCase().indexOf("windows") > -1) { processor = new WindowSystemMonitorProcessor(); } else { processor = new LinuxSystemMonitorProcessor(); } try { SystemInfo info = processor.call(); System.out.println("System info:" + info); } catch (Exception e) { e.printStackTrace(); } }
public void aupdate(float time) { if(time > len) time = len; this.time = time; reset(); for(int i = 0; i < tracks.length; i++) { Track t = tracks[i]; if((t == null) || (t.frames.length == 0)) continue; if(t.frames.length == 1) { qset(lrot[i], t.frames[0].rot); vset(lpos[i], t.frames[0].trans); } else { Track.Frame cf, nf; int l = 0, r = t.frames.length; while(true) { int c = l + ((r - l) >> 1); float ct = t.frames[c].time; float nt = (c < t.frames.length - 1)?(t.frames[c + 1].time):len; if(ct > time) { r = c; } else if(nt < time) { l = c + 1; } else { cf = t.frames[c]; nf = t.frames[(c + 1) % t.frames.length]; break; } } float d = (time - cf.time) / (nf.time - cf.time); qqslerp(lrot[i], cf.rot, nf.rot, d); lpos[i][0] = cf.trans[0] + ((nf.trans[0] - cf.trans[0]) * d); lpos[i][1] = cf.trans[1] + ((nf.trans[1] - cf.trans[1]) * d); lpos[i][2] = cf.trans[2] + ((nf.trans[2] - cf.trans[2]) * d); } } }
public void aupdate(float time) { if(time > len) time = len; this.time = time; reset(); for(int i = 0; i < tracks.length; i++) { Track t = tracks[i]; if((t == null) || (t.frames.length == 0)) continue; if(t.frames.length == 1) { qset(lrot[i], t.frames[0].rot); vset(lpos[i], t.frames[0].trans); } else { Track.Frame cf, nf; float ct, nt; int l = 0, r = t.frames.length; while(true) { int c = l + ((r - l) >> 1); ct = t.frames[c].time; nt = (c < t.frames.length - 1)?(t.frames[c + 1].time):len; if(ct > time) { r = c; } else if(nt < time) { l = c + 1; } else { cf = t.frames[c]; nf = t.frames[(c + 1) % t.frames.length]; break; } } float d = (time - ct) / (nt - ct); qqslerp(lrot[i], cf.rot, nf.rot, d); lpos[i][0] = cf.trans[0] + ((nf.trans[0] - cf.trans[0]) * d); lpos[i][1] = cf.trans[1] + ((nf.trans[1] - cf.trans[1]) * d); lpos[i][2] = cf.trans[2] + ((nf.trans[2] - cf.trans[2]) * d); } } }
public byte[] getResponse() { byte[] copy = new byte[response.length]; System.arraycopy( response, 0, copy, 0, response.length ); return copy; }
public byte[] getResponse() { if ( response == null ) { return null; } byte[] copy = new byte[response.length]; System.arraycopy( response, 0, copy, 0, response.length ); return copy; }
private void initialize( RAInputStream rowExprsIs, RAInputStream rowLenIs, int rowCount ) throws DataException { try { IOUtil.readInt( rowExprsIs ); int exprCount = IOUtil.readInt( rowExprsIs ); this.exprKeys = new ArrayList(); this.rowExprsDis = new DataInputStream( rowExprsIs ); for( int i = 0; i < exprCount; i++ ) { this.exprKeys.add( IOUtil.readString( this.rowExprsDis ) ); } this.metaOffset = IOUtil.INT_LENGTH + IOUtil.readInt( this.rowExprsDis ) + IOUtil.INT_LENGTH; } catch ( IOException e ) { throw new DataException( ResourceConstants.RD_LOAD_ERROR, e, "Result Data" ); } this.rowExprsIs = rowExprsIs; this.rowLenIs = rowLenIs; this.currRowIndex = -1; this.lastRowIndex = -1; this.currRowLenReadIndex = -1; this.rowCount = rowCount; this.rowIDMap = new BasicCachedArray( rowCount ); }
private void initialize( RAInputStream rowExprsIs, RAInputStream rowLenIs, int rowCount ) throws DataException { try { IOUtil.readInt( rowExprsIs ); int exprCount = IOUtil.readInt( rowExprsIs ); this.exprKeys = new ArrayList(); this.rowExprsDis = new DataInputStream( rowExprsIs ); for( int i = 0; i < exprCount; i++ ) { this.exprKeys.add( IOUtil.readString( this.rowExprsDis ) ); } this.metaOffset = IOUtil.INT_LENGTH + IOUtil.readInt( this.rowExprsDis ) + IOUtil.INT_LENGTH; } catch ( IOException e ) { throw new DataException( ResourceConstants.RD_LOAD_ERROR, e, "Result Data" ); } this.rowExprsIs = rowExprsIs; this.rowLenIs = rowLenIs; this.currRowIndex = -1; this.lastRowIndex = -1; this.currRowLenReadIndex = 0; this.rowCount = rowCount; this.rowIDMap = new BasicCachedArray( rowCount ); }
public void eventsArePublishedByDefault() throws Exception { setContext(CONTEXT, "3.0"); AuthListener listener = new AuthListener(); appContext.addApplicationListener(listener); appContext.refresh(); ProviderManager pm = (ProviderManager) appContext.getBeansOfType(ProviderManager.class).values().toArray()[0]; Object eventPublisher = FieldUtils.getFieldValue(pm, "eventPublisher"); assertNotNull(eventPublisher); assertTrue(eventPublisher instanceof DefaultAuthenticationEventPublisher); pm.authenticate(new UsernamePasswordAuthenticationToken("bob", "bobspassword")); assertEquals(1, listener.events.size()); }
public void eventsArePublishedByDefault() throws Exception { setContext(CONTEXT, "3.0"); AuthListener listener = new AuthListener(); appContext.addApplicationListener(listener); ProviderManager pm = (ProviderManager) appContext.getBeansOfType(ProviderManager.class).values().toArray()[0]; Object eventPublisher = FieldUtils.getFieldValue(pm, "eventPublisher"); assertNotNull(eventPublisher); assertTrue(eventPublisher instanceof DefaultAuthenticationEventPublisher); pm.authenticate(new UsernamePasswordAuthenticationToken("bob", "bobspassword")); assertEquals(1, listener.events.size()); }
public void init(Broker broker,Settings config) throws InitException { super.init(broker,config); this.broker = broker; log = broker.getLog("resource","DelegatingTemplateProvider"); String factoryClass = config.getSetting("TemplateLoaderFactory",""); log.info("DelegatingTemplateProvider: Using TemplateLoaderFactory "+factoryClass); factory = createFactory(factoryClass); List loaders = new ArrayList(); if (config.getBooleanSetting("DelegatingTemplateProvider.EmulateTemplatePath",false)) { if (config.getSetting("TemplatePath").length() > 0) { TemplateLoader loader = new TemplatePathTemplateLoader(); loader.init(broker,config); loader.setConfig(""); loaders.add(loader); } } int i = 0; String loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1))); while (loader != null) { loaders.add(factory.getTemplateLoader(broker,loader)); i++; loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1))); } templateLoaders = new TemplateLoader[loaders.size()]; loaders.toArray(templateLoaders); }
public void init(Broker broker,Settings config) throws InitException { super.init(broker,config); this.broker = broker; log = broker.getLog("resource","DelegatingTemplateProvider"); String factoryClass = config.getSetting("TemplateLoaderFactory",""); log.info("DelegatingTemplateProvider: Using TemplateLoaderFactory "+factoryClass); factory = createFactory(factoryClass); List loaders = new ArrayList(); if (config.getBooleanSetting("DelegatingTemplateProvider.EmulateTemplatePath",false)) { if (config.getSetting("TemplatePath","").length() > 0) { TemplateLoader loader = new TemplatePathTemplateLoader(); loader.init(broker,config); loader.setConfig(""); loaders.add(loader); } } int i = 0; String loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1))); while (loader != null) { loaders.add(factory.getTemplateLoader(broker,loader)); i++; loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1))); } templateLoaders = new TemplateLoader[loaders.size()]; loaders.toArray(templateLoaders); }
protected List getChildElements(Node srcNode, String tagName) { List childElements = new ArrayList(); NodeList childNodes = srcNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node curNode = childNodes.item(i); if (curNode.getNodeType() == Node.ELEMENT_NODE) { String curNodeName = curNode.getLocalName(); if (curNode != null && curNodeName.equals(tagName)) { childElements.add(curNode); } } } return childElements; }
protected List getChildElements(Node srcNode, String tagName) { List childElements = new ArrayList(); NodeList childNodes = srcNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node curNode = childNodes.item(i); if (curNode.getNodeType() == Node.ELEMENT_NODE) { String curNodeName = curNode.getLocalName(); if (curNodeName != null && curNodeName.equals(tagName)) { childElements.add(curNode); } } } return childElements; }
public static MultiInputPanel getConnectionPanel() { int LENGTH = 20; MultiInputPanel connectionMP = new MultiInputPanel(I18N.tr("Connection parameters")); connectionMP.addInput(CONNAME, I18N.tr("Connexion name"), I18N.tr("MyConnexion"), new TextBoxType(LENGTH)); connectionMP.addInput(DBTYPE, I18N.tr("Type of database"), getDriverInput()); connectionMP.addInput(HOST, I18N.tr("Host"), "127.0.0.1", new TextBoxType(LENGTH)); connectionMP.addInput(PORT, I18N.tr("Default port"), "0", new TextBoxType(LENGTH)); connectionMP.addInput(DBNAME, I18N.tr("Database name"), "database_name", new TextBoxType(LENGTH)); connectionMP.addInput(SSL, I18N.tr("SSL"), new CheckBoxChoice(false)); connectionMP.addValidation(new MIPValidation() { @Override public String validate(MultiInputPanel mid) { if (mid.getInput(CONNAME).isEmpty()) { return I18N.tr("Please specify a connexion name"); } if (mid.getInput(DBNAME).isEmpty()) { return I18N.tr("The database name is mandatory"); } String host = mid.getInput(HOST); if (host.isEmpty()) { return I18N.tr("The host cannot be null"); } String port = mid.getInput(PORT); if (port.isEmpty()) { return I18N.tr("The port field is mandatory"); } else { try { Integer portNumber = Integer.valueOf(port); if (!(portNumber >= 0 && portNumber <= 32767)) { return I18N.tr("The port number must be comprise between 0 and 32767"); } } catch (NumberFormatException e) { return I18N.tr("Cannot format the port code into an int"); } } return null; } }); return connectionMP; }
public static MultiInputPanel getConnectionPanel() { int LENGTH = 20; MultiInputPanel connectionMP = new MultiInputPanel(I18N.tr("Connection parameters")); connectionMP.addInput(CONNAME, I18N.tr("Connexion name"), I18N.tr("MyConnexion"), new TextBoxType(LENGTH)); connectionMP.addInput(DBTYPE, I18N.tr("Type of database"), getDriverInput()); connectionMP.addInput(HOST, I18N.tr("Host"), "127.0.0.1", new TextBoxType(LENGTH)); connectionMP.addInput(PORT, I18N.tr("Default port"), "0", new TextBoxType(LENGTH)); connectionMP.addInput(DBNAME, I18N.tr("Database name"), "database_name", new TextBoxType(LENGTH)); connectionMP.addInput(SSL, I18N.tr("SSL"), new CheckBoxChoice(false)); connectionMP.addValidation(new MIPValidation() { @Override public String validate(MultiInputPanel mid) { if (mid.getInput(CONNAME).isEmpty()) { return I18N.tr("Please specify a connexion name"); } if (mid.getInput(DBNAME).isEmpty()) { return I18N.tr("The database name is mandatory"); } String host = mid.getInput(HOST); if (host.isEmpty()) { return I18N.tr("The host cannot be null"); } String port = mid.getInput(PORT); if (port.isEmpty()) { return I18N.tr("The port field is mandatory"); } else { try { Integer portNumber = Integer.valueOf(port); if (!(portNumber >= 0 && portNumber <= 32767)) { return I18N.tr("The port number must lie between 0 and 32767."); } } catch (NumberFormatException e) { return I18N.tr("Cannot format the port code into an int"); } } return null; } }); return connectionMP; }
public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed) throws IOException { if (from.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(from.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); if (autocompletes.size() > 1) return new QueryConnectionsResult(autocompletes, null, null); from = autocompletes.get(0); } if (via != null && via.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(via.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); if (autocompletes.size() > 1) return new QueryConnectionsResult(null, autocompletes, null); via = autocompletes.get(0); } if (to.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(to.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); if (autocompletes.size() > 1) return new QueryConnectionsResult(null, null, autocompletes); to = autocompletes.get(0); } final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm"); final String request = "<ConReq>" + "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" + (via != null ? "<Via>" + location(via) + "</Via>" : "") + "<Dest>" + location(to) + "</Dest>" + "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" + "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" + "</ConReq>"; InputStream is = null; try { is = ParserUtils.scrapeInputStream(apiUri, wrap(request)); final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); final XmlPullParser pp = factory.newPullParser(); pp.setInput(is, DEFAULT_ENCODING); assertResC(pp); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "ConRes"); XmlPullUtil.enter(pp); if (pp.getName().equals("Err")) { final String code = XmlPullUtil.attr(pp, "code"); if (code.equals("K9380")) return QueryConnectionsResult.TOO_CLOSE; if (code.equals("K9220")) return QueryConnectionsResult.NO_CONNECTIONS; if (code.equals("K890")) return QueryConnectionsResult.NO_CONNECTIONS; throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text")); } XmlPullUtil.require(pp, "ConResCtxt"); final String sessionId = XmlPullUtil.text(pp); XmlPullUtil.require(pp, "ConnectionList"); XmlPullUtil.enter(pp); final List<Connection> connections = new ArrayList<Connection>(); while (XmlPullUtil.test(pp, "Connection")) { final String id = XmlPullUtil.attr(pp, "id"); XmlPullUtil.enter(pp); while (pp.getName().equals("RtStateList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Overview"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Date"); final Calendar currentDate = new GregorianCalendar(); currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp))); XmlPullUtil.exit(pp); XmlPullUtil.require(pp, "ConSectionList"); XmlPullUtil.enter(pp); final List<Connection.Part> parts = new ArrayList<Connection.Part>(4); Date firstDepartureTime = null; Date lastArrivalTime = null; while (XmlPullUtil.test(pp, "ConSection")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Departure"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location departure; if (pp.getName().equals("Station")) departure = parseStation(pp); else if (pp.getName().equals("Poi")) departure = parsePoi(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Dep"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String departurePos = XmlPullUtil.text(pp).trim(); if (departurePos.length() == 0) departurePos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); String line = null; String direction = null; int min = 0; final String tag = pp.getName(); if (tag.equals("Journey")) { XmlPullUtil.enter(pp); while (pp.getName().equals("JHandle")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "JourneyAttributeList"); XmlPullUtil.enter(pp); String name = null; String category = null; String longCategory = null; while (XmlPullUtil.test(pp, "JourneyAttribute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Attribute"); final String attrName = XmlPullUtil.attr(pp, "type"); XmlPullUtil.enter(pp); final Map<String, String> attributeVariants = parseAttributeVariants(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if ("NAME".equals(attrName)) { name = attributeVariants.get("NORMAL"); } else if ("CATEGORY".equals(attrName)) { category = attributeVariants.get("NORMAL"); longCategory = attributeVariants.get("LONG"); } else if ("DIRECTION".equals(attrName)) { direction = attributeVariants.get("NORMAL"); } } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); line = _normalizeLine(category, name, longCategory); } else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Duration"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); min = parseDuration(XmlPullUtil.text(pp).substring(3, 8)); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); } else { throw new IllegalStateException("cannot handle: " + pp.getName()); } XmlPullUtil.require(pp, "Arrival"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location arrival; if (pp.getName().equals("Station")) arrival = parseStation(pp); else if (pp.getName().equals("Poi")) arrival = parsePoi(pp); else if (pp.getName().equals("Address")) arrival = parseAddress(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Arr"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String arrivalPos = XmlPullUtil.text(pp).trim(); if (arrivalPos.length() == 0) arrivalPos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if (min == 0 || line != null) { parts.add(new Connection.Trip(line, lineColors(line), 0, direction, departureTime, departurePos, departure.id, departure.name, arrivalTime, arrivalPos, arrival.id, arrival.name)); } else { if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway) { final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1); parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure, arrival.id, arrival.name)); } else { parts.add(new Connection.Footway(min, departure.id, departure.name, arrival.id, arrival.name)); } } if (firstDepartureTime == null) firstDepartureTime = departureTime; lastArrivalTime = arrivalTime; } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, null, null, 0, null, 0, null, parts)); } XmlPullUtil.exit(pp); return new QueryConnectionsResult(null, from, via, to, null, null, connections); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } catch (final SocketTimeoutException x) { throw new RuntimeException(x); } catch (final ParseException x) { throw new RuntimeException(x); } finally { if (is != null) is.close(); } }
public QueryConnectionsResult queryConnections(Location from, Location via, Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed) throws IOException { if (from.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(from.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); if (autocompletes.size() > 1) return new QueryConnectionsResult(autocompletes, null, null); from = autocompletes.get(0); } if (via != null && via.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(via.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); if (autocompletes.size() > 1) return new QueryConnectionsResult(null, autocompletes, null); via = autocompletes.get(0); } if (to.type == LocationType.ANY) { final List<Location> autocompletes = autocompleteStations(to.name); if (autocompletes.isEmpty()) return new QueryConnectionsResult(QueryConnectionsResult.Status.NO_CONNECTIONS); if (autocompletes.size() > 1) return new QueryConnectionsResult(null, null, autocompletes); to = autocompletes.get(0); } final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm"); final String request = "<ConReq>" + "<Start>" + location(from) + "<Prod bike=\"0\" couchette=\"0\" direct=\"0\" sleeper=\"0\"/></Start>" + (via != null ? "<Via>" + location(via) + "</Via>" : "") + "<Dest>" + location(to) + "</Dest>" + "<ReqT a=\"" + (dep ? 0 : 1) + "\" date=\"" + DATE_FORMAT.format(date) + "\" time=\"" + TIME_FORMAT.format(date) + "\"/>" + "<RFlags b=\"0\" chExtension=\"0\" f=\"4\" sMode=\"N\"/>" + "</ConReq>"; InputStream is = null; try { is = ParserUtils.scrapeInputStream(apiUri, wrap(request)); final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); final XmlPullParser pp = factory.newPullParser(); pp.setInput(is, DEFAULT_ENCODING); assertResC(pp); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "ConRes"); XmlPullUtil.enter(pp); if (pp.getName().equals("Err")) { final String code = XmlPullUtil.attr(pp, "code"); if (code.equals("K9380")) return QueryConnectionsResult.TOO_CLOSE; if (code.equals("K9220")) return QueryConnectionsResult.NO_CONNECTIONS; if (code.equals("K890")) return QueryConnectionsResult.NO_CONNECTIONS; throw new IllegalStateException("error " + code + " " + XmlPullUtil.attr(pp, "text")); } XmlPullUtil.require(pp, "ConResCtxt"); final String sessionId = XmlPullUtil.text(pp); XmlPullUtil.require(pp, "ConnectionList"); XmlPullUtil.enter(pp); final List<Connection> connections = new ArrayList<Connection>(); while (XmlPullUtil.test(pp, "Connection")) { final String id = XmlPullUtil.attr(pp, "id"); XmlPullUtil.enter(pp); while (pp.getName().equals("RtStateList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Overview"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Date"); final Calendar currentDate = new GregorianCalendar(); currentDate.setTime(DATE_FORMAT.parse(XmlPullUtil.text(pp))); XmlPullUtil.exit(pp); XmlPullUtil.require(pp, "ConSectionList"); XmlPullUtil.enter(pp); final List<Connection.Part> parts = new ArrayList<Connection.Part>(4); Date firstDepartureTime = null; Date lastArrivalTime = null; while (XmlPullUtil.test(pp, "ConSection")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Departure"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location departure; if (pp.getName().equals("Station")) departure = parseStation(pp); else if (pp.getName().equals("Poi")) departure = parsePoi(pp); else if (pp.getName().equals("Address")) departure = parseAddress(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Dep"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date departureTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String departurePos = XmlPullUtil.text(pp).trim(); if (departurePos.length() == 0) departurePos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); String line = null; String direction = null; int min = 0; final String tag = pp.getName(); if (tag.equals("Journey")) { XmlPullUtil.enter(pp); while (pp.getName().equals("JHandle")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "JourneyAttributeList"); XmlPullUtil.enter(pp); String name = null; String category = null; String longCategory = null; while (XmlPullUtil.test(pp, "JourneyAttribute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Attribute"); final String attrName = XmlPullUtil.attr(pp, "type"); XmlPullUtil.enter(pp); final Map<String, String> attributeVariants = parseAttributeVariants(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if ("NAME".equals(attrName)) { name = attributeVariants.get("NORMAL"); } else if ("CATEGORY".equals(attrName)) { category = attributeVariants.get("NORMAL"); longCategory = attributeVariants.get("LONG"); } else if ("DIRECTION".equals(attrName)) { direction = attributeVariants.get("NORMAL"); } } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); line = _normalizeLine(category, name, longCategory); } else if (tag.equals("Walk") || tag.equals("Transfer") || tag.equals("GisRoute")) { XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Duration"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); min = parseDuration(XmlPullUtil.text(pp).substring(3, 8)); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); } else { throw new IllegalStateException("cannot handle: " + pp.getName()); } XmlPullUtil.require(pp, "Arrival"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "BasicStop"); XmlPullUtil.enter(pp); while (pp.getName().equals("StAttrList")) XmlPullUtil.next(pp); Location arrival; if (pp.getName().equals("Station")) arrival = parseStation(pp); else if (pp.getName().equals("Poi")) arrival = parsePoi(pp); else if (pp.getName().equals("Address")) arrival = parseAddress(pp); else throw new IllegalStateException("cannot parse: " + pp.getName()); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "Arr"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Time"); final Date arrivalTime = parseTime(currentDate, XmlPullUtil.text(pp)); XmlPullUtil.require(pp, "Platform"); XmlPullUtil.enter(pp); XmlPullUtil.require(pp, "Text"); String arrivalPos = XmlPullUtil.text(pp).trim(); if (arrivalPos.length() == 0) arrivalPos = null; XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); if (min == 0 || line != null) { parts.add(new Connection.Trip(line, lineColors(line), 0, direction, departureTime, departurePos, departure.id, departure.name, arrivalTime, arrivalPos, arrival.id, arrival.name)); } else { if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway) { final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1); parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departureId, lastFootway.departure, arrival.id, arrival.name)); } else { parts.add(new Connection.Footway(min, departure.id, departure.name, arrival.id, arrival.name)); } } if (firstDepartureTime == null) firstDepartureTime = departureTime; lastArrivalTime = arrivalTime; } XmlPullUtil.exit(pp); XmlPullUtil.exit(pp); connections.add(new Connection(id, null, firstDepartureTime, lastArrivalTime, null, null, 0, null, 0, null, parts)); } XmlPullUtil.exit(pp); return new QueryConnectionsResult(null, from, via, to, null, null, connections); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } catch (final SocketTimeoutException x) { throw new RuntimeException(x); } catch (final ParseException x) { throw new RuntimeException(x); } finally { if (is != null) is.close(); } }
public void run() { synchronized (JavaFXPreviewTopComponent.this) { if (pr != null) { pr.destroy(); timer = 0; task.schedule(150); return; } } if (oldD != null) { oldD.removePropertyChangeListener(JavaFXPreviewTopComponent.this); oldD = null; } Node[] sel = TopComponent.getRegistry().getActivatedNodes(); if (sel.length == 1) { DataObject d = sel[0].getLookup().lookup(DataObject.class); if (d != null) { FileObject f = d.getPrimaryFile(); if (f.isData()) bi = null; if ("fx".equals(f.getExt())) { d.addPropertyChangeListener(JavaFXPreviewTopComponent.this); oldD = d; Project p = FileOwnerQuery.getOwner(f); if (p instanceof JavaFXProject) { PropertyEvaluator ev = ((JavaFXProject)p).evaluator(); FileObject srcRoots[] = ((JavaFXProject)p).getFOSourceRoots(); StringBuffer src = new StringBuffer(); String className = null; for (FileObject srcRoot : srcRoots) { if (src.length() > 0) src.append(';'); src.append(FileUtil.toFile(srcRoot).getAbsolutePath()); if (FileUtil.isParentOf(srcRoot, f)) { className = FileUtil.getRelativePath(srcRoot, f); className = className.substring(0, className.length() - 3).replace('/', '.'); } } String cp = ev.getProperty("javac.classpath"); cp = cp == null ? "" : cp.trim(); String enc = ev.getProperty("source.encoding"); if (enc == null || enc.trim().length() == 0) enc = "UTF-8"; File basedir = FileUtil.toFile(p.getProjectDirectory()); File build = PropertyUtils.resolveFile(basedir, "build/compiled"); ArrayList<String> args = new ArrayList<String>(); args.add(fxHome + "/bin/javafxc" + (Utilities.isWindows() ? ".exe" : "")); args.add("-cp"); args.add(build.getAbsolutePath() + File.pathSeparator + cp); args.add("-sourcepath"); args.add(src.toString()); args.add("-d"); args.add(build.getAbsolutePath()); args.add("-encoding"); args.add(enc.trim()); args.add(FileUtil.toFile(f).getAbsolutePath()); try { build.mkdirs(); log.info(args.toString()); synchronized (JavaFXPreviewTopComponent.this) { pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir); } if (log.isLoggable(Level.INFO)) { ByteArrayOutputStream err = new ByteArrayOutputStream(); InputStream in = pr.getErrorStream(); try { FileUtil.copy(in, err); } catch (IOException e) { log.severe(e.getLocalizedMessage()); } finally { try { in.close(); } catch (IOException e) {} } log.info(err.toString()); } pr.waitFor(); String jvmargs = ev.getProperty("run.jvmargs"); String appargs = ev.getProperty("application.args"); if (pr.exitValue() == 0) { args = new ArrayList<String>(); args.add(fxHome + "/bin/javafx" + (Utilities.isWindows() ? ".exe" : "")); args.add("-javaagent:" + previewLib.getAbsolutePath()); args.add("-Xbootclasspath/p:" + previewLib.getAbsolutePath()); args.add("-Dcom.apple.backgroundOnly=true"); args.add("-Dapple.awt.UIElement=true"); if (jvmargs != null) for (String ja : jvmargs.trim().split("\\s+")) if (ja.length()>0) args.add(ja); args.add("-cp"); args.add(src.toString() + File.pathSeparator + build.getAbsolutePath() + File.pathSeparator + cp); args.add(className); if (appargs != null) for (String aa : appargs.trim().split("\\s+")) args.add(aa); log.info(args.toString()); synchronized (JavaFXPreviewTopComponent.this) { pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir); } if (log.isLoggable(Level.INFO)) { RequestProcessor.getDefault().execute(new Runnable() { public void run() { ByteArrayOutputStream err = new ByteArrayOutputStream(); InputStream in = pr.getErrorStream(); try { final byte[] BUFFER = new byte[4096]; int len; while (pr != null && timer > 0) { while ((len = in.available()) > 0) { len = in.read(BUFFER, 0, BUFFER.length > len ? len : BUFFER.length); err.write(BUFFER, 0, len); } Thread.sleep(50); } } catch (IOException e) { log.severe(e.getLocalizedMessage()); } catch (InterruptedException ie) { } finally { try { in.close(); } catch (IOException e) {} } log.info(err.toString()); } }); } InputStream in = pr.getInputStream(); timer = 200; while (timer-- > 0 && in.available() == 0) Thread.sleep(50); if (in.available() > 0) bi = ImageIO.read(in); } } catch (Exception ex) { } finally { synchronized (JavaFXPreviewTopComponent.this) { pr.destroy(); pr = null; } } } } } } repaint(); }
public void run() { synchronized (JavaFXPreviewTopComponent.this) { if (pr != null) { pr.destroy(); timer = 0; task.schedule(150); return; } } if (oldD != null) { oldD.removePropertyChangeListener(JavaFXPreviewTopComponent.this); oldD = null; } Node[] sel = TopComponent.getRegistry().getActivatedNodes(); if (sel.length == 1) { DataObject d = sel[0].getLookup().lookup(DataObject.class); if (d != null) { FileObject f = d.getPrimaryFile(); if (f.isData()) bi = null; if ("fx".equals(f.getExt())) { d.addPropertyChangeListener(JavaFXPreviewTopComponent.this); oldD = d; Project p = FileOwnerQuery.getOwner(f); if (p instanceof JavaFXProject) { PropertyEvaluator ev = ((JavaFXProject)p).evaluator(); FileObject srcRoots[] = ((JavaFXProject)p).getFOSourceRoots(); StringBuffer src = new StringBuffer(); String className = null; for (FileObject srcRoot : srcRoots) { if (src.length() > 0) src.append(';'); src.append(FileUtil.toFile(srcRoot).getAbsolutePath()); if (FileUtil.isParentOf(srcRoot, f)) { className = FileUtil.getRelativePath(srcRoot, f); className = className.substring(0, className.length() - 3).replace('/', '.'); } } String cp = ev.getProperty("javac.classpath"); cp = cp == null ? "" : cp.trim(); String enc = ev.getProperty("source.encoding"); if (enc == null || enc.trim().length() == 0) enc = "UTF-8"; File basedir = FileUtil.toFile(p.getProjectDirectory()); File build = PropertyUtils.resolveFile(basedir, "build/compiled"); ArrayList<String> args = new ArrayList<String>(); args.add(fxHome + "/bin/javafxc" + (Utilities.isWindows() ? ".exe" : "")); args.add("-cp"); args.add(build.getAbsolutePath() + File.pathSeparator + cp); args.add("-sourcepath"); args.add(src.toString()); args.add("-d"); args.add(build.getAbsolutePath()); args.add("-encoding"); args.add(enc.trim()); args.add(FileUtil.toFile(f).getAbsolutePath()); try { build.mkdirs(); log.info(args.toString()); synchronized (JavaFXPreviewTopComponent.this) { pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir); } if (log.isLoggable(Level.INFO)) { ByteArrayOutputStream err = new ByteArrayOutputStream(); InputStream in = pr.getErrorStream(); try { FileUtil.copy(in, err); } catch (IOException e) { log.severe(e.getLocalizedMessage()); } finally { try { in.close(); } catch (IOException e) {} } log.info(err.toString()); } pr.waitFor(); String jvmargs = ev.getProperty("run.jvmargs"); String appargs = ev.getProperty("application.args"); if (pr.exitValue() == 0) { args = new ArrayList<String>(); args.add(fxHome + "/bin/javafx" + (Utilities.isWindows() ? ".exe" : "")); args.add("-javaagent:" + previewLib.getAbsolutePath()); args.add("-Xbootclasspath/p:" + previewLib.getAbsolutePath()); args.add("-Dcom.apple.backgroundOnly=true"); args.add("-Dapple.awt.UIElement=true"); if (jvmargs != null) for (String ja : jvmargs.trim().split("\\s+")) if (ja.length()>0) args.add(ja); args.add("-cp"); args.add(src.toString() + File.pathSeparator + build.getAbsolutePath() + File.pathSeparator + cp); args.add(className); if (appargs != null) for (String aa : appargs.trim().split("\\s+")) args.add(aa); log.info(args.toString()); synchronized (JavaFXPreviewTopComponent.this) { pr = Runtime.getRuntime().exec(args.toArray(new String[args.size()]), null, basedir); } if (log.isLoggable(Level.INFO)) { RequestProcessor.getDefault().execute(new Runnable() { public void run() { ByteArrayOutputStream err = new ByteArrayOutputStream(); Process p = pr; if (p == null) return; InputStream in = p.getErrorStream(); try { final byte[] BUFFER = new byte[4096]; int len; while (pr != null && timer > 0) { while ((len = in.available()) > 0) { len = in.read(BUFFER, 0, BUFFER.length > len ? len : BUFFER.length); err.write(BUFFER, 0, len); } Thread.sleep(50); } } catch (IOException e) { log.severe(e.getLocalizedMessage()); } catch (InterruptedException ie) { } finally { try { in.close(); } catch (IOException e) {} } log.info(err.toString()); } }); } InputStream in = pr.getInputStream(); timer = 200; while (timer-- > 0 && in.available() == 0) Thread.sleep(50); if (in.available() > 0) bi = ImageIO.read(in); } } catch (Exception ex) { } finally { synchronized (JavaFXPreviewTopComponent.this) { pr.destroy(); pr = null; } } } } } } repaint(); }
public TiBlob resizer(int width, int height, String path, int rotate, int x, int y){ try{ Activity activity = getActivity(); AssetManager as = activity.getResources().getAssets(); String fpath = null; String save_path = null; if(path.startsWith("file://") || path.startsWith("content://") || path.startsWith("appdata://")){ fpath = path; path = path.replaceFirst("(appdata|file|content)://", ""); is = new FileInputStream(new File(new File(Environment.getExternalStorageDirectory(), TiApplication.getInstance().getPackageName()), path)); }else{ if(path.startsWith("app://")){ path = path.replaceFirst("app://", "Resources/"); }else if(path.startsWith("Resources") == false){ if(path.startsWith("/")){ path = "Resources" + path; }else{ path = "Resources/" + path; } } fpath = path; is = as.open(fpath); } File save_path_base = new File(path); save_path = "camera/" + save_path_base.getName(); String toFile = "/data/data/"+ TiApplication.getInstance().getPackageName() +"/app_appdata/" + save_path; copyFile(is, toFile); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(toFile, opts); try{ opts.inJustDecodeBounds = false; opts.inSampleSize = calcSampleSize(opts, width, height); Bitmap image_base = BitmapFactory.decodeFile(toFile, opts); int w = image_base.getWidth(); int h = image_base.getHeight(); Matrix matrix = getScaleMatrix(opts.outWidth, opts.outHeight, w, h); if(rotate > 0){ matrix.postRotate(rotate); } return returnBlob(opts, image_base, matrix, width, height, x, y); }catch(NullPointerException e){ Log.d(LCAT, "Bitmap IOException:" + e); return null; } }catch(IOException e){ Log.d(LCAT, "Bitmap IOException:" + e); return null; } }
public TiBlob resizer(int width, int height, String path, int rotate, int x, int y){ try{ Activity activity = getActivity(); AssetManager as = activity.getResources().getAssets(); String fpath = null; String save_path = null; if(path.startsWith("file://") || path.startsWith("content://") || path.startsWith("appdata://")){ path = path.replaceAll("(appdata|file|content)://", ""); fpath = path; is = new FileInputStream(new File(path)); }else{ if(path.startsWith("app://")){ path = path.replaceFirst("app://", "Resources/"); }else if(path.startsWith("Resources") == false){ if(path.startsWith("/")){ path = "Resources" + path; }else{ path = "Resources/" + path; } } fpath = path; is = as.open(fpath); } File save_path_base = new File(path); save_path = "camera/" + save_path_base.getName(); String toFile = "/data/data/"+ TiApplication.getInstance().getPackageName() +"/app_appdata/" + save_path; copyFile(is, toFile); BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(toFile, opts); try{ opts.inJustDecodeBounds = false; opts.inSampleSize = calcSampleSize(opts, width, height); Bitmap image_base = BitmapFactory.decodeFile(toFile, opts); int w = image_base.getWidth(); int h = image_base.getHeight(); Matrix matrix = getScaleMatrix(opts.outWidth, opts.outHeight, w, h); if(rotate > 0){ matrix.postRotate(rotate); } return returnBlob(opts, image_base, matrix, width, height, x, y); }catch(NullPointerException e){ Log.d(LCAT, "Bitmap IOException:" + e); return null; } }catch(IOException e){ Log.d(LCAT, "Bitmap IOException:" + e); return null; } }
public void bench() { ModelCompare compare = new DefaultModelCompare(); long before = System.currentTimeMillis(); KMFContainer root = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel.json")).get(0); KMFContainer root2 = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel2.json")).get(0); long after = System.currentTimeMillis(); System.out.println(after - before); before = System.currentTimeMillis(); TraceSequence sequence = compare.merge(root,root2); after = System.currentTimeMillis(); System.out.println(after - before); System.out.println(sequence.exportToString()); }
public void bench() { ModelCompare compare = new DefaultModelCompare(); long before = System.currentTimeMillis(); KMFContainer root = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel.json")).get(0); KMFContainer root2 = loader.loadModelFromStream(this.getClass().getClassLoader().getResourceAsStream("jedModel2.json")).get(0); long after = System.currentTimeMillis(); System.out.println(after - before); before = System.currentTimeMillis(); TraceSequence sequence = compare.diff(root,root2); after = System.currentTimeMillis(); System.out.println(after - before); System.out.println(sequence.exportToString()); }
public void merge() throws HyracksDataException, TreeIndexException { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Merging LSM-BTree."); } if (isMerging.get()) { throw new TreeIndexException("Merge already in progress in LSMBTree. Only one concurrent merge allowed."); } isMerging.set(true); AtomicInteger localSearcherRefCount = searcherRefCount; LSMBTreeOpContext ctx = createOpContext(); ITreeIndexCursor cursor = new LSMBTreeRangeSearchCursor(); RangePredicate rangePred = new RangePredicate(true, null, null, true, true, null, null); List<BTree> mergingDiskBTrees = search(cursor, (RangePredicate) rangePred, ctx, false); BTree mergedBTree = createMergeTargetBTree(); IIndexBulkLoadContext bulkLoadCtx = mergedBTree.beginBulkLoad(1.0f); try { while (cursor.hasNext()) { cursor.next(); ITupleReference frameTuple = cursor.getTuple(); mergedBTree.bulkLoadAddTuple(frameTuple, bulkLoadCtx); } } finally { cursor.close(); } mergedBTree.endBulkLoad(bulkLoadCtx); synchronized (diskBTrees) { diskBTrees.removeAll(mergingDiskBTrees); diskBTrees.addLast(mergedBTree); if (searcherRefCount == searcherRefCountA) { searcherRefCount = searcherRefCountB; } else { searcherRefCount = searcherRefCountA; } searcherRefCount.set(0); } while (localSearcherRefCount.get() != 0) { try { Thread.sleep(AFTER_MERGE_CLEANUP_SLEEP); } catch (InterruptedException e) { throw new HyracksDataException(e); } } for (BTree oldBTree : mergingDiskBTrees) { oldBTree.close(); FileReference fileRef = diskFileMapProvider.lookupFileName(oldBTree.getFileId()); diskBufferCache.closeFile(oldBTree.getFileId()); diskBufferCache.deleteFile(oldBTree.getFileId()); fileRef.getFile().delete(); } isMerging.set(false); }
public void merge() throws HyracksDataException, TreeIndexException { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Merging LSM-BTree."); } if (!isMerging.compareAndSet(false, true)) { throw new TreeIndexException("Merge already in progress in LSMBTree. Only one concurrent merge allowed."); } AtomicInteger localSearcherRefCount = searcherRefCount; LSMBTreeOpContext ctx = createOpContext(); ITreeIndexCursor cursor = new LSMBTreeRangeSearchCursor(); RangePredicate rangePred = new RangePredicate(true, null, null, true, true, null, null); List<BTree> mergingDiskBTrees = search(cursor, (RangePredicate) rangePred, ctx, false); BTree mergedBTree = createMergeTargetBTree(); IIndexBulkLoadContext bulkLoadCtx = mergedBTree.beginBulkLoad(1.0f); try { while (cursor.hasNext()) { cursor.next(); ITupleReference frameTuple = cursor.getTuple(); mergedBTree.bulkLoadAddTuple(frameTuple, bulkLoadCtx); } } finally { cursor.close(); } mergedBTree.endBulkLoad(bulkLoadCtx); synchronized (diskBTrees) { diskBTrees.removeAll(mergingDiskBTrees); diskBTrees.addLast(mergedBTree); if (searcherRefCount == searcherRefCountA) { searcherRefCount = searcherRefCountB; } else { searcherRefCount = searcherRefCountA; } searcherRefCount.set(0); } while (localSearcherRefCount.get() != 0) { try { Thread.sleep(AFTER_MERGE_CLEANUP_SLEEP); } catch (InterruptedException e) { throw new HyracksDataException(e); } } for (BTree oldBTree : mergingDiskBTrees) { oldBTree.close(); FileReference fileRef = diskFileMapProvider.lookupFileName(oldBTree.getFileId()); diskBufferCache.closeFile(oldBTree.getFileId()); diskBufferCache.deleteFile(oldBTree.getFileId()); fileRef.getFile().delete(); } isMerging.set(false); }
public void execute() { AlertDialog.Builder builder = new AlertDialog.Builder( (Context) GeoQuestApp.getCurrentActivity()).setMessage( (params.get("message"))).setPositiveButton(R.string.ok, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if (params.containsKey("icon")) { Bitmap bitmap = BitmapUtil.loadBitmap(params.get("icon"), false); builder.setIcon(new BitmapDrawable(bitmap)); } builder.show(); }
public void execute() { AlertDialog.Builder builder = new AlertDialog.Builder( (Context) GeoQuestApp.getCurrentActivity()).setTitle( (params.get("message"))).setPositiveButton(R.string.ok, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if (params.containsKey("image")) { Bitmap bitmap = BitmapUtil.loadBitmap(params.get("image"), false); builder.setIcon(new BitmapDrawable(bitmap)); } builder.show(); }
private static synchronized Server spawn(final int i) throws Exception { if(isLocal()) { return null; } StringBuffer sb = new StringBuffer(); sb.append("java").append(' '); sb.append("-Xmx512M").append(' '); String moduleOutput = System.getProperty("module.output"); if (moduleOutput == null) { moduleOutput = "./output"; } sb.append("-Dmodule.output=").append(moduleOutput).append(' '); sb.append("-Dtest.bind.address=localhost").append(' '); String database = System.getProperty("test.database"); if (database != null) { sb.append("-Dtest.database=").append(database).append(' '); } String serialization = System.getProperty("test.serialization"); if (serialization != null) { sb.append("-Dtest.serialization=").append(serialization).append(' '); } sb.append("-Dtest.server.index=").append(i).append(' '); String clustered = System.getProperty("test.clustered"); if (clustered != null && clustered.trim().length() == 0) { clustered = null; } if (clustered != null) { sb.append("-Dtest.clustered=").append(clustered).append(' '); } String remoting = System.getProperty("test.remoting"); if (remoting != null) { sb.append("-Dtest.remoting=").append(remoting).append(' '); } String testLogfileSuffix = System.getProperty("test.logfile.suffix"); if (testLogfileSuffix == null) { testLogfileSuffix = "undefined-test-type"; } else { int pos; if ((pos = testLogfileSuffix.lastIndexOf("client")) != -1) { testLogfileSuffix = testLogfileSuffix.substring(0, pos) + "server"; } if (clustered != null) { testLogfileSuffix += i; } } sb.append("-Dtest.logfile.suffix=").append(testLogfileSuffix).append(' '); String classPath = System.getProperty("java.class.path"); sb.append("-cp").append(" \"").append(classPath).append("\" "); sb.append("org.jboss.test.messaging.tools.jmx.rmi.RMITestServer"); String commandLine = sb.toString(); Process process = Runtime.getRuntime().exec(commandLine); log.trace("process: " + process); final boolean verbose = false; final BufferedReader rs = new BufferedReader(new InputStreamReader(process.getInputStream())); final BufferedReader re = new BufferedReader(new InputStreamReader(process.getErrorStream())); new Thread(new Runnable() { public void run() { try { String line; while((line = rs.readLine()) != null) { if (verbose) { System.out.println("SERVER " + i + " STDOUT: " + line); } } } catch(Exception e) { log.error("exception", e); } } }, "Server " + i + " STDOUT reader thread").start(); new Thread(new Runnable() { public void run() { try { String line; while((line = re.readLine()) != null) { if (verbose) { System.out.println("SERVER " + i + " STDERR: " + line); } } } catch(Exception e) { log.error("exception", e); } } }, "Server " + i + " STDERR reader thread").start(); long maxWaitTime = 30; long startTime = System.currentTimeMillis(); Server s = null; log.info("spawned server " + i + ", waiting for it to come online"); while(System.currentTimeMillis() - startTime < maxWaitTime * 1000) { s = acquireRemote(1, i, true); if (s != null) { break; } } if (s == null) { log.error("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ..."); throw new Exception("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ..."); } return s; }
private static synchronized Server spawn(final int i) throws Exception { if(isLocal()) { return null; } StringBuffer sb = new StringBuffer(); sb.append("java").append(' '); sb.append("-Xmx512M").append(' '); String moduleOutput = System.getProperty("module.output"); if (moduleOutput == null) { moduleOutput = "./output"; } sb.append("-Dmodule.output=").append(moduleOutput).append(' '); sb.append("-Dtest.bind.address=localhost").append(' '); String database = System.getProperty("test.database"); if (database != null) { sb.append("-Dtest.database=").append(database).append(' '); } String serialization = System.getProperty("test.serialization"); if (serialization != null) { sb.append("-Dtest.serialization=").append(serialization).append(' '); } sb.append("-Dtest.server.index=").append(i).append(' '); String clustered = System.getProperty("test.clustered"); if (clustered != null && clustered.trim().length() == 0) { clustered = null; } if (clustered != null) { sb.append("-Dtest.clustered=").append(clustered).append(' '); } String remoting = System.getProperty("test.remoting"); if (remoting != null) { sb.append("-Dtest.remoting=").append(remoting).append(' '); } String testLogfileSuffix = System.getProperty("test.logfile.suffix"); if (testLogfileSuffix == null) { testLogfileSuffix = "undefined-test-type"; } else { int pos; if ((pos = testLogfileSuffix.lastIndexOf("client")) != -1) { testLogfileSuffix = testLogfileSuffix.substring(0, pos) + "server"; } if (clustered != null) { testLogfileSuffix += i; } } sb.append("-Dtest.logfile.suffix=").append(testLogfileSuffix).append(' '); String classPath = System.getProperty("java.class.path"); if (System.getProperty("os.name").equals("Linux")) { sb.append("-cp").append(" ").append(classPath).append(" "); } else { sb.append("-cp").append(" \"").append(classPath).append("\" "); } sb.append("org.jboss.test.messaging.tools.jmx.rmi.RMITestServer"); String commandLine = sb.toString(); Process process = Runtime.getRuntime().exec(commandLine); log.trace("process: " + process); final boolean verbose = false; final BufferedReader rs = new BufferedReader(new InputStreamReader(process.getInputStream())); final BufferedReader re = new BufferedReader(new InputStreamReader(process.getErrorStream())); new Thread(new Runnable() { public void run() { try { String line; while((line = rs.readLine()) != null) { if (verbose) { System.out.println("SERVER " + i + " STDOUT: " + line); } } } catch(Exception e) { log.error("exception", e); } } }, "Server " + i + " STDOUT reader thread").start(); new Thread(new Runnable() { public void run() { try { String line; while((line = re.readLine()) != null) { if (verbose) { System.out.println("SERVER " + i + " STDERR: " + line); } } } catch(Exception e) { log.error("exception", e); } } }, "Server " + i + " STDERR reader thread").start(); long maxWaitTime = 30; long startTime = System.currentTimeMillis(); Server s = null; log.info("spawned server " + i + ", waiting for it to come online"); while(System.currentTimeMillis() - startTime < maxWaitTime * 1000) { s = acquireRemote(1, i, true); if (s != null) { break; } } if (s == null) { log.error("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ..."); throw new Exception("Cannot contact newly spawned server " + i + ", most likely the attempt failed, timing out ..."); } return s; }
public ContainerResponse filter(ContainerRequest request, ContainerResponse resp) { Matcher hostMatcher = hostPattern.matcher(request.getHeaderValue("Referer")); if(hostMatcher.matches()){ MultivaluedMap<String, Object> headers =resp.getHttpHeaders(); headers.putSingle("Access-Control-Allow-Origin", hostMatcher.group(1)); headers.putSingle("Access-Control-Allow-Methods", "POST, PUT,DELETE,GET, OPTIONS"); headers.putSingle("Access-Control-Allow-Credentials", "true"); } return resp; }
public ContainerResponse filter(ContainerRequest request, ContainerResponse resp) { String referer = request.getHeaderValue("Referer"); if(referer == null) return resp; Matcher hostMatcher = hostPattern.matcher(referer); if(hostMatcher.matches()){ MultivaluedMap<String, Object> headers =resp.getHttpHeaders(); headers.putSingle("Access-Control-Allow-Origin", hostMatcher.group(1)); headers.putSingle("Access-Control-Allow-Methods", "POST, PUT,DELETE,GET, OPTIONS"); headers.putSingle("Access-Control-Allow-Credentials", "true"); } return resp; }
public void begin( String namespace, String name, Attributes attributes ) throws Exception { Class<?> clazz = this.clazz; if ( clazz == null ) { String realClassName = className; if ( attributeName != null ) { String value = attributes.getValue( attributeName ); if ( value != null ) { realClassName = value; } } if ( getDigester().getLogger().isDebugEnabled() ) { getDigester().getLogger().debug( format( "[ObjectCreateRule]{%s} New '%s'", getDigester().getMatch(), realClassName ) ); } clazz = getDigester().getClassLoader().loadClass( realClassName ); } Object instance; if ( constructorArgumentTypes == null || constructorArgumentTypes.length == 0 ) { if ( getDigester().getLogger().isDebugEnabled() ) { getDigester().getLogger().debug( format( "[ObjectCreateRule]{%s} New '%s' using default empty constructor", getDigester().getMatch(), clazz.getName() ) ); } instance = clazz.newInstance(); } else { if ( proxyManager == null ) { Constructor<?> constructor = getAccessibleConstructor( clazz, constructorArgumentTypes ); if ( constructor == null ) { throw new SAXException( format( "[ObjectCreateRule]{%s} Class '%s' does not have a construcor with types %s", getDigester().getMatch(), clazz.getName(), Arrays.toString( constructorArgumentTypes ) ) ); } proxyManager = new ProxyManager( clazz, constructor, defaultConstructorArguments, getDigester() ); } instance = proxyManager.createProxy(); } getDigester().push( instance ); }
public void begin( String namespace, String name, Attributes attributes ) throws Exception { Class<?> clazz = this.clazz; if ( clazz == null ) { String realClassName = className; if ( attributeName != null ) { String value = attributes.getValue( attributeName ); if ( value != null ) { realClassName = value; } } if ( getDigester().getLogger().isDebugEnabled() ) { getDigester().getLogger().debug( format( "[ObjectCreateRule]{%s} New '%s'", getDigester().getMatch(), realClassName ) ); } clazz = getDigester().getClassLoader().loadClass( realClassName ); } Object instance; if ( constructorArgumentTypes == null || constructorArgumentTypes.length == 0 ) { if ( getDigester().getLogger().isDebugEnabled() ) { getDigester() .getLogger() .debug( format( "[ObjectCreateRule]{%s} New '%s' using default empty constructor", getDigester().getMatch(), clazz.getName() ) ); } instance = clazz.newInstance(); } else { if ( proxyManager == null ) { Constructor<?> constructor = getAccessibleConstructor( clazz, constructorArgumentTypes ); if ( constructor == null ) { throw new SAXException( format( "[ObjectCreateRule]{%s} Class '%s' does not have a construcor with types %s", getDigester().getMatch(), clazz.getName(), Arrays.toString( constructorArgumentTypes ) ) ); } proxyManager = new ProxyManager( clazz, constructor, defaultConstructorArguments, getDigester() ); } instance = proxyManager.createProxy(); } getDigester().push( instance ); }
private void fillMenuBar() { NetworkView networkView = cyWindow; CytoscapeObj cytoscapeObj = cyWindow.getCytoscapeObj(); JMenuItem mi = loadSubMenu.add(new LoadGraphFileAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK)); mi = loadSubMenu.add(new LoadNodeAttributesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK)); mi = loadSubMenu.add(new LoadEdgeAttributesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK)); mi = loadSubMenu.add(new LoadExpressionMatrixAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK)); mi = loadSubMenu.add(new LoadBioDataServerAction(networkView)); saveSubMenu.add(new SaveAsGMLAction(networkView)); saveSubMenu.add(new SaveAsInteractionsAction(networkView)); saveSubMenu.add(new SaveVisibleNodesAction(networkView)); saveSubMenu.add(new SaveSelectedNodesAction(networkView)); fileMenu.add(new PrintAction(networkView)); if (cytoscapeObj.getParentApp() != null) { mi = fileMenu.add(new ExitAction(cyWindow)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); } editMenu.add( new SquiggleAction( networkView ) ); mi = dataMenu.add(new DisplayBrowserAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK)); menuBar.addAction( new GraphObjectSelectionAction( networkView ) ); mi = dataMenu.add(new EdgeManipulationAction(networkView)); JMenu selectNodesSubMenu = new JMenu("Nodes"); selectMenu.add(selectNodesSubMenu); JMenu selectEdgesSubMenu = new JMenu("Edges"); selectMenu.add(selectEdgesSubMenu); JMenu displayNWSubMenu = new JMenu("To New Window"); selectMenu.add(displayNWSubMenu); mi = selectNodesSubMenu.add(new InvertSelectedNodesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK)); mi = selectNodesSubMenu.add(new HideSelectedNodesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.CTRL_MASK)); mi = selectNodesSubMenu.add(new UnHideSelectedNodesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK)); mi = selectNodesSubMenu.add(new SelectAllNodesAction(networkView)); mi = selectNodesSubMenu.add(new DeSelectAllNodesAction(networkView)); mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK)); selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView)); selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView)); mi = selectEdgesSubMenu.add(new InvertSelectedEdgesAction(networkView)); mi = selectEdgesSubMenu.add(new HideSelectedEdgesAction(networkView)); mi = selectEdgesSubMenu.add(new UnHideSelectedEdgesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK)); mi = selectEdgesSubMenu.add(new SelectAllEdgesAction(networkView)); mi = selectEdgesSubMenu.add(new DeSelectAllEdgesAction(networkView)); mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK)); menuBar.addAction( new GraphObjectSelectionAction( networkView ) ); vizMenu.add( new BirdsEyeViewAction( networkView ) ); menuBar.addAction( new AnimatedLayoutAction( networkView ) ); vizMenu.add ( new BackgroundColorAction (networkView) ); selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView)); selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView)); mi = displayNWSubMenu.add(new NewWindowSelectedNodesOnlyAction(cyWindow)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); mi = displayNWSubMenu.add(new NewWindowSelectedNodesEdgesAction(cyWindow)); mi = displayNWSubMenu.add(new CloneGraphInNewWindowAction(cyWindow)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK)); mi = selectMenu.add(new SelectAllAction(networkView)); mi = selectMenu.add(new DeselectAllAction(networkView)); layoutMenu.add(new SpringEmbeddedLayoutAction(networkView)); layoutMenu.addSeparator(); JMenu alignSubMenu = new JMenu("Align Selected Nodes"); layoutMenu.add(alignSubMenu); alignSubMenu.add(new AlignHorizontalAction(networkView)); alignSubMenu.add(new AlignVerticalAction(networkView)); layoutMenu.add(new RotateSelectedNodesAction(networkView)); ShrinkExpandGraphUI shrinkExpand = new ShrinkExpandGraphUI(cyWindow, layoutMenu); vizMenu.add( new BirdsEyeViewAction( networkView ) ); JMenu showExpressionData = new JMenu ("Show Expression Data" ); vizMenu.add ( new BackgroundColorAction (networkView) ); this.vizMenuItem = vizMenu.add(new SetVisualPropertiesAction(cyWindow)); this.disableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, false)); this.enableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, true)); this.enableVizMapperItem.setEnabled(false); menuBar.addAction( new AnimatedLayoutAction( networkView ) ); }
private void fillMenuBar() { NetworkView networkView = cyWindow; CytoscapeObj cytoscapeObj = cyWindow.getCytoscapeObj(); JMenuItem mi = loadSubMenu.add(new LoadGraphFileAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK)); mi = loadSubMenu.add(new LoadNodeAttributesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK)); mi = loadSubMenu.add(new LoadEdgeAttributesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK|ActionEvent.SHIFT_MASK)); mi = loadSubMenu.add(new LoadExpressionMatrixAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK)); mi = loadSubMenu.add(new LoadBioDataServerAction(networkView)); saveSubMenu.add(new SaveAsGMLAction(networkView)); saveSubMenu.add(new SaveAsInteractionsAction(networkView)); saveSubMenu.add(new SaveVisibleNodesAction(networkView)); saveSubMenu.add(new SaveSelectedNodesAction(networkView)); fileMenu.add(new PrintAction(networkView)); if (cytoscapeObj.getParentApp() != null) { mi = fileMenu.add(new ExitAction(cyWindow)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); } editMenu.add( new SquiggleAction( networkView ) ); mi = dataMenu.add(new DisplayBrowserAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK)); menuBar.addAction( new GraphObjectSelectionAction( networkView ) ); mi = dataMenu.add(new EdgeManipulationAction(networkView)); JMenu selectNodesSubMenu = new JMenu("Nodes"); selectMenu.add(selectNodesSubMenu); JMenu selectEdgesSubMenu = new JMenu("Edges"); selectMenu.add(selectEdgesSubMenu); JMenu displayNWSubMenu = new JMenu("To New Window"); selectMenu.add(displayNWSubMenu); mi = selectNodesSubMenu.add(new InvertSelectedNodesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK)); mi = selectNodesSubMenu.add(new HideSelectedNodesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.CTRL_MASK)); mi = selectNodesSubMenu.add(new UnHideSelectedNodesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK)); mi = selectNodesSubMenu.add(new SelectAllNodesAction(networkView)); mi = selectNodesSubMenu.add(new DeSelectAllNodesAction(networkView)); mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK)); selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView)); selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView)); mi = selectEdgesSubMenu.add(new InvertSelectedEdgesAction(networkView)); mi = selectEdgesSubMenu.add(new HideSelectedEdgesAction(networkView)); mi = selectEdgesSubMenu.add(new UnHideSelectedEdgesAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK)); mi = selectEdgesSubMenu.add(new SelectAllEdgesAction(networkView)); mi = selectEdgesSubMenu.add(new DeSelectAllEdgesAction(networkView)); mi = selectNodesSubMenu.add(new SelectFirstNeighborsAction(networkView)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK)); menuBar.addAction( new GraphObjectSelectionAction( networkView ) ); vizMenu.add( new BirdsEyeViewAction( networkView ) ); menuBar.addAction( new AnimatedLayoutAction( networkView ) ); vizMenu.add ( new BackgroundColorAction (networkView) ); selectNodesSubMenu.add(new AlphabeticalSelectionAction(networkView)); selectNodesSubMenu.add(new ListFromFileSelectionAction(networkView)); mi = displayNWSubMenu.add(new NewWindowSelectedNodesOnlyAction(cyWindow)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.SHIFT_MASK|ActionEvent.CTRL_MASK)); mi = displayNWSubMenu.add(new NewWindowSelectedNodesEdgesAction(cyWindow)); mi = displayNWSubMenu.add(new CloneGraphInNewWindowAction(cyWindow)); mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK)); mi = selectMenu.add(new SelectAllAction(networkView)); mi = selectMenu.add(new DeselectAllAction(networkView)); layoutMenu.add(new SpringEmbeddedLayoutAction(networkView)); layoutMenu.addSeparator(); JMenu alignSubMenu = new JMenu("Align Selected Nodes"); layoutMenu.add(alignSubMenu); alignSubMenu.add(new AlignHorizontalAction(networkView)); alignSubMenu.add(new AlignVerticalAction(networkView)); layoutMenu.add(new RotateSelectedNodesAction(networkView)); ShrinkExpandGraphUI shrinkExpand = new ShrinkExpandGraphUI(cyWindow, layoutMenu); vizMenu.add( new BirdsEyeViewAction( networkView ) ); JMenu showExpressionData = new JMenu ("Show Expression Data" ); vizMenu.add ( new BackgroundColorAction (networkView) ); this.vizMenuItem = vizMenu.add(new SetVisualPropertiesAction(cyWindow)); this.disableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, false)); this.enableVizMapperItem = vizMenu.add(new ToggleVisualMapperAction(cyWindow, true)); this.enableVizMapperItem.setEnabled(false); menuBar.addAction( new AnimatedLayoutAction( networkView ) ); }
public static void main(String[] args) { if(args.length <= 0) { System.out.println("invalid arguments"); return; } if(!args[0].endsWith(".pgl")) { System.out.println("wrong file type: .pgl file expected"); return; } parse p = new parse(args[0],false); }
public static void main(String[] args) { if(args.length <= 0) { System.out.println("invalid arguments"); return; } if(!args[0].endsWith(".pgl")) { System.out.println("wrong file type: .pgl file expected"); return; } parse p = new parse(args[0],null); }
private static String readAll(String fileName) { StringBuilder buf = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); String line; while ((line = reader.readLine()) != null) { buf.append(line); buf.append('\n'); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buf.toString(); }
private static String readAll(String fileName) { StringBuilder buf = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); String line; while ((line = reader.readLine()) != null) { buf.append(line); buf.append('\n'); } reader.close(); } catch (FileNotFoundException e) { System.err.println("cannot open file \"" + fileName + "\""); } catch (IOException e) { e.printStackTrace(); } return buf.toString(); }
public Wizard(List<WizardStep> steps) { VerticalPanel mainPanel = new VerticalPanel(); initWidget(mainPanel); nextButton = new Button("Next", new ClickListener() { public void onClick(Widget sender) { currentStep++; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); prevButton = new Button("Previous", new ClickListener() { public void onClick(Widget sender) { currentStep--; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); stepContentPanel = new SimplePanel(); stepsTree = new Tree(); stepsTree.addTreeListener(new WizardTreeListener()); HorizontalPanel contentPanel = new HorizontalPanel(); contentPanel.add(stepsTree); DecoratorPanel contentDecorator = new DecoratorPanel(); contentDecorator.setWidget(stepContentPanel); contentPanel.add(contentDecorator); mainPanel.add(contentPanel); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.add(prevButton); buttonPanel.add(nextButton); mainPanel.add(buttonPanel); treeItemToStep = new HashMap<TreeItem, WizardStep>(); setSteps(steps); stepsTree.setSelectedItem(stepsTree.getItem(0)); }
public Wizard(List<WizardStep> steps) { VerticalPanel mainPanel = new VerticalPanel(); initWidget(mainPanel); nextButton = new Button("Next", new ClickListener() { public void onClick(Widget sender) { if(currentStep == Wizard.this.steps.size()-1) { return; } currentStep++; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); prevButton = new Button("Previous", new ClickListener() { public void onClick(Widget sender) { currentStep--; TreeItem item = stepsTree.getItem(currentStep); stepsTree.setSelectedItem(item); } }); stepContentPanel = new SimplePanel(); stepsTree = new Tree(); stepsTree.addTreeListener(new WizardTreeListener()); HorizontalPanel contentPanel = new HorizontalPanel(); contentPanel.add(stepsTree); DecoratorPanel contentDecorator = new DecoratorPanel(); contentDecorator.setWidget(stepContentPanel); contentPanel.add(contentDecorator); mainPanel.add(contentPanel); HorizontalPanel buttonPanel = new HorizontalPanel(); buttonPanel.add(prevButton); buttonPanel.add(nextButton); mainPanel.add(buttonPanel); treeItemToStep = new HashMap<TreeItem, WizardStep>(); setSteps(steps); stepsTree.setSelectedItem(stepsTree.getItem(0)); }
public InputStream combineRepeatedFormat(final InputStream in, final PipedOutputStream pios) { PipedInputStream piis=null; try { piis = new PipedInputStream(pios); } catch (IOException e) { LOGGER.log(Level.SEVERE,"Can't read piped input stream."); throw new OkapiIOException("Can't read piped input stream."); } final OutputStreamWriter osw = new OutputStreamWriter(pios); final BufferedWriter bw = new BufferedWriter(osw); final InputStreamReader isr = new InputStreamReader(in); final BufferedReader br = new BufferedReader(isr); Thread readThread = new Thread(new Runnable() { char cbuf[] = new char[512]; String curtag="",curtext="",curtagname="",onp="",offp=""; String r1b4text="",r1aftext="",t1=""; String r2b4text="",r2aftext="",t2=""; int i,n; boolean bIntag=false,bGotname=false,bInap=false,bHavr1=false; boolean bInsideTextMarkers=false,bInr=false,bB4text=true,bInInnerR=false; boolean bInsideNastyTextBox=false; public void run() { try { while((n=br.read(cbuf,0,512))!=-1) { for(i=0;i<n;i++) { handleOneChar(cbuf[i]); } } if (curtext.length()>0) havtext(curtext); } catch(IOException e) { LOGGER.log(Level.SEVERE,"Can't read input pipe."); throw new OkapiIOException("Can't read input pipe."); } try { br.close(); isr.close(); bw.flush(); bw.close(); osw.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE,"Can't read piped input."); throw new OkapiIOException("Can't read piped input."); } } private void handleOneChar(char c) { if (c=='>') { curtag = curtag + ">"; havatag(curtag,curtagname); curtag = ""; curtagname = ""; bIntag = false; } else if (c=='<') { if (!bIntag) { if (curtext.length()>0) { havtext(curtext); curtext = ""; } curtag = curtag + "<"; bIntag = true; bGotname = false; } else { curtag = curtag + "&lt;"; } } else { if (bIntag) { curtag = curtag + c; if (!bGotname) if (c==' ') bGotname = true; else curtagname = curtagname + c; } else curtext = curtext + c; } } private void havatag(String snug,String tugname) { String tug=snug; String b4text; boolean bCollapsing=false; if (bInsideNastyTextBox) { if (tugname.equals("/v:textbox")) bInsideNastyTextBox = false; else tug = killRevisionIDsAndErrs(snug); innanar(tug); } else if (tugname.equals("v:textbox")) { bInsideNastyTextBox = true; innanar(tug); } else if (tugname.equals("w:p") || tugname.equals("a:p")) { tug = killRevisionIDsAndErrs(snug); onp = tug; if (tug.equals("<w:p/>")) { bInap = false; offp += tug; streamTheCurrentStuff(); } else { bInap = true; bInr = false; bInInnerR = false; bHavr1 = false; bB4text = false; } } else if (tugname.equals("/w:p") || tugname.equals("/a:p")) { offp = tug; bInap = false; streamTheCurrentStuff(); } else if (tugname.equals("w:t") || tugname.equals("a:t")) { bInsideTextMarkers = true; innanar(tug); } else if (tugname.equals("/w:t") || tugname.equals("/a:t")) { bInsideTextMarkers = false; innanar(tug); } else if (bInap) { if (tugname.equals("w:r") || tugname.equals("a:r") || tugname.equals("a:fld")) { tug = killRevisionIDsAndErrs(snug); if (bInr) { bInInnerR = true; innanar(tug); } else { if (bHavr1) r2b4text = tug; else r1b4text = tug; bInr = true; bB4text = true; } } else if (tugname.equals("/w:r") || tugname.equals("/a:r") || tugname.equals("/a:fld")) { if (bInInnerR) { bInInnerR = false; innanar(tug); } else { bInr = false; if (bHavr1) { r2aftext = r2aftext + tug; if (r1aftext.equals(r2aftext)) { bCollapsing = false; b4text = r1b4text; if (r1b4text.equals(r2b4text)) bCollapsing = true; else { int ndx = r1b4text.indexOf(":t xml:space=\"preserve\""); if (ndx>-1) { if (r2b4text.equals( r1b4text.substring(0,ndx)+":t"+r1b4text.substring(ndx+23))) { bCollapsing = true; b4text = r1b4text; } } ndx = r2b4text.indexOf(":t xml:space=\"preserve\""); if (ndx>-1) { if (r1b4text.equals( r2b4text.substring(0,ndx)+":t"+r2b4text.substring(ndx+23))) { bCollapsing = true; b4text = r2b4text; } } } if (bCollapsing) { r1b4text = b4text; t1 = t1 + t2; r2b4text = ""; r2aftext = ""; t2 = ""; } else streamTheCurrentStuff(); } else streamTheCurrentStuff(); } else { r1aftext = r1aftext + tug; bHavr1 = true; } } } else if (bInr) innanar(tug); else { streamTheCurrentStuff(); onp = tug; } } else if (tugname.equalsIgnoreCase("w:sectPr") || tugname.equalsIgnoreCase("a:sectPr")) { tug = killRevisionIDsAndErrs(tug); rat(tug); } else rat(tug); } private void innanar(String tug) { if (bHavr1) { if (bB4text) r2b4text = r2b4text + tug; else r2aftext = r2aftext + tug; } else { if (bB4text) r1b4text = r1b4text + tug; else r1aftext = r1aftext + tug; } } private String killRevisionIDsAndErrs(String tug) { String tigger; if (configurationType==MSWORD) tigger = killRevisionIDs(tug); else tigger=killErrs(tug); return tigger; } private String killRevisionIDs(String tug) { String snug=tug; String shrug=""; String slug; int ndx; while ((ndx=snug.indexOf(" w:rsid"))>-1) { shrug += snug.substring(0,ndx); snug = snug.substring(ndx); slug = snug.substring(1); ndx = slug.indexOf(' '); if (ndx>-1) snug = slug.substring(ndx); else { ndx = slug.indexOf("/>"); if (ndx>-1) snug = snug.substring(ndx+1); else { ndx = slug.indexOf('>'); if (ndx>-1) snug = snug.substring(ndx+1); } break; } } shrug += snug; return shrug; } private String killErrs(String tug) { String snug=tug; String shrug=""; String slug; int ndx; if ((ndx=snug.indexOf(" err="))>-1) { shrug += snug.substring(0,ndx); snug = snug.substring(ndx); slug = snug.substring(1); ndx = slug.indexOf(' '); if (ndx>-1) snug = slug.substring(ndx); else { ndx = slug.indexOf("/>"); if (ndx>-1) snug = snug.substring(ndx+1); else { ndx = slug.indexOf('>'); if (ndx>-1) snug = snug.substring(ndx+1); } } } shrug += snug; return shrug; } private void havtext(String curtext) { if (bInsideNastyTextBox) innanar(curtext); else if (bInap) { if (bInInnerR || !bInsideTextMarkers) { if (bInr) innanar(curtext); else { streamTheCurrentStuff(); streamTheCurrentStuff(); onp = curtext; } } else { bB4text = false; if (bHavr1) { t2 = curtext; } else t1 = curtext; } } else rat(curtext); } private void streamTheCurrentStuff() { if (bInap) { rat(onp+r1b4text+t1+r1aftext); onp = ""; r1b4text = r2b4text; t1 = t2; r1aftext = r2aftext; r2b4text = ""; t2 = ""; r2aftext = ""; offp = ""; } else { rat(onp+r1b4text+t1+r1aftext+r2b4text+t2+r2aftext+offp); onp = ""; r1b4text = ""; t1 = ""; r1aftext = ""; r2b4text = ""; t2 = ""; r2aftext = ""; offp = ""; bHavr1 = false; } } private void rat(String s) { try { bw.write(s); LOGGER.log(Level.FINEST,s); } catch (IOException e) { LOGGER.log(Level.WARNING,"Problem writing piped stream."); s = s + " "; } } }); readThread.start(); return piis; }
public InputStream combineRepeatedFormat(final InputStream in, final PipedOutputStream pios) { final OutputStreamWriter osw; final BufferedWriter bw; final InputStreamReader isr; final BufferedReader br; PipedInputStream piis=null; try { piis = new PipedInputStream(pios); osw = new OutputStreamWriter(pios,"UTF-8"); bw = new BufferedWriter(osw); isr = new InputStreamReader(in,"UTF-8"); br = new BufferedReader(isr); } catch (IOException e) { LOGGER.log(Level.SEVERE,"Can't read piped input stream."); throw new OkapiIOException("Can't read piped input stream."); } Thread readThread = new Thread(new Runnable() { char cbuf[] = new char[512]; String curtag="",curtext="",curtagname="",onp="",offp=""; String r1b4text="",r1aftext="",t1=""; String r2b4text="",r2aftext="",t2=""; int i,n; boolean bIntag=false,bGotname=false,bInap=false,bHavr1=false; boolean bInsideTextMarkers=false,bInr=false,bB4text=true,bInInnerR=false; boolean bInsideNastyTextBox=false; public void run() { try { while((n=br.read(cbuf,0,512))!=-1) { for(i=0;i<n;i++) { handleOneChar(cbuf[i]); } } if (curtext.length()>0) havtext(curtext); } catch(IOException e) { LOGGER.log(Level.SEVERE,"Can't read input pipe."); throw new OkapiIOException("Can't read input pipe."); } try { br.close(); isr.close(); bw.flush(); bw.close(); osw.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE,"Can't read piped input."); throw new OkapiIOException("Can't read piped input."); } } private void handleOneChar(char c) { if (c=='>') { curtag = curtag + ">"; havatag(curtag,curtagname); curtag = ""; curtagname = ""; bIntag = false; } else if (c=='<') { if (!bIntag) { if (curtext.length()>0) { havtext(curtext); curtext = ""; } curtag = curtag + "<"; bIntag = true; bGotname = false; } else { curtag = curtag + "&lt;"; } } else { if (bIntag) { curtag = curtag + c; if (!bGotname) if (c==' ') bGotname = true; else curtagname = curtagname + c; } else curtext = curtext + c; } } private void havatag(String snug,String tugname) { String tug=snug; String b4text; boolean bCollapsing=false; if (bInsideNastyTextBox) { if (tugname.equals("/v:textbox")) bInsideNastyTextBox = false; else tug = killRevisionIDsAndErrs(snug); innanar(tug); } else if (tugname.equals("v:textbox")) { bInsideNastyTextBox = true; innanar(tug); } else if (tugname.equals("w:p") || tugname.equals("a:p")) { tug = killRevisionIDsAndErrs(snug); onp = tug; if (tug.equals("<w:p/>")) { bInap = false; offp += tug; streamTheCurrentStuff(); } else { bInap = true; bInr = false; bInInnerR = false; bHavr1 = false; bB4text = false; } } else if (tugname.equals("/w:p") || tugname.equals("/a:p")) { offp = tug; bInap = false; streamTheCurrentStuff(); } else if (tugname.equals("w:t") || tugname.equals("a:t")) { bInsideTextMarkers = true; innanar(tug); } else if (tugname.equals("/w:t") || tugname.equals("/a:t")) { bInsideTextMarkers = false; innanar(tug); } else if (bInap) { if (tugname.equals("w:r") || tugname.equals("a:r") || tugname.equals("a:fld")) { tug = killRevisionIDsAndErrs(snug); if (bInr) { bInInnerR = true; innanar(tug); } else { if (bHavr1) r2b4text = tug; else r1b4text = tug; bInr = true; bB4text = true; } } else if (tugname.equals("/w:r") || tugname.equals("/a:r") || tugname.equals("/a:fld")) { if (bInInnerR) { bInInnerR = false; innanar(tug); } else { bInr = false; if (bHavr1) { r2aftext = r2aftext + tug; if (r1aftext.equals(r2aftext)) { bCollapsing = false; b4text = r1b4text; if (r1b4text.equals(r2b4text)) bCollapsing = true; else { int ndx = r1b4text.indexOf(":t xml:space=\"preserve\""); if (ndx>-1) { if (r2b4text.equals( r1b4text.substring(0,ndx)+":t"+r1b4text.substring(ndx+23))) { bCollapsing = true; b4text = r1b4text; } } ndx = r2b4text.indexOf(":t xml:space=\"preserve\""); if (ndx>-1) { if (r1b4text.equals( r2b4text.substring(0,ndx)+":t"+r2b4text.substring(ndx+23))) { bCollapsing = true; b4text = r2b4text; } } } if (bCollapsing) { r1b4text = b4text; t1 = t1 + t2; r2b4text = ""; r2aftext = ""; t2 = ""; } else streamTheCurrentStuff(); } else streamTheCurrentStuff(); } else { r1aftext = r1aftext + tug; bHavr1 = true; } } } else if (bInr) innanar(tug); else { streamTheCurrentStuff(); onp = tug; } } else if (tugname.equalsIgnoreCase("w:sectPr") || tugname.equalsIgnoreCase("a:sectPr")) { tug = killRevisionIDsAndErrs(tug); rat(tug); } else rat(tug); } private void innanar(String tug) { if (bHavr1) { if (bB4text) r2b4text = r2b4text + tug; else r2aftext = r2aftext + tug; } else { if (bB4text) r1b4text = r1b4text + tug; else r1aftext = r1aftext + tug; } } private String killRevisionIDsAndErrs(String tug) { String tigger; if (configurationType==MSWORD) tigger = killRevisionIDs(tug); else tigger=killErrs(tug); return tigger; } private String killRevisionIDs(String tug) { String snug=tug; String shrug=""; String slug; int ndx; while ((ndx=snug.indexOf(" w:rsid"))>-1) { shrug += snug.substring(0,ndx); snug = snug.substring(ndx); slug = snug.substring(1); ndx = slug.indexOf(' '); if (ndx>-1) snug = slug.substring(ndx); else { ndx = slug.indexOf("/>"); if (ndx>-1) snug = snug.substring(ndx+1); else { ndx = slug.indexOf('>'); if (ndx>-1) snug = snug.substring(ndx+1); } break; } } shrug += snug; return shrug; } private String killErrs(String tug) { String snug=tug; String shrug=""; String slug; int ndx; if ((ndx=snug.indexOf(" err="))>-1) { shrug += snug.substring(0,ndx); snug = snug.substring(ndx); slug = snug.substring(1); ndx = slug.indexOf(' '); if (ndx>-1) snug = slug.substring(ndx); else { ndx = slug.indexOf("/>"); if (ndx>-1) snug = snug.substring(ndx+1); else { ndx = slug.indexOf('>'); if (ndx>-1) snug = snug.substring(ndx+1); } } } shrug += snug; return shrug; } private void havtext(String curtext) { if (bInsideNastyTextBox) innanar(curtext); else if (bInap) { if (bInInnerR || !bInsideTextMarkers) { if (bInr) innanar(curtext); else { streamTheCurrentStuff(); streamTheCurrentStuff(); onp = curtext; } } else { bB4text = false; if (bHavr1) { t2 = curtext; } else t1 = curtext; } } else rat(curtext); } private void streamTheCurrentStuff() { if (bInap) { rat(onp+r1b4text+t1+r1aftext); onp = ""; r1b4text = r2b4text; t1 = t2; r1aftext = r2aftext; r2b4text = ""; t2 = ""; r2aftext = ""; offp = ""; } else { rat(onp+r1b4text+t1+r1aftext+r2b4text+t2+r2aftext+offp); onp = ""; r1b4text = ""; t1 = ""; r1aftext = ""; r2b4text = ""; t2 = ""; r2aftext = ""; offp = ""; bHavr1 = false; } } private void rat(String s) { try { bw.write(s); LOGGER.log(Level.FINEST,s); } catch (IOException e) { LOGGER.log(Level.WARNING,"Problem writing piped stream."); s = s + " "; } } }); readThread.start(); return piis; }
public List<BBSDataModel> getBBSDataList(int offset, int limit) { ArrayList<Integer> idList = new ArrayList<Integer>(limit); int startId = BBSDataModelDao.getMaxId() - offset; for (int i = 0; i < limit; i++) idList.add(new Integer(startId - i)); return Datastore.query(meta).filter(meta.id.in(idList)).asList(); }
public List<BBSDataModel> getBBSDataList(int offset, int limit) { ArrayList<Integer> idList = new ArrayList<Integer>(limit); int startId = BBSDataModelDao.getMaxId() - offset; for (int i = 0; i < limit; i++) idList.add(new Integer(startId - i)); return Datastore .query(meta) .filter(meta.id.in(idList)) .sort(meta.id.desc) .asList(); }
public ServletContainer start(TreeLogger logger, int port, File appRootDir, Filter shellServletFilter) throws UnableToCompleteException { checkStartParams(logger, port, appRootDir); System.setProperty("VERBOSE", "true"); JettyTreeLogger.setDefaultConstruction(logger, TreeLogger.INFO); System.setProperty("org.mortbay.log.class", JettyTreeLogger.class.getName()); Log.isDebugEnabled(); if (JettyTreeLogger.isDefaultConstructionReady()) { Log.setLog(new JettyTreeLogger()); } Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); connector.setHost("127.0.0.1"); server.addConnector(connector); WebAppContext wac = new WebAppContext(appRootDir.getAbsolutePath(), "/"); wac.getInitParams().put( "org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"); FilterHolder filterHolder = new FilterHolder(); filterHolder.setFilter(shellServletFilter); wac.addFilter(filterHolder, "/*", Handler.ALL); server.setHandler(wac); server.setStopAtShutdown(true); try { server.start(); int actualPort = connector.getPort(); return new JettyServletContainer(logger, wac, actualPort, appRootDir); } catch (Exception e) { logger.log(TreeLogger.ERROR, "Unable to start embedded Jetty server", e); throw new UnableToCompleteException(); } }
public ServletContainer start(TreeLogger logger, int port, File appRootDir, Filter shellServletFilter) throws UnableToCompleteException { checkStartParams(logger, port, appRootDir); System.setProperty("VERBOSE", "true"); JettyTreeLogger.setDefaultConstruction(logger, TreeLogger.INFO); System.setProperty("org.mortbay.log.class", JettyTreeLogger.class.getName()); Log.isDebugEnabled(); if (JettyTreeLogger.isDefaultConstructionReady()) { Log.setLog(new JettyTreeLogger()); } Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); connector.setHost("127.0.0.1"); server.addConnector(connector); WebAppContext wac = new WebAppContext(appRootDir.getAbsolutePath(), "/"); wac.getInitParams().put( "org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"); FilterHolder filterHolder = new FilterHolder(); filterHolder.setFilter(shellServletFilter); wac.addFilter(filterHolder, "/*", Handler.ALL); server.setHandler(wac); server.setStopAtShutdown(true); try { server.start(); int actualPort = connector.getLocalPort(); return new JettyServletContainer(logger, wac, actualPort, appRootDir); } catch (Exception e) { logger.log(TreeLogger.ERROR, "Unable to start embedded Jetty server", e); throw new UnableToCompleteException(); } }
private void updateInfolinkField() { IConfigurationRetriever retriever = null; try { retriever = ExperimentFactory.getExperimentConfigurationRetriever(this.experimentAllowed.getExperiment().getExperimentUniqueName()); final String infolink = retriever.getProperty(ExperimentWindow.EXPERIMENT_INFOLINK_PROPERTY, ExperimentWindow.DEFAULT_EXPERIMENT_INFOLINK ); final String infodesc = retriever.getProperty(ExperimentWindow.EXPERIMENT_INFODESCRIPTION_PROPERTY, ExperimentWindow.DEFAULT_EXPERIMENT_INFODESCRIPTION ); this.informationLink.setHref(infolink); this.informationLink.setText(infodesc); } catch(IllegalArgumentException e){ e.printStackTrace(); this.informationLink.setText("<not available>"); } this.informationLink.setTarget("_blank"); String href = this.informationLink.getHref(); if(this.informationLink.getHref().isEmpty()) this.informationLinkLabel.setVisible(false); }
private void updateInfolinkField() { IConfigurationRetriever retriever = null; try { retriever = ExperimentFactory.getExperimentConfigurationRetriever(this.experimentAllowed.getExperiment().getExperimentUniqueName()); final String infolink = retriever.getProperty(ExperimentWindow.EXPERIMENT_INFOLINK_PROPERTY, ExperimentWindow.DEFAULT_EXPERIMENT_INFOLINK ); final String infodesc = retriever.getProperty(ExperimentWindow.EXPERIMENT_INFODESCRIPTION_PROPERTY, ExperimentWindow.DEFAULT_EXPERIMENT_INFODESCRIPTION ); if(!infolink.isEmpty()) this.informationLink.setHref(infolink); this.informationLink.setText(infodesc); } catch(IllegalArgumentException e){ e.printStackTrace(); this.informationLink.setText("<not available>"); } this.informationLink.setTarget("_blank"); String href = this.informationLink.getHref(); if(this.informationLink.getHref().isEmpty()) this.informationLinkLabel.setVisible(false); }
public void onSaveTerminalClick(InventoryClickEvent event) { Inventory inv = event.getInventory(); String name = inv.getTitle(); if (name.equals("§4TARDIS saves")) { event.setCancelled(true); int slot = event.getRawSlot(); if (slot < 54) { final Player player = (Player) event.getWhoClicked(); String playerNameStr = player.getName(); HashMap<String, Object> wheres = new HashMap<String, Object>(); wheres.put("player", playerNameStr); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheres, false); if (rst.resultSet()) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("tardis_id", rst.getTardis_id()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (rs.resultSet()) { int id = rs.getTardis_id(); ItemStack is = inv.getItem(slot); ItemMeta im = is.getItemMeta(); List<String> lore = im.getLore(); String save = getDestination(lore); if (!save.equals(rs.getCurrent())) { HashMap<String, Object> set = new HashMap<String, Object>(); set.put("save", save); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); new QueryFactory(plugin).doUpdate("tardis", set, wheret); plugin.tardisHasDestination.put(id, plugin.getArtronConfig().getInt("random")); if (plugin.trackRescue.containsKey(Integer.valueOf(id))) { plugin.trackRescue.remove(Integer.valueOf(id)); } close(player); player.sendMessage(plugin.pluginName + im.getDisplayName() + " destination set. Please release the handbrake!"); } else { lore.add("§6Current location"); im.setLore(lore); is.setItemMeta(im); } } } } } }
public void onSaveTerminalClick(InventoryClickEvent event) { Inventory inv = event.getInventory(); String name = inv.getTitle(); if (name.equals("§4TARDIS saves")) { event.setCancelled(true); int slot = event.getRawSlot(); if (slot < 54) { final Player player = (Player) event.getWhoClicked(); String playerNameStr = player.getName(); HashMap<String, Object> wheres = new HashMap<String, Object>(); wheres.put("player", playerNameStr); ResultSetTravellers rst = new ResultSetTravellers(plugin, wheres, false); if (rst.resultSet()) { HashMap<String, Object> where = new HashMap<String, Object>(); where.put("tardis_id", rst.getTardis_id()); ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false); if (rs.resultSet()) { int id = rs.getTardis_id(); ItemStack is = inv.getItem(slot); if (is != null) { ItemMeta im = is.getItemMeta(); List<String> lore = im.getLore(); String save = getDestination(lore); if (!save.equals(rs.getCurrent())) { HashMap<String, Object> set = new HashMap<String, Object>(); set.put("save", save); HashMap<String, Object> wheret = new HashMap<String, Object>(); wheret.put("tardis_id", id); new QueryFactory(plugin).doUpdate("tardis", set, wheret); plugin.tardisHasDestination.put(id, plugin.getArtronConfig().getInt("random")); if (plugin.trackRescue.containsKey(Integer.valueOf(id))) { plugin.trackRescue.remove(Integer.valueOf(id)); } close(player); player.sendMessage(plugin.pluginName + im.getDisplayName() + " destination set. Please release the handbrake!"); } else if (!lore.contains("§6Current location")) { lore.add("§6Current location"); im.setLore(lore); is.setItemMeta(im); } } } } } } }
public Object[][] getContents() { Object[][] temp = new Object[][] { {"textframe.button.dismiss", "St\u00E4ng"}, {"appletviewer.tool.title", "Applet Viewer: {0}"}, {"appletviewer.menu.applet", "Applet"}, {"appletviewer.menuitem.restart", "Starta om"}, {"appletviewer.menuitem.reload", "Ladda om"}, {"appletviewer.menuitem.stop", "Stopp"}, {"appletviewer.menuitem.save", "Spara..."}, {"appletviewer.menuitem.start", "Starta"}, {"appletviewer.menuitem.clone", "Klona..."}, {"appletviewer.menuitem.tag", "Tagg..."}, {"appletviewer.menuitem.info", "Information..."}, {"appletviewer.menuitem.edit", "Redigera"}, {"appletviewer.menuitem.encoding", "Teckenkodning"}, {"appletviewer.menuitem.print", "Skriv ut..."}, {"appletviewer.menuitem.props", "Egenskaper..."}, {"appletviewer.menuitem.close", "St\u00E4ng"}, {"appletviewer.menuitem.quit", "Avsluta"}, {"appletviewer.label.hello", "Hej..."}, {"appletviewer.status.start", "startar applet..."}, {"appletviewer.appletsave.filedialogtitle","Serialisera applet till fil"}, {"appletviewer.appletsave.err1", "serialiserar {0} till {1}"}, {"appletviewer.appletsave.err2", "i appletSave: {0}"}, {"appletviewer.applettag", "Tagg visas"}, {"appletviewer.applettag.textframe", "HTML-tagg f\u00F6r applet"}, {"appletviewer.appletinfo.applet", "-- ingen appletinformation --"}, {"appletviewer.appletinfo.param", "-- ingen parameterinformation --"}, {"appletviewer.appletinfo.textframe", "Appletinformation"}, {"appletviewer.appletprint.fail", "Kunde inte skriva ut."}, {"appletviewer.appletprint.finish", "Utskriften klar."}, {"appletviewer.appletprint.cancel", "Utskriften avbruten."}, {"appletviewer.appletencoding", "Teckenkodning: {0}"}, {"appletviewer.parse.warning.requiresname", "Varning: <param name=... value=...>-taggen kr\u00E4ver ett namnattribut."}, {"appletviewer.parse.warning.paramoutside", "Varning: <param>-taggen finns utanf\u00F6r <applet> ... </applet>."}, {"appletviewer.parse.warning.applet.requirescode", "Varning: <applet>-taggen kr\u00E4ver ett kodattribut."}, {"appletviewer.parse.warning.applet.requiresheight", "Varning: <applet>-taggen kr\u00E4ver ett h\u00F6jdattribut."}, {"appletviewer.parse.warning.applet.requireswidth", "Varning: <applet>-taggen kr\u00E4ver ett breddattribut."}, {"appletviewer.parse.warning.object.requirescode", "Varning: <object>-taggen kr\u00E4ver ett kodattribut."}, {"appletviewer.parse.warning.object.requiresheight", "Varning: <object>-taggen kr\u00E4ver ett h\u00F6jdattribut."}, {"appletviewer.parse.warning.object.requireswidth", "Varning: <object>-taggen kr\u00E4ver ett breddattribut."}, {"appletviewer.parse.warning.embed.requirescode", "Varning: <embed>-taggen kr\u00E4ver ett kodattribut."}, {"appletviewer.parse.warning.embed.requiresheight", "Varning: <embed>-taggen kr\u00E4ver ett h\u00F6jdattribut."}, {"appletviewer.parse.warning.embed.requireswidth", "Varning: <embed>-taggen kr\u00E4ver ett breddattribut."}, {"appletviewer.parse.warning.appnotLongersupported", "Varning: <app>-taggen st\u00F6ds inte l\u00E4ngre, anv\u00E4nd <applet> ist\u00E4llet:"}, {"appletviewer.usage", "Syntax: appletviewer-<alternativ> url:er \n\nd\u00E4r <alternativ> inkluderar:\n -debug Startar appletvisning i Java-fels\u00F6kningen\n -encoding <kodning> Anger teckenkodning som anv\u00E4nds i HTML-filer\n -J<k\u00F6rningsflagga> \u00D6verf\u00F6r argument till Java-tolkningen\n\nAlternativet -J \u00E4r inte standard och kan \u00E4ndras utan f\u00F6reg\u00E5ende meddelande."}, {"appletviewer.main.err.unsupportedopt", "Alternativ som inte st\u00F6ds: {0}"}, {"appletviewer.main.err.unrecognizedarg", "Ok\u00E4nt argument: {0}"}, {"appletviewer.main.err.dupoption", "Duplicerat alternativ: {0}"}, {"appletviewer.main.err.inputfile", "Inga angivna indatafiler."}, {"appletviewer.main.err.badurl", "Felaktig URL: {0} ( {1} )"}, {"appletviewer.main.err.io", "I/O-undantag vid l\u00E4sning: {0}"}, {"appletviewer.main.err.readablefile", "Kontrollera att {0} \u00E4r en fil som \u00E4r l\u00E4sbar."}, {"appletviewer.main.err.correcturl", "\u00C4r {0} den korrekta URL:en?"}, {"appletviewer.main.prop.store", "Anv\u00E4ndarspecifika egenskaper f\u00F6r AppletViewer"}, {"appletviewer.main.err.prop.cantread", "Kan inte l\u00E4sa egenskapsfilen: {0}"}, {"appletviewer.main.err.prop.cantsave", "Kan inte spara egenskapsfilen: {0}"}, {"appletviewer.main.warn.nosecmgr", "Varning: s\u00E4kerheten inaktiveras."}, {"appletviewer.main.debug.cantfinddebug", "Hittar inte fels\u00F6kningsprogrammet!"}, {"appletviewer.main.debug.cantfindmain", "Hittar inte huvudmetoden i fels\u00F6kningsprogrammet!"}, {"appletviewer.main.debug.exceptionindebug", "Undantag i fels\u00F6kningsprogrammet!"}, {"appletviewer.main.debug.cantaccess", "Det finns ingen \u00E5tkomst till fels\u00F6kningsprogrammet!"}, {"appletviewer.main.nosecmgr", "Varning: SecurityManager har inte installerats!"}, {"appletviewer.main.warning", "Varning: Inga appletar har startats. Kontrollera att indata inneh\u00E5ller <applet>-tagg."}, {"appletviewer.main.warn.prop.overwrite", "Varning: Skriver tillf\u00E4lligt \u00F6ver systemegenskap enligt beg\u00E4ran fr\u00E5n anv\u00E4ndare: nyckel: {0} gammalt v\u00E4rde: {1} nytt v\u00E4rde: {2}"}, {"appletviewer.main.warn.cantreadprops", "Varning: Kan inte l\u00E4sa egenskapsfil f\u00F6r AppletViewer: {0} Standardv\u00E4rden anv\u00E4nds."}, {"appletioexception.loadclass.throw.interrupted", "klassinl\u00E4sning avbr\u00F6ts: {0}"}, {"appletioexception.loadclass.throw.notloaded", "klass inte inl\u00E4st: {0}"}, {"appletclassloader.loadcode.verbose", "\u00D6ppnar str\u00F6m till: {0} f\u00F6r h\u00E4mtning av {1}"}, {"appletclassloader.filenotfound", "Hittade inte fil vid s\u00F6kning efter: {0}"}, {"appletclassloader.fileformat", "Undantag av filformat vid l\u00E4sning av: {0}"}, {"appletclassloader.fileioexception", "I/O-undantag vid l\u00E4sning: {0}"}, {"appletclassloader.fileexception", "{0} undantag vid l\u00E4sning: {1}"}, {"appletclassloader.filedeath", "{0} avslutad vid l\u00E4sning: {1}"}, {"appletclassloader.fileerror", "{0} fel vid l\u00E4sning: {1}"}, {"appletclassloader.findclass.verbose.openstream", "\u00D6ppnar str\u00F6m till: {0} f\u00F6r h\u00E4mtning av {1}"}, {"appletclassloader.getresource.verbose.forname", "AppletClassLoader.getResource f\u00F6r namnet: {0}"}, {"appletclassloader.getresource.verbose.found", "Hittade resursen: {0} som systemresurs"}, {"appletclassloader.getresourceasstream.verbose", "Hittade resursen: {0} som systemresurs"}, {"appletpanel.runloader.err", "Antingen objekt- eller kodparameter!"}, {"appletpanel.runloader.exception", "undantag vid avserialisering {0}"}, {"appletpanel.destroyed", "Applet raderad."}, {"appletpanel.loaded", "Applet laddad."}, {"appletpanel.started", "Applet startad."}, {"appletpanel.inited", "Applet initierad."}, {"appletpanel.stopped", "Applet stoppad."}, {"appletpanel.disposed", "Applet kasserad."}, {"appletpanel.nocode", "APPLET-tagg saknar CODE-parameter."}, {"appletpanel.notfound", "load: hittade inte klassen {0}."}, {"appletpanel.nocreate", "load: {0} kan inte instansieras."}, {"appletpanel.noconstruct", "load: {0} \u00E4r inte allm\u00E4n eller saknar allm\u00E4n konstruktor."}, {"appletpanel.death", "avslutad"}, {"appletpanel.exception", "undantag: {0}."}, {"appletpanel.exception2", "undantag: {0}: {1}."}, {"appletpanel.error", "fel: {0}."}, {"appletpanel.error2", "fel {0}: {1}."}, {"appletpanel.notloaded", "Initiera: applet \u00E4r inte inl\u00E4st."}, {"appletpanel.notinited", "Starta: applet \u00E4r inte initierad."}, {"appletpanel.notstarted", "Stoppa: applet har inte startats."}, {"appletpanel.notstopped", "Radera: applet har inte stoppats."}, {"appletpanel.notdestroyed", "Kassera: applet har inte raderats."}, {"appletpanel.notdisposed", "Ladda: applet har inte kasserats."}, {"appletpanel.bail", "Avbruten."}, {"appletpanel.filenotfound", "Hittade inte fil vid s\u00F6kning efter: {0}"}, {"appletpanel.fileformat", "Undantag av filformat vid l\u00E4sning av: {0}"}, {"appletpanel.fileioexception", "I/O-undantag vid l\u00E4sning: {0}"}, {"appletpanel.fileexception", "{0} undantag vid l\u00E4sning: {1}"}, {"appletpanel.filedeath", "{0} avslutad vid l\u00E4sning: {1}"}, {"appletpanel.fileerror", "{0} fel vid l\u00E4sning: {1}"}, {"appletpanel.badattribute.exception", "HTML-tolkning: felaktigt v\u00E4rde f\u00F6r bredd-/h\u00F6jdattribut"}, {"appletillegalargumentexception.objectinputstream", "AppletObjectInputStream kr\u00E4ver laddare med icke-null"}, {"appletprops.title", "AppletViewer-egenskaper"}, {"appletprops.label.http.server", "HTTP-proxyserver:"}, {"appletprops.label.http.proxy", "HTTP-proxyport:"}, {"appletprops.label.network", "N\u00E4tverks\u00E5tkomst:"}, {"appletprops.choice.network.item.none", "Ingen"}, {"appletprops.choice.network.item.applethost", "Appletv\u00E4rd"}, {"appletprops.choice.network.item.unrestricted", "Obegr\u00E4nsad"}, {"appletprops.label.class", "Klass\u00E5tkomst:"}, {"appletprops.choice.class.item.restricted", "Begr\u00E4nsad"}, {"appletprops.choice.class.item.unrestricted", "Obegr\u00E4nsad"}, {"appletprops.label.unsignedapplet", "Till\u00E5t osignerade appletar:"}, {"appletprops.choice.unsignedapplet.no", "Nej"}, {"appletprops.choice.unsignedapplet.yes", "Ja"}, {"appletprops.button.apply", "Till\u00E4mpa"}, {"appletprops.button.cancel", "Avbryt"}, {"appletprops.button.reset", "\u00C5terst\u00E4ll"}, {"appletprops.apply.exception", "Kunde inte spara egenskaper: {0}"}, {"appletprops.title.invalidproxy", "Ogiltig post"}, {"appletprops.label.invalidproxy", "Proxyport m\u00E5ste vara ett positivt heltal."}, {"appletprops.button.ok", "OK"}, {"appletprops.prop.store", "Anv\u00E4ndarspecifika egenskaper f\u00F6r AppletViewer"}, {"appletsecurityexception.checkcreateclassloader", "S\u00E4kerhetsundantag: klassladdare"}, {"appletsecurityexception.checkaccess.thread", "S\u00E4kerhetsundantag: tr\u00E5d"}, {"appletsecurityexception.checkaccess.threadgroup", "S\u00E4kerhetsundantag: tr\u00E5dgrupp: {0}"}, {"appletsecurityexception.checkexit", "S\u00E4kerhetsundantag: utg\u00E5ng: {0}"}, {"appletsecurityexception.checkexec", "S\u00E4kerhetsundantag: exec: {0}"}, {"appletsecurityexception.checklink", "S\u00E4kerhetsundantag: l\u00E4nk: {0}"}, {"appletsecurityexception.checkpropsaccess", "S\u00E4kerhetsundantag: egenskaper"}, {"appletsecurityexception.checkpropsaccess.key", "S\u00E4kerhetsundantag: egenskaps\u00E5tkomst {0}"}, {"appletsecurityexception.checkread.exception1", "S\u00E4kerhetsundantag: {0}, {1}"}, {"appletsecurityexception.checkread.exception2", "S\u00E4kerhetsundantag: file.read: {0}"}, {"appletsecurityexception.checkread", "S\u00E4kerhetsundantag: file.read: {0} == {1}"}, {"appletsecurityexception.checkwrite.exception", "S\u00E4kerhetsundantag: {0}, {1}"}, {"appletsecurityexception.checkwrite", "S\u00E4kerhetsundantag: file.write: {0} == {1}"}, {"appletsecurityexception.checkread.fd", "S\u00E4kerhetsundantag: fd.read"}, {"appletsecurityexception.checkwrite.fd", "S\u00E4kerhetsundantag: fd.write"}, {"appletsecurityexception.checklisten", "S\u00E4kerhetsundantag: socket.listen: {0}"}, {"appletsecurityexception.checkaccept", "S\u00E4kerhetsundantag: socket.accept: {0}:{1}"}, {"appletsecurityexception.checkconnect.networknone", "S\u00E4kerhetsundantag: socket.connect: {0}->{1}"}, {"appletsecurityexception.checkconnect.networkhost1", "S\u00E4kerhetsundantag: Kunde inte ansluta till {0} med ursprung fr\u00E5n {1}."}, {"appletsecurityexception.checkconnect.networkhost2", "S\u00E4kerhetsundantag: Kunde inte matcha IP f\u00F6r v\u00E4rd {0} eller f\u00F6r {1}. "}, {"appletsecurityexception.checkconnect.networkhost3", "S\u00E4kerhetsundantag: Kunde inte matcha IP f\u00F6r v\u00E4rd {0}. Se egenskapen trustProxy."}, {"appletsecurityexception.checkconnect", "S\u00E4kerhetsundantag: connect: {0}->{1}"}, {"appletsecurityexception.checkpackageaccess", "S\u00E4kerhetsundantag: ingen \u00E5tkomst till paket: {0}"}, {"appletsecurityexception.checkpackagedefinition", "S\u00E4kerhetsundantag: kan inte definiera paket: {0}"}, {"appletsecurityexception.cannotsetfactory", "S\u00E4kerhetsundantag: kan inte ange fabrik"}, {"appletsecurityexception.checkmemberaccess", "S\u00E4kerhetsundantag: kontrollera medlems\u00E5tkomst"}, {"appletsecurityexception.checkgetprintjob", "S\u00E4kerhetsundantag: getPrintJob"}, {"appletsecurityexception.checksystemclipboardaccess", "S\u00E4kerhetsundantag: getSystemClipboard"}, {"appletsecurityexception.checkawteventqueueaccess", "S\u00E4kerhetsundantag: getEventQueue"}, {"appletsecurityexception.checksecurityaccess", "S\u00E4kerhetsundantag: s\u00E4kerhets\u00E5tg\u00E4rd: {0}"}, {"appletsecurityexception.getsecuritycontext.unknown", "ok\u00E4nd typ av klassladdare. kan inte kontrollera getContext"}, {"appletsecurityexception.checkread.unknown", "ok\u00E4nd typ av klassladdare. kan inte kontrollera kontroll\u00E4sning {0}"}, {"appletsecurityexception.checkconnect.unknown", "ok\u00E4nd typ av klassladdare. kan inte kontrollera kontrollanslutning"}, }; return temp; }
public Object[][] getContents() { Object[][] temp = new Object[][] { {"textframe.button.dismiss", "St\u00E4ng"}, {"appletviewer.tool.title", "Applet Viewer: {0}"}, {"appletviewer.menu.applet", "Applet"}, {"appletviewer.menuitem.restart", "Starta om"}, {"appletviewer.menuitem.reload", "Ladda om"}, {"appletviewer.menuitem.stop", "Stopp"}, {"appletviewer.menuitem.save", "Spara..."}, {"appletviewer.menuitem.start", "Starta"}, {"appletviewer.menuitem.clone", "Klona..."}, {"appletviewer.menuitem.tag", "Tagg..."}, {"appletviewer.menuitem.info", "Information..."}, {"appletviewer.menuitem.edit", "Redigera"}, {"appletviewer.menuitem.encoding", "Teckenkodning"}, {"appletviewer.menuitem.print", "Skriv ut..."}, {"appletviewer.menuitem.props", "Egenskaper..."}, {"appletviewer.menuitem.close", "St\u00E4ng"}, {"appletviewer.menuitem.quit", "Avsluta"}, {"appletviewer.label.hello", "Hej..."}, {"appletviewer.status.start", "startar applet..."}, {"appletviewer.appletsave.filedialogtitle","Serialisera applet till fil"}, {"appletviewer.appletsave.err1", "serialiserar {0} till {1}"}, {"appletviewer.appletsave.err2", "i appletSave: {0}"}, {"appletviewer.applettag", "Tagg visas"}, {"appletviewer.applettag.textframe", "HTML-tagg f\u00F6r applet"}, {"appletviewer.appletinfo.applet", "-- ingen appletinformation --"}, {"appletviewer.appletinfo.param", "-- ingen parameterinformation --"}, {"appletviewer.appletinfo.textframe", "Appletinformation"}, {"appletviewer.appletprint.fail", "Kunde inte skriva ut."}, {"appletviewer.appletprint.finish", "Utskriften klar."}, {"appletviewer.appletprint.cancel", "Utskriften avbruten."}, {"appletviewer.appletencoding", "Teckenkodning: {0}"}, {"appletviewer.parse.warning.requiresname", "Varning: <param name=... value=...>-taggen kr\u00E4ver ett namnattribut."}, {"appletviewer.parse.warning.paramoutside", "Varning: <param>-taggen finns utanf\u00F6r <applet> ... </applet>."}, {"appletviewer.parse.warning.applet.requirescode", "Varning: <applet>-taggen kr\u00E4ver ett kodattribut."}, {"appletviewer.parse.warning.applet.requiresheight", "Varning: <applet>-taggen kr\u00E4ver ett h\u00F6jdattribut."}, {"appletviewer.parse.warning.applet.requireswidth", "Varning: <applet>-taggen kr\u00E4ver ett breddattribut."}, {"appletviewer.parse.warning.object.requirescode", "Varning: <object>-taggen kr\u00E4ver ett kodattribut."}, {"appletviewer.parse.warning.object.requiresheight", "Varning: <object>-taggen kr\u00E4ver ett h\u00F6jdattribut."}, {"appletviewer.parse.warning.object.requireswidth", "Varning: <object>-taggen kr\u00E4ver ett breddattribut."}, {"appletviewer.parse.warning.embed.requirescode", "Varning: <embed>-taggen kr\u00E4ver ett kodattribut."}, {"appletviewer.parse.warning.embed.requiresheight", "Varning: <embed>-taggen kr\u00E4ver ett h\u00F6jdattribut."}, {"appletviewer.parse.warning.embed.requireswidth", "Varning: <embed>-taggen kr\u00E4ver ett breddattribut."}, {"appletviewer.parse.warning.appnotLongersupported", "Varning: <app>-taggen st\u00F6ds inte l\u00E4ngre, anv\u00E4nd <applet> ist\u00E4llet:"}, {"appletviewer.usage", "Syntax: appletviewer <alternativ> url:er \n\nd\u00E4r <alternativ> inkluderar:\n -debug Startar appletvisning i Java-fels\u00F6kningen\n -encoding <kodning> Anger teckenkodning som anv\u00E4nds i HTML-filer\n -J<k\u00F6rningsflagga> \u00D6verf\u00F6r argument till Java-tolkningen\n\nAlternativet -J \u00E4r inte standard och kan \u00E4ndras utan f\u00F6reg\u00E5ende meddelande."}, {"appletviewer.main.err.unsupportedopt", "Alternativ som inte st\u00F6ds: {0}"}, {"appletviewer.main.err.unrecognizedarg", "Ok\u00E4nt argument: {0}"}, {"appletviewer.main.err.dupoption", "Duplicerat alternativ: {0}"}, {"appletviewer.main.err.inputfile", "Inga angivna indatafiler."}, {"appletviewer.main.err.badurl", "Felaktig URL: {0} ( {1} )"}, {"appletviewer.main.err.io", "I/O-undantag vid l\u00E4sning: {0}"}, {"appletviewer.main.err.readablefile", "Kontrollera att {0} \u00E4r en fil som \u00E4r l\u00E4sbar."}, {"appletviewer.main.err.correcturl", "\u00C4r {0} den korrekta URL:en?"}, {"appletviewer.main.prop.store", "Anv\u00E4ndarspecifika egenskaper f\u00F6r AppletViewer"}, {"appletviewer.main.err.prop.cantread", "Kan inte l\u00E4sa egenskapsfilen: {0}"}, {"appletviewer.main.err.prop.cantsave", "Kan inte spara egenskapsfilen: {0}"}, {"appletviewer.main.warn.nosecmgr", "Varning: s\u00E4kerheten inaktiveras."}, {"appletviewer.main.debug.cantfinddebug", "Hittar inte fels\u00F6kningsprogrammet!"}, {"appletviewer.main.debug.cantfindmain", "Hittar inte huvudmetoden i fels\u00F6kningsprogrammet!"}, {"appletviewer.main.debug.exceptionindebug", "Undantag i fels\u00F6kningsprogrammet!"}, {"appletviewer.main.debug.cantaccess", "Det finns ingen \u00E5tkomst till fels\u00F6kningsprogrammet!"}, {"appletviewer.main.nosecmgr", "Varning: SecurityManager har inte installerats!"}, {"appletviewer.main.warning", "Varning: Inga appletar har startats. Kontrollera att indata inneh\u00E5ller <applet>-tagg."}, {"appletviewer.main.warn.prop.overwrite", "Varning: Skriver tillf\u00E4lligt \u00F6ver systemegenskap enligt beg\u00E4ran fr\u00E5n anv\u00E4ndare: nyckel: {0} gammalt v\u00E4rde: {1} nytt v\u00E4rde: {2}"}, {"appletviewer.main.warn.cantreadprops", "Varning: Kan inte l\u00E4sa egenskapsfil f\u00F6r AppletViewer: {0} Standardv\u00E4rden anv\u00E4nds."}, {"appletioexception.loadclass.throw.interrupted", "klassinl\u00E4sning avbr\u00F6ts: {0}"}, {"appletioexception.loadclass.throw.notloaded", "klass inte inl\u00E4st: {0}"}, {"appletclassloader.loadcode.verbose", "\u00D6ppnar str\u00F6m till: {0} f\u00F6r h\u00E4mtning av {1}"}, {"appletclassloader.filenotfound", "Hittade inte fil vid s\u00F6kning efter: {0}"}, {"appletclassloader.fileformat", "Undantag av filformat vid l\u00E4sning av: {0}"}, {"appletclassloader.fileioexception", "I/O-undantag vid l\u00E4sning: {0}"}, {"appletclassloader.fileexception", "{0} undantag vid l\u00E4sning: {1}"}, {"appletclassloader.filedeath", "{0} avslutad vid l\u00E4sning: {1}"}, {"appletclassloader.fileerror", "{0} fel vid l\u00E4sning: {1}"}, {"appletclassloader.findclass.verbose.openstream", "\u00D6ppnar str\u00F6m till: {0} f\u00F6r h\u00E4mtning av {1}"}, {"appletclassloader.getresource.verbose.forname", "AppletClassLoader.getResource f\u00F6r namnet: {0}"}, {"appletclassloader.getresource.verbose.found", "Hittade resursen: {0} som systemresurs"}, {"appletclassloader.getresourceasstream.verbose", "Hittade resursen: {0} som systemresurs"}, {"appletpanel.runloader.err", "Antingen objekt- eller kodparameter!"}, {"appletpanel.runloader.exception", "undantag vid avserialisering {0}"}, {"appletpanel.destroyed", "Applet raderad."}, {"appletpanel.loaded", "Applet laddad."}, {"appletpanel.started", "Applet startad."}, {"appletpanel.inited", "Applet initierad."}, {"appletpanel.stopped", "Applet stoppad."}, {"appletpanel.disposed", "Applet kasserad."}, {"appletpanel.nocode", "APPLET-tagg saknar CODE-parameter."}, {"appletpanel.notfound", "load: hittade inte klassen {0}."}, {"appletpanel.nocreate", "load: {0} kan inte instansieras."}, {"appletpanel.noconstruct", "load: {0} \u00E4r inte allm\u00E4n eller saknar allm\u00E4n konstruktor."}, {"appletpanel.death", "avslutad"}, {"appletpanel.exception", "undantag: {0}."}, {"appletpanel.exception2", "undantag: {0}: {1}."}, {"appletpanel.error", "fel: {0}."}, {"appletpanel.error2", "fel {0}: {1}."}, {"appletpanel.notloaded", "Initiera: applet \u00E4r inte inl\u00E4st."}, {"appletpanel.notinited", "Starta: applet \u00E4r inte initierad."}, {"appletpanel.notstarted", "Stoppa: applet har inte startats."}, {"appletpanel.notstopped", "Radera: applet har inte stoppats."}, {"appletpanel.notdestroyed", "Kassera: applet har inte raderats."}, {"appletpanel.notdisposed", "Ladda: applet har inte kasserats."}, {"appletpanel.bail", "Avbruten."}, {"appletpanel.filenotfound", "Hittade inte fil vid s\u00F6kning efter: {0}"}, {"appletpanel.fileformat", "Undantag av filformat vid l\u00E4sning av: {0}"}, {"appletpanel.fileioexception", "I/O-undantag vid l\u00E4sning: {0}"}, {"appletpanel.fileexception", "{0} undantag vid l\u00E4sning: {1}"}, {"appletpanel.filedeath", "{0} avslutad vid l\u00E4sning: {1}"}, {"appletpanel.fileerror", "{0} fel vid l\u00E4sning: {1}"}, {"appletpanel.badattribute.exception", "HTML-tolkning: felaktigt v\u00E4rde f\u00F6r bredd-/h\u00F6jdattribut"}, {"appletillegalargumentexception.objectinputstream", "AppletObjectInputStream kr\u00E4ver laddare med icke-null"}, {"appletprops.title", "AppletViewer-egenskaper"}, {"appletprops.label.http.server", "HTTP-proxyserver:"}, {"appletprops.label.http.proxy", "HTTP-proxyport:"}, {"appletprops.label.network", "N\u00E4tverks\u00E5tkomst:"}, {"appletprops.choice.network.item.none", "Ingen"}, {"appletprops.choice.network.item.applethost", "Appletv\u00E4rd"}, {"appletprops.choice.network.item.unrestricted", "Obegr\u00E4nsad"}, {"appletprops.label.class", "Klass\u00E5tkomst:"}, {"appletprops.choice.class.item.restricted", "Begr\u00E4nsad"}, {"appletprops.choice.class.item.unrestricted", "Obegr\u00E4nsad"}, {"appletprops.label.unsignedapplet", "Till\u00E5t osignerade appletar:"}, {"appletprops.choice.unsignedapplet.no", "Nej"}, {"appletprops.choice.unsignedapplet.yes", "Ja"}, {"appletprops.button.apply", "Till\u00E4mpa"}, {"appletprops.button.cancel", "Avbryt"}, {"appletprops.button.reset", "\u00C5terst\u00E4ll"}, {"appletprops.apply.exception", "Kunde inte spara egenskaper: {0}"}, {"appletprops.title.invalidproxy", "Ogiltig post"}, {"appletprops.label.invalidproxy", "Proxyport m\u00E5ste vara ett positivt heltal."}, {"appletprops.button.ok", "OK"}, {"appletprops.prop.store", "Anv\u00E4ndarspecifika egenskaper f\u00F6r AppletViewer"}, {"appletsecurityexception.checkcreateclassloader", "S\u00E4kerhetsundantag: klassladdare"}, {"appletsecurityexception.checkaccess.thread", "S\u00E4kerhetsundantag: tr\u00E5d"}, {"appletsecurityexception.checkaccess.threadgroup", "S\u00E4kerhetsundantag: tr\u00E5dgrupp: {0}"}, {"appletsecurityexception.checkexit", "S\u00E4kerhetsundantag: utg\u00E5ng: {0}"}, {"appletsecurityexception.checkexec", "S\u00E4kerhetsundantag: exec: {0}"}, {"appletsecurityexception.checklink", "S\u00E4kerhetsundantag: l\u00E4nk: {0}"}, {"appletsecurityexception.checkpropsaccess", "S\u00E4kerhetsundantag: egenskaper"}, {"appletsecurityexception.checkpropsaccess.key", "S\u00E4kerhetsundantag: egenskaps\u00E5tkomst {0}"}, {"appletsecurityexception.checkread.exception1", "S\u00E4kerhetsundantag: {0}, {1}"}, {"appletsecurityexception.checkread.exception2", "S\u00E4kerhetsundantag: file.read: {0}"}, {"appletsecurityexception.checkread", "S\u00E4kerhetsundantag: file.read: {0} == {1}"}, {"appletsecurityexception.checkwrite.exception", "S\u00E4kerhetsundantag: {0}, {1}"}, {"appletsecurityexception.checkwrite", "S\u00E4kerhetsundantag: file.write: {0} == {1}"}, {"appletsecurityexception.checkread.fd", "S\u00E4kerhetsundantag: fd.read"}, {"appletsecurityexception.checkwrite.fd", "S\u00E4kerhetsundantag: fd.write"}, {"appletsecurityexception.checklisten", "S\u00E4kerhetsundantag: socket.listen: {0}"}, {"appletsecurityexception.checkaccept", "S\u00E4kerhetsundantag: socket.accept: {0}:{1}"}, {"appletsecurityexception.checkconnect.networknone", "S\u00E4kerhetsundantag: socket.connect: {0}->{1}"}, {"appletsecurityexception.checkconnect.networkhost1", "S\u00E4kerhetsundantag: Kunde inte ansluta till {0} med ursprung fr\u00E5n {1}."}, {"appletsecurityexception.checkconnect.networkhost2", "S\u00E4kerhetsundantag: Kunde inte matcha IP f\u00F6r v\u00E4rd {0} eller f\u00F6r {1}. "}, {"appletsecurityexception.checkconnect.networkhost3", "S\u00E4kerhetsundantag: Kunde inte matcha IP f\u00F6r v\u00E4rd {0}. Se egenskapen trustProxy."}, {"appletsecurityexception.checkconnect", "S\u00E4kerhetsundantag: connect: {0}->{1}"}, {"appletsecurityexception.checkpackageaccess", "S\u00E4kerhetsundantag: ingen \u00E5tkomst till paket: {0}"}, {"appletsecurityexception.checkpackagedefinition", "S\u00E4kerhetsundantag: kan inte definiera paket: {0}"}, {"appletsecurityexception.cannotsetfactory", "S\u00E4kerhetsundantag: kan inte ange fabrik"}, {"appletsecurityexception.checkmemberaccess", "S\u00E4kerhetsundantag: kontrollera medlems\u00E5tkomst"}, {"appletsecurityexception.checkgetprintjob", "S\u00E4kerhetsundantag: getPrintJob"}, {"appletsecurityexception.checksystemclipboardaccess", "S\u00E4kerhetsundantag: getSystemClipboard"}, {"appletsecurityexception.checkawteventqueueaccess", "S\u00E4kerhetsundantag: getEventQueue"}, {"appletsecurityexception.checksecurityaccess", "S\u00E4kerhetsundantag: s\u00E4kerhets\u00E5tg\u00E4rd: {0}"}, {"appletsecurityexception.getsecuritycontext.unknown", "ok\u00E4nd typ av klassladdare. kan inte kontrollera getContext"}, {"appletsecurityexception.checkread.unknown", "ok\u00E4nd typ av klassladdare. kan inte kontrollera kontroll\u00E4sning {0}"}, {"appletsecurityexception.checkconnect.unknown", "ok\u00E4nd typ av klassladdare. kan inte kontrollera kontrollanslutning"}, }; return temp; }
public void setUp() throws Exception { dbPropFile = File.createTempFile("database", ".properties"); appPropFile = File.createTempFile("application", ".properties"); BufferedWriter dbwriter = new BufferedWriter(new FileWriter(dbPropFile)); BufferedWriter appwriter = new BufferedWriter(new FileWriter(appPropFile)); dbwriter.write("db.driver=org.hsqldb.jdbcDriver"); dbwriter.newLine(); dbwriter.write("db.user=sa"); dbwriter.newLine(); dbwriter.write("db.password="); dbwriter.newLine(); dbwriter.write("db.connection=jdbc:hsqldb:mem:demo"); appwriter.write("json.dir=~/workshop/json"); dbwriter.flush(); appwriter.flush(); }
public void setUp() throws Exception { dbPropFile = File.createTempFile("database", ".properties"); appPropFile = File.createTempFile("application", ".properties"); BufferedWriter dbwriter = new BufferedWriter(new FileWriter(dbPropFile)); BufferedWriter appwriter = new BufferedWriter(new FileWriter(appPropFile)); dbwriter.write("db.driver=org.hsqldb.jdbcDriver"); dbwriter.newLine(); dbwriter.write("db.user=sa"); dbwriter.newLine(); dbwriter.write("db.password="); dbwriter.newLine(); dbwriter.write("db.connection=jdbc:hsqldb:mem:demo"); appwriter.write("json.dir=/home/ebernie/json"); dbwriter.flush(); appwriter.flush(); }
public void map(long position, Map<FeatureSet, Collection<Feature>> atoms, MapperInterface<Text, Text> mapperInterface) { Set<Feature> featuresAtCurrentLocation = new HashSet<Feature>(); for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { if (f.getStart() == position) { featuresAtCurrentLocation.add(f); } } } for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { String fOverlapID = f.getTagByKey("id").getValue().toString(); for (Feature positionFeature : featuresAtCurrentLocation) { String positionFeatureVarID = calculateVarID(positionFeature); String positionOverlapID = positionFeature.getTagByKey("id").getValue().toString(); String fFeatureVarID = calculateVarID(positionFeature); if (positionFeatureVarID.equals(fFeatureVarID)){ continue; } textKey.set(positionFeatureVarID); text.set(fOverlapID); mapperInterface.write(textKey, text); textKey.set(fFeatureVarID); text.set(positionOverlapID); mapperInterface.write(textKey, text); } } } }
public void map(long position, Map<FeatureSet, Collection<Feature>> atoms, MapperInterface<Text, Text> mapperInterface) { Set<Feature> featuresAtCurrentLocation = new HashSet<Feature>(); for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { if (f.getStart() == position) { featuresAtCurrentLocation.add(f); } } } for (FeatureSet fs : atoms.keySet()) { for (Feature f : atoms.get(fs)) { String fOverlapID = f.getTagByKey("id").getValue().toString(); for (Feature positionFeature : featuresAtCurrentLocation) { String positionFeatureVarID = calculateVarID(positionFeature); String positionOverlapID = positionFeature.getTagByKey("id").getValue().toString(); String fFeatureVarID = calculateVarID(f); if (positionFeatureVarID.equals(fFeatureVarID)){ continue; } textKey.set(positionFeatureVarID); text.set(fOverlapID); mapperInterface.write(textKey, text); textKey.set(fFeatureVarID); text.set(positionOverlapID); mapperInterface.write(textKey, text); } } } }
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction(); flatList = new FlatListFragment(); ft.replace(R.id.list, flatList,"flat_fragment"); ft.commit(); if(settingsOpen == 1){ android.support.v4.app.FragmentTransaction ft2 = getFragmentManager().beginTransaction(); Fragment settings = new FlatSettingsFragment(); ft2.replace(R.id.list, settings,"Set_fragment"); ft2.commit(); ((ImageView) c.findViewById(R.id.settingsButton)).setImageResource(R.drawable.flatmates_tab); c.findViewById(R.id.map_button).setVisibility(View.GONE); } final Button button = (Button) c.findViewById(R.id.map_button); FlatDataExchanger.flatData.updateDebts(); if(debtsOpen == 1){ debtsOpen = 0; button.setText("View Debts"); }else{ button.setText("View Debts"); } button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(debtsOpen == 0){ button.setText("View Contact Buttons"); debtsOpen = 1; flatList.setDebtsVisible(1); }else{ debtsOpen = 0; button.setText("View Debts"); flatList.setDebtsVisible(0); } } }); final ImageButton settings = (ImageButton) c.findViewById(R.id.settingsButton); settings.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(settingsOpen == 0){ settingsOpen = 1; settings.setImageResource(R.drawable.flatmates_tab); android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction(); Fragment set = new FlatSettingsFragment(); ft.replace(R.id.list, set, "Set_fragment"); ft.commit(); button.setVisibility(View.GONE); }else{ settingsOpen = 0; settings.setImageResource(R.drawable.settings); getFragmentManager().popBackStack(); button.setVisibility(View.VISIBLE); } } });
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction(); flatList = new FlatListFragment(); ft.replace(R.id.list, flatList,"flat_fragment"); ft.commit(); if(settingsOpen == 1){ android.support.v4.app.FragmentTransaction ft2 = getFragmentManager().beginTransaction(); Fragment settings = new FlatSettingsFragment(); ft2.replace(R.id.list, settings,"Set_fragment"); ft2.commit(); ((ImageView) c.findViewById(R.id.settingsButton)).setImageResource(R.drawable.flatmates_tab); c.findViewById(R.id.map_button).setVisibility(View.GONE); } final Button button = (Button) c.findViewById(R.id.map_button); FlatDataExchanger.flatData.updateDebts(); if(debtsOpen == 1){ debtsOpen = 0; button.setText("View Debts"); }else{ button.setText("View Debts"); } button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(debtsOpen == 0){ button.setText("View Contact Buttons"); debtsOpen = 1; flatList.setDebtsVisible(1); }else{ debtsOpen = 0; button.setText("View Debts"); flatList.setDebtsVisible(0); } } }); final ImageButton settings = (ImageButton) c.findViewById(R.id.settingsButton); settings.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(settingsOpen == 0){ settingsOpen = 1; settings.setImageResource(R.drawable.flatmates_tab); android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction(); Fragment set = new FlatSettingsFragment(); ft.replace(R.id.list, set, "Set_fragment"); ft.commit(); button.setVisibility(View.GONE); }else{ settingsOpen = 0; settings.setImageResource(R.drawable.settings); android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction(); flatList = new FlatListFragment(); ft.replace(R.id.list, flatList, "flat_fragment"); ft.commit(); button.setVisibility(View.VISIBLE); } } });
public BundleDiscoverySource(Bundle bundle) { if (bundle == null) { throw new IllegalArgumentException(); } this.bundle = bundle; setPolicy(new Policy(true)); }
public BundleDiscoverySource(Bundle bundle) { if (bundle == null) { throw new IllegalArgumentException(); } this.bundle = bundle; }
private void createLabelRow() { Composite labelComposite = new Composite(this, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 6; gridLayout.horizontalSpacing = 5; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; labelComposite.setLayout(gridLayout); labelComposite.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); Label txtLabel = new Label(labelComposite, SWT.NONE); txtLabel.setText(" " + UIUtils.getDisplayName(locale) + " "); txtLabel.setFont(boldFont); GridData gridData = new GridData(); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gridData.grabExcessHorizontalSpace = true; simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); simButton.setImage(UIUtils.getImage("similar.gif")); simButton.setLayoutData(gridData); simButton.setVisible(false); simButton.setToolTipText( RBEPlugin.getString("value.similar.tooltip")); simButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.similar.head"); String body = RBEPlugin.getString( "dialog.similar.body", activeKey, UIUtils.getDisplayName(locale)); body += "\":\n\n"; for (Iterator iter = similarVisitor.getSimilars().iterator(); iter.hasNext();) { body += " " + ((BundleEntry) iter.next()).getKey() + "\n"; } MessageDialog.openInformation(getShell(), head, body); } }); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); duplButton.setImage(UIUtils.getImage("duplicate.gif")); duplButton.setLayoutData(gridData); duplButton.setVisible(false); duplButton.setToolTipText( RBEPlugin.getString("value.duplicate.tooltip")); duplButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.identical.head"); String body = RBEPlugin.getString( "dialog.identical.body", activeKey, UIUtils.getDisplayName(locale)); body += "\":\n\n"; for (Iterator iter = duplVisitor.getDuplicates().iterator(); iter.hasNext();) { body += " " + ((BundleEntry) iter.next()).getKey() + "\n"; } MessageDialog.openInformation(getShell(), head, body); } }); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; commentedCheckbox = new Button( labelComposite, SWT.CHECK); commentedCheckbox.setText("#"); commentedCheckbox.setFont(smallFont); commentedCheckbox.setLayoutData(gridData); commentedCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { resetCommented(); updateBundleOnChanges(); } }); commentedCheckbox.setEnabled(false); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; Label imgLabel = new Label(labelComposite, SWT.NONE); imgLabel.setLayoutData(gridData); imgLabel.setImage(loadCountryIcon(locale)); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gotoButton = new Button( labelComposite, SWT.ARROW | SWT.RIGHT); gotoButton.setToolTipText( RBEPlugin.getString("value.goto.tooltip")); gotoButton.setEnabled(false); gotoButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ITextEditor editor = resourceManager.getSourceEditor( locale).getEditor(); Object activeEditor = editor.getSite().getPage().getActiveEditor(); if (activeEditor instanceof ResourceBundleEditor) { ((ResourceBundleEditor) activeEditor).setActivePage(locale); } } }); gotoButton.setLayoutData(gridData); }
private void createLabelRow() { Composite labelComposite = new Composite(this, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 6; gridLayout.horizontalSpacing = 5; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; labelComposite.setLayout(gridLayout); labelComposite.setLayoutData( new GridData(GridData.FILL_HORIZONTAL)); Label txtLabel = new Label(labelComposite, SWT.NONE); txtLabel.setText(" " + UIUtils.getDisplayName(locale) + " "); txtLabel.setFont(boldFont); GridData gridData = new GridData(); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gridData.grabExcessHorizontalSpace = true; simButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); simButton.setImage(UIUtils.getImage("similar.gif")); simButton.setLayoutData(gridData); simButton.setVisible(false); simButton.setToolTipText( RBEPlugin.getString("value.similar.tooltip")); simButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.similar.head"); String body = RBEPlugin.getString( "dialog.similar.body", activeKey, UIUtils.getDisplayName(locale)); body += "\n\n"; for (Iterator iter = similarVisitor.getSimilars().iterator(); iter.hasNext();) { body += " " + ((BundleEntry) iter.next()).getKey() + "\n"; } MessageDialog.openInformation(getShell(), head, body); } }); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; duplButton = new Button(labelComposite, SWT.PUSH | SWT.FLAT); duplButton.setImage(UIUtils.getImage("duplicate.gif")); duplButton.setLayoutData(gridData); duplButton.setVisible(false); duplButton.setToolTipText( RBEPlugin.getString("value.duplicate.tooltip")); duplButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String head = RBEPlugin.getString( "dialog.identical.head"); String body = RBEPlugin.getString( "dialog.identical.body", activeKey, UIUtils.getDisplayName(locale)); body += "\n\n"; for (Iterator iter = duplVisitor.getDuplicates().iterator(); iter.hasNext();) { body += " " + ((BundleEntry) iter.next()).getKey() + "\n"; } MessageDialog.openInformation(getShell(), head, body); } }); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; commentedCheckbox = new Button( labelComposite, SWT.CHECK); commentedCheckbox.setText("#"); commentedCheckbox.setFont(smallFont); commentedCheckbox.setLayoutData(gridData); commentedCheckbox.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { resetCommented(); updateBundleOnChanges(); } }); commentedCheckbox.setEnabled(false); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; Label imgLabel = new Label(labelComposite, SWT.NONE); imgLabel.setLayoutData(gridData); imgLabel.setImage(loadCountryIcon(locale)); gridData = new GridData(); gridData.horizontalAlignment = GridData.END; gotoButton = new Button( labelComposite, SWT.ARROW | SWT.RIGHT); gotoButton.setToolTipText( RBEPlugin.getString("value.goto.tooltip")); gotoButton.setEnabled(false); gotoButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ITextEditor editor = resourceManager.getSourceEditor( locale).getEditor(); Object activeEditor = editor.getSite().getPage().getActiveEditor(); if (activeEditor instanceof ResourceBundleEditor) { ((ResourceBundleEditor) activeEditor).setActivePage(locale); } } }); gotoButton.setLayoutData(gridData); }
public void onStart() { super.onStart(); LObjDictionary loDict = null; LabBook.registerFactory(new DataObjFactory()); graph.Bin.START_DATA_SIZE = 25000; graph.LargeFloatArray.MaxNumChunks = 25; int dictHeight = myHeight; LabBookDB lbDB; String plat = waba.sys.Vm.getPlatform(); if(plat.equals("PalmOS")){ graph.Bin.START_DATA_SIZE = 4000; graph.LargeFloatArray.MaxNumChunks = 4; GraphSettings.MAX_COLLECTIONS = 1; graph.GraphViewLine.scrollStepSize = 0.45f; lbDB = new LabBookCatalog("LabBook"); CCTextArea.INTER_LINE_SPACING = 0; Dialog.showImages = false; } else if(plat.equals("Java")){ lbDB = new LabBookFile("LabBook"); } else { lbDB = new LabBookFile("LabBook"); GraphSettings.MAX_COLLECTIONS = 4; } if(myHeight < 180){ yOffset = 13; dictHeight -= 13; if(title == null) title = new Title("CCProbe"); title.setRect(0,0,width, 13); me.add(title); } if(lbDB.getError()){ exit(0); } if(plat.equals("PalmOS")){ addFileMenuItems(palmFileStrings, null); } else if(plat.equals("Java")){ addFileMenuItems(javaFileStrings, null); } else { addFileMenuItems(ceFileStrings, null); } Debug.println("Openning"); labBook.open(lbDB); LabObjectPtr rootPtr = labBook.getRoot(); mainSession = rootPtr.getSession(); loDict = (LObjDictionary)mainSession.getObj(rootPtr); if(loDict == null){ loDict = DefaultFactory.createDictionary(); loDict.setName("Home"); mainSession.storeNew(loDict); labBook.store(loDict); } LabObjectView view = (LabObjectView)loDict.getView(this, true, mainSession); view.setRect(x,yOffset,width,dictHeight); view.setShowMenus(true); me.add(view); lObjView = view; newIndex = loDict.getChildCount(); if(plat.equals("PalmOS")){ ((LObjDictionaryView)view).checkForBeam(); } }
public void onStart() { super.onStart(); LObjDictionary loDict = null; LabBook.registerFactory(new DataObjFactory()); graph.Bin.START_DATA_SIZE = 25000; graph.LargeFloatArray.MaxNumChunks = 25; int dictHeight = myHeight; LabBookDB lbDB; String plat = waba.sys.Vm.getPlatform(); if(plat.equals("PalmOS")){ graph.Bin.START_DATA_SIZE = 4000; graph.LargeFloatArray.MaxNumChunks = 4; GraphSettings.MAX_COLLECTIONS = 1; graph.GraphViewLine.scrollStepSize = 0.45f; lbDB = new LabBookCatalog("LabBook"); CCTextArea.INTER_LINE_SPACING = 0; Dialog.showImages = false; } else if(plat.equals("Java")){ lbDB = new LabBookCatalog("LabBook"); } else { lbDB = new LabBookFile("LabBook"); GraphSettings.MAX_COLLECTIONS = 4; } if(myHeight < 180){ yOffset = 13; dictHeight -= 13; if(title == null) title = new Title("CCProbe"); title.setRect(0,0,width, 13); me.add(title); } if(lbDB.getError()){ exit(0); } if(plat.equals("PalmOS")){ addFileMenuItems(palmFileStrings, null); } else if(plat.equals("Java")){ addFileMenuItems(javaFileStrings, null); } else { addFileMenuItems(ceFileStrings, null); } Debug.println("Openning"); labBook.open(lbDB); LabObjectPtr rootPtr = labBook.getRoot(); mainSession = rootPtr.getSession(); loDict = (LObjDictionary)mainSession.getObj(rootPtr); if(loDict == null){ loDict = DefaultFactory.createDictionary(); loDict.setName("Home"); mainSession.storeNew(loDict); labBook.store(loDict); } LabObjectView view = (LabObjectView)loDict.getView(this, true, mainSession); view.setRect(x,yOffset,width,dictHeight); view.setShowMenus(true); me.add(view); lObjView = view; newIndex = loDict.getChildCount(); if(plat.equals("PalmOS")){ ((LObjDictionaryView)view).checkForBeam(); } }
public static UnixUserGroupInformation login() throws LoginException { try { String userName; try { userName = getUnixUserName(); } catch (Exception e) { userName = DEFAULT_USERNAME; } UnixUserGroupInformation ugi = user2UGIMap.get(userName); if (ugi != null) { return ugi; } String[] groupNames; try { groupNames = getUnixGroups(); } catch (Exception e) { groupNames = new String[1]; groupNames[0] = DEFAULT_GROUP; } ugi = new UnixUserGroupInformation(userName, groupNames); user2UGIMap.put(ugi.getUserName(), ugi); return ugi; } catch (Exception e) { throw new LoginException("Login failed: "+e.getMessage()); } }
public static UnixUserGroupInformation login() throws LoginException { try { String userName; try { userName = getUnixUserName(); } catch (Exception e) { LOG.warn("Couldn't get unix username, using " + DEFAULT_USERNAME, e); userName = DEFAULT_USERNAME; } UnixUserGroupInformation ugi = user2UGIMap.get(userName); if (ugi != null) { return ugi; } String[] groupNames; try { groupNames = getUnixGroups(); } catch (Exception e) { LOG.warn("Couldn't get unix groups, using " + DEFAULT_GROUP, e); groupNames = new String[1]; groupNames[0] = DEFAULT_GROUP; } ugi = new UnixUserGroupInformation(userName, groupNames); user2UGIMap.put(ugi.getUserName(), ugi); return ugi; } catch (Exception e) { throw new LoginException("Login failed: "+e.getMessage()); } }
public Constraint ( String s ) { if ( s.indexOf ( ">=" ) > 0 ) op = ">=" ; if ( s.indexOf ( "<=" ) > 0 ) op = "<=" ; if ( s.indexOf ( "<=" ) > 0 ) op = "<=" ; if ( s.indexOf ( "=<" ) > 0 ) op = "=<" ; if ( s.indexOf ( "!=" ) > 0 ) op = "!=" ; if ( s.indexOf ( ">=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "=<" ) == -1 && s.indexOf ( "!=" ) == -1 ) { if ( s.indexOf ( "<" ) > 0 ) op = "<" ; if ( s.indexOf ( "=" ) > 0 ) op = "=" ; if ( s.indexOf ( ">" ) > 0 ) op = ">" ; } StringTokenizer tok = new StringTokenizer ( s, " <>=!" ) ; first = tok.nextToken () ; second = tok.nextToken () ; }
public Constraint ( String s ) { if ( s.indexOf ( ">=" ) > 0 ) op = ">=" ; if ( s.indexOf ( "<=" ) > 0 ) op = "<=" ; if ( s.indexOf ( "=>" ) > 0 ) op = "=>" ; if ( s.indexOf ( "=<" ) > 0 ) op = "=<" ; if ( s.indexOf ( "!=" ) > 0 ) op = "!=" ; if ( s.indexOf ( ">=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "<=" ) == -1 && s.indexOf ( "=<" ) == -1 && s.indexOf ( "!=" ) == -1 ) { if ( s.indexOf ( "<" ) > 0 ) op = "<" ; if ( s.indexOf ( "=" ) > 0 ) op = "=" ; if ( s.indexOf ( ">" ) > 0 ) op = ">" ; } StringTokenizer tok = new StringTokenizer ( s, " <>=!" ) ; first = tok.nextToken () ; second = tok.nextToken () ; }
public Sequence estimatepupil(Sequence sequence, float _xySampling, float _zSampling, float _objNA, float _indexImmersion, int _lem, int _bgd, float _sigma, float _alpha, int _nIter) { Sequence pupil = new Sequence(); pupil.setName("Estimated Pupil"); pupil.setChannelName(0, "Amplitude"); pupil.setChannelName(1, "Phase"); Sequence psf3d = new Sequence(); psf3d.setName("Estimated PSF"); Sequence resizedSeq = new Sequence(); final int NSECTIONS = 4; int _w = sequence.getSizeX(); int _h = sequence.getSizeY(); int _z = sequence.getSizeZ(); double _lambdaObj = _lem/_indexImmersion; double _kObj = (2 * Math.PI)/_lambdaObj; double _rMax = (3 * 0.061 * _lambdaObj)/(_objNA * _xySampling); double _k0 = (2*Math.PI)/_lem; int leftPad = 0; int rightPad = 0; int topPad = 0; int botPad = 0; if(_w>_h) { int dh = _w-_h; _h = _w; if(Math.IEEEremainder(dh, 2)==0) { topPad = dh/2; botPad = dh/2; } else { topPad = (int) Math.ceil(dh/2); botPad = (int) Math.floor(dh/2); } } else { int dw = _h -_w; _w = _h; if(Math.IEEEremainder(dw, 2)==0) { leftPad = dw/2; rightPad = dw/2; } else { leftPad = (int) Math.ceil(dw/2); rightPad = (int) Math.floor(dw/2); } } for(int iz=0;iz<_z;iz++) { final RenderedOp renderedOp = BorderDescriptor.create(sequence.getImage(0, iz, 0), leftPad, rightPad, topPad, botPad, BorderExtender.createInstance(BorderExtender.BORDER_REFLECT), null); IcyBufferedImage resizedImage = IcyBufferedImage.createFrom(renderedOp.getAsBufferedImage()); resizedSeq.addImage(resizedImage); } final DoubleFFT_2D fftOp = new DoubleFFT_2D(_w, _h); double kSampling = 2*Math.PI/(_w*_xySampling); double _kMax = (2 * Math.PI * _objNA)/(_lambdaObj*kSampling); int hc = _h/2; int wc = _w/2; double[][] seqArray = new double[_z][_w*_h]; double[][] bgRemovedArray = new double[_z][_w*_h]; int cPlane = 0; double[] zMaxIntensity = new double[_z]; double maxIntensity=0; for(int iz = 0;iz<_z;iz++) { IcyBufferedImage zImage = sequence.getImage(0, iz, 0); zImage.updateComponentsBounds(true, true); zMaxIntensity[iz] = zImage.getComponentUserMaxValue(0); if(maxIntensity < zMaxIntensity[iz]) { cPlane = iz; maxIntensity = zMaxIntensity[iz]; } seqArray[iz] = Array1DUtil.arrayToDoubleArray(resizedSeq.getDataXY(0, iz, 0), false); for(int ix = 0;ix<_w;ix++) { for(int iy = 0;iy<_h;iy++) { bgRemovedArray[iz][ix + iy*_h] = seqArray[iz][ix + iy*_h]-_bgd; bgRemovedArray[iz][ix + iy*_h] = ((bgRemovedArray[iz][ix + iy*_h] < 0) ? 0 : bgRemovedArray[iz][ix + iy*_h]); } } } cPlane = cPlane+1; new AnnounceFrame("Detected focal plane at the " + cPlane + "th slice."); int[] selectedPlanes = new int[]{cPlane-15, cPlane-2, cPlane+2, cPlane+15}; double[] defocus = new double[NSECTIONS]; ArrayMath.subtract(selectedPlanes, cPlane, selectedPlanes); ArrayMath.multiply(Array1DUtil.arrayToDoubleArray(selectedPlanes, true), (double)_zSampling, defocus); IcyBufferedImage pupilImage = new IcyBufferedImage(_w, _h, 2, DataType.DOUBLE); double[] pupilReBuffer = pupilImage.getDataXYAsDouble(0); double[] pupilImBuffer = pupilImage.getDataXYAsDouble(1); IcyBufferedImage dpupilImage = new IcyBufferedImage(_w, _h, 2, DataType.DOUBLE); double[] dpupilReBuffer = dpupilImage.getDataXYAsDouble(0); double[] dpupilImBuffer = dpupilImage.getDataXYAsDouble(1); IcyBufferedImage ctheta = new IcyBufferedImage(_w, _h, 1, DataType.DOUBLE); double[] cthetaBuffer = ctheta.getDataXYAsDouble(0); IcyBufferedImage stheta = new IcyBufferedImage(_w, _h, 1, DataType.DOUBLE); double[] sthetaBuffer = stheta.getDataXYAsDouble(0); for(int x = 0; x < _w; x++) { for(int y = 0; y < _h; y++) { double kxy = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); pupilReBuffer[pupilImage.getOffset(x, y)] = ((kxy < _kMax) ? 1 : 0); pupilImBuffer[pupilImage.getOffset(x, y)] = 0; sthetaBuffer[x + y * _w] = Math.sin( kxy * kSampling / _kObj ); sthetaBuffer[x + y * _w] = (sthetaBuffer[x + y * _w]< 0) ? 0: sthetaBuffer[x + y * _w]; cthetaBuffer[x + y * _w] = Double.MIN_VALUE + Math.sqrt(1 - Math.pow(sthetaBuffer[x + y * _w], 2)); } } Sequence tpupil = new Sequence(); tpupil.addImage(pupilImage); addSequence(tpupil); double[] gaussianKernel = Kernels1D.CUSTOM_GAUSSIAN.createGaussianKernel1D(_sigma).getData(); double[][] tempPupil = new double[][]{ pupilReBuffer }; Convolution1D.convolve(tempPupil, _w, _h, gaussianKernel, gaussianKernel, null); System.arraycopy(tempPupil[0], 0, pupilReBuffer, 0, _w*_h); for(int n = 0; n<_nIter; n++) { IcyBufferedImage avgPupil = new IcyBufferedImage(_w, _h, 2, DataType.DOUBLE); double[] avgPupilReBuffer = avgPupil.getDataXYAsDouble(0); double[] avgPupilImBuffer = avgPupil.getDataXYAsDouble(1); for(int iz=0;iz<NSECTIONS;iz++) { for(int x = 0; x < _w; x++) { for(int y = 0; y < _h; y++) { dpupilReBuffer[x + y * _w] = pupilReBuffer[x + y * _w] * Math.cos((defocus[iz] * _k0 * cthetaBuffer[x + y * _w])); dpupilImBuffer[x + y * _w] = pupilReBuffer[x + y * _w] * Math.sin((defocus[iz] * _k0 * cthetaBuffer[x + y * _w])); } } double[] psf2d = dpupilImage.getDataCopyCXYAsDouble(); fftOp.complexForward(psf2d); IcyBufferedImage psfCentered = new IcyBufferedImage(_w, _h, 2, DataType.DOUBLE); double[] psfReBuffer = psfCentered.getDataXYAsDouble(0); double[] psfImBuffer = psfCentered.getDataXYAsDouble(1); psfCentered.beginUpdate(); try{ for(int x = 0; x < (wc+1); x++) { for(int y = 0; y < (hc+1); y++) { double r = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); psfReBuffer[x + y * _w] = psf2d[(((wc-x) + (hc-y) * _w)*2) + 0]; psfImBuffer[x + y * _w] = psf2d[(((wc-x) + (hc-y) * _w)*2) + 1]; double psf = Double.MIN_VALUE + Math.pow(psfReBuffer[x + y * _w], 2) + Math.pow(psfImBuffer[x + y * _w], 2); psfReBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfReBuffer[x + y * _w] * (1 - _alpha - (_alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf) ); psfImBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfImBuffer[x + y * _w] * (1 + _alpha - (_alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf) ); } for(int y = hc+1; y < _h; y++) { double r = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); psfReBuffer[x + y * _w] = psf2d[(((wc-x) + (y-hc) * _w)*2) + 0]; psfImBuffer[x + y * _w] = psf2d[(((wc-x) + (y-hc) * _w)*2) + 1]; double psf = Double.MIN_VALUE + Math.pow(psfReBuffer[x + y * _w], 2) + Math.pow(psfImBuffer[x + y * _w], 2); psfReBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfReBuffer[x + y * _w] * (1 - _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); psfImBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfImBuffer[x + y * _w] * (1 + _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); } } for(int x = (wc+1); x < _w; x++) { for(int y = 0; y < (hc+1); y++) { double r = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); psfReBuffer[x + y * _w] = psf2d[(((x-wc) + (hc-y) * _w)*2) + 0]; psfImBuffer[x + y * _w] = psf2d[(((x-wc) + (hc-y) * _w)*2) + 1]; double psf = Double.MIN_VALUE + Math.pow(psfReBuffer[x + y * _w], 2) + Math.pow(psfImBuffer[x + y * _w], 2); psfReBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfReBuffer[x + y * _w] * (1 - _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); psfImBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfImBuffer[x + y * _w] * (1 + _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); } for(int y = hc+1; y < _h; y++) { double r = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); psfReBuffer[x + y * _w] = psf2d[(((x-wc) + (y-hc) * _w)*2) + 0]; psfImBuffer[x + y * _w] = psf2d[(((x-wc) + (y-hc) * _w)*2) + 1]; double psf = Double.MIN_VALUE + Math.pow(psfReBuffer[x + y * _w], 2) + Math.pow(psfImBuffer[x + y * _w], 2); psfReBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfReBuffer[x + y * _w] * (1 - _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); psfImBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfImBuffer[x + y * _w] * (1 + _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); } } }finally { psfCentered.endUpdate(); } double[] pupilArray = psfCentered.getDataCopyCXYAsDouble(); fftOp.complexInverse(pupilArray, false); for(int x = 0; x < _w; x++) { for(int y = 0; y < _h; y++) { dpupilReBuffer[x + y * _w] = pupilArray[((x + y * _w) * 2) + 0] * Math.cos((defocus[iz] * _k0 * cthetaBuffer[x + y * _w])); dpupilImBuffer[x + y * _w] = pupilArray[((x + y * _w) * 2) + 1] * Math.sin((defocus[iz] * _k0 * cthetaBuffer[x + y * _w])); avgPupilReBuffer[x + y * _w] = avgPupilReBuffer[x + y * _w] + dpupilReBuffer[x + y * _w]; avgPupilImBuffer[x + y * _w] = avgPupilImBuffer[x + y * _w] + dpupilImBuffer[x + y * _w]; } } ArrayMath.divide(avgPupilReBuffer, NSECTIONS); ArrayMath.divide(avgPupilImBuffer, NSECTIONS); for(int x = 0; x < _w; x++) { for(int y = 0; y < _h; y++) { pupilReBuffer[x + y * _w] = avgPupilReBuffer[x + y * _w]; pupilImBuffer[x + y * _w] = avgPupilImBuffer[x + y * _w]; } } if(Math.IEEEremainder(n, 5) == 0) { tempPupil = new double[][]{ pupilReBuffer }; Convolution1D.convolve(tempPupil, _w, _h, gaussianKernel, gaussianKernel, null); System.arraycopy(tempPupil[0], 0, pupilReBuffer, 0, _w*_h); tempPupil = new double[][]{ pupilImBuffer }; Convolution1D.convolve(tempPupil, _w, _h, gaussianKernel, gaussianKernel, null); System.arraycopy(tempPupil[0], 0, pupilReBuffer, 0, _w*_h); } } } pupil.addImage(pupilImage); return pupil; }
public Sequence estimatepupil(Sequence sequence, float _xySampling, float _zSampling, float _objNA, float _indexImmersion, int _lem, int _bgd, float _sigma, float _alpha, int _nIter) { Sequence pupil = new Sequence(); pupil.setName("Estimated Pupil"); pupil.setChannelName(0, "Amplitude"); pupil.setChannelName(1, "Phase"); Sequence psf3d = new Sequence(); psf3d.setName("Estimated PSF"); Sequence resizedSeq = new Sequence(); final int NSECTIONS = 4; int _w = sequence.getSizeX(); int _h = sequence.getSizeY(); int _z = sequence.getSizeZ(); double _lambdaObj = _lem/_indexImmersion; double _kObj = (2 * Math.PI)/_lambdaObj; double _rMax = (3 * 0.061 * _lambdaObj)/(_objNA * _xySampling); double _k0 = (2*Math.PI)/_lem; int leftPad = 0; int rightPad = 0; int topPad = 0; int botPad = 0; if(_w>_h) { int dh = _w-_h; _h = _w; if(Math.IEEEremainder(dh, 2)==0) { topPad = dh/2; botPad = dh/2; } else { topPad = (int) Math.ceil(dh/2); botPad = (int) Math.floor(dh/2); } } else { int dw = _h -_w; _w = _h; if(Math.IEEEremainder(dw, 2)==0) { leftPad = dw/2; rightPad = dw/2; } else { leftPad = (int) Math.ceil(dw/2); rightPad = (int) Math.floor(dw/2); } } for(int iz=0;iz<_z;iz++) { final RenderedOp renderedOp = BorderDescriptor.create(sequence.getImage(0, iz, 0), leftPad, rightPad, topPad, botPad, BorderExtender.createInstance(BorderExtender.BORDER_REFLECT), null); IcyBufferedImage resizedImage = IcyBufferedImage.createFrom(renderedOp.getAsBufferedImage()); resizedSeq.addImage(resizedImage); } final DoubleFFT_2D fftOp = new DoubleFFT_2D(_w, _h); double kSampling = 2*Math.PI/(_w*_xySampling); double _kMax = (2 * Math.PI * _objNA)/(_lambdaObj*kSampling); int hc = _h/2; int wc = _w/2; double[][] seqArray = new double[_z][_w*_h]; double[][] bgRemovedArray = new double[_z][_w*_h]; int cPlane = 0; double[] zMaxIntensity = new double[_z]; double maxIntensity=0; for(int iz = 0;iz<_z;iz++) { IcyBufferedImage zImage = sequence.getImage(0, iz, 0); zImage.updateComponentsBounds(true, true); zMaxIntensity[iz] = zImage.getComponentUserMaxValue(0); if(maxIntensity < zMaxIntensity[iz]) { cPlane = iz; maxIntensity = zMaxIntensity[iz]; } seqArray[iz] = Array1DUtil.arrayToDoubleArray(resizedSeq.getDataXY(0, iz, 0), false); for(int ix = 0;ix<_w;ix++) { for(int iy = 0;iy<_h;iy++) { bgRemovedArray[iz][ix + iy*_h] = seqArray[iz][ix + iy*_h]-_bgd; bgRemovedArray[iz][ix + iy*_h] = ((bgRemovedArray[iz][ix + iy*_h] < 0) ? 0 : bgRemovedArray[iz][ix + iy*_h]); } } } cPlane = cPlane+1; new AnnounceFrame("Detected focal plane at the " + cPlane + "th slice."); int[] selectedPlanes = new int[]{cPlane-15, cPlane-2, cPlane+2, cPlane+15}; double[] defocus = new double[NSECTIONS]; ArrayMath.subtract(selectedPlanes, cPlane, selectedPlanes); ArrayMath.multiply(Array1DUtil.arrayToDoubleArray(selectedPlanes, true), (double)_zSampling, defocus); IcyBufferedImage pupilImage = new IcyBufferedImage(_w, _h, 2, DataType.DOUBLE); double[] pupilReBuffer = pupilImage.getDataXYAsDouble(0); double[] pupilImBuffer = pupilImage.getDataXYAsDouble(1); IcyBufferedImage dpupilImage = new IcyBufferedImage(_w, _h, 2, DataType.DOUBLE); double[] dpupilReBuffer = dpupilImage.getDataXYAsDouble(0); double[] dpupilImBuffer = dpupilImage.getDataXYAsDouble(1); IcyBufferedImage ctheta = new IcyBufferedImage(_w, _h, 1, DataType.DOUBLE); double[] cthetaBuffer = ctheta.getDataXYAsDouble(0); IcyBufferedImage stheta = new IcyBufferedImage(_w, _h, 1, DataType.DOUBLE); double[] sthetaBuffer = stheta.getDataXYAsDouble(0); for(int x = 0; x < _w; x++) { for(int y = 0; y < _h; y++) { double kxy = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); pupilReBuffer[pupilImage.getOffset(x, y)] = ((kxy < _kMax) ? 1 : 0); pupilImBuffer[pupilImage.getOffset(x, y)] = 0; sthetaBuffer[x + y * _w] = Math.sin( kxy * kSampling / _kObj ); sthetaBuffer[x + y * _w] = (sthetaBuffer[x + y * _w]< 0) ? 0: sthetaBuffer[x + y * _w]; cthetaBuffer[x + y * _w] = Double.MIN_VALUE + Math.sqrt(1 - Math.pow(sthetaBuffer[x + y * _w], 2)); } } Sequence tpupil = new Sequence(); tpupil.addImage(pupilImage); addSequence(tpupil); double[] gaussianKernel = Kernels1D.CUSTOM_GAUSSIAN.createGaussianKernel1D(_sigma).getData(); double[][] tempPupil = new double[][]{ pupilReBuffer }; Convolution1D.convolve(tempPupil, _w, _h, gaussianKernel, gaussianKernel, null); System.arraycopy(tempPupil[0], 0, pupilReBuffer, 0, _w*_h); for(int n = 0; n<_nIter; n++) { IcyBufferedImage avgPupil = new IcyBufferedImage(_w, _h, 2, DataType.DOUBLE); double[] avgPupilReBuffer = avgPupil.getDataXYAsDouble(0); double[] avgPupilImBuffer = avgPupil.getDataXYAsDouble(1); for(int iz=0;iz<NSECTIONS;iz++) { for(int x = 0; x < _w; x++) { for(int y = 0; y < _h; y++) { dpupilReBuffer[x + y * _w] = pupilReBuffer[x + y * _w] * Math.cos((defocus[iz] * _k0 * cthetaBuffer[x + y * _w])); dpupilImBuffer[x + y * _w] = pupilReBuffer[x + y * _w] * Math.sin((defocus[iz] * _k0 * cthetaBuffer[x + y * _w])); } } double[] psf2d = dpupilImage.getDataCopyCXYAsDouble(); fftOp.complexForward(psf2d); IcyBufferedImage psfCentered = new IcyBufferedImage(_w, _h, 2, DataType.DOUBLE); double[] psfReBuffer = psfCentered.getDataXYAsDouble(0); double[] psfImBuffer = psfCentered.getDataXYAsDouble(1); psfCentered.beginUpdate(); try{ for(int x = 0; x < (wc+1); x++) { for(int y = 0; y < (hc+1); y++) { double r = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); psfReBuffer[x + y * _w] = psf2d[(((wc-x) + (hc-y) * _w)*2) + 0]; psfImBuffer[x + y * _w] = psf2d[(((wc-x) + (hc-y) * _w)*2) + 1]; double psf = Double.MIN_VALUE + Math.pow(psfReBuffer[x + y * _w], 2) + Math.pow(psfImBuffer[x + y * _w], 2); psfReBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfReBuffer[x + y * _w] * (1 - _alpha - (_alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf) ); psfImBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfImBuffer[x + y * _w] * (1 + _alpha - (_alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf) ); } for(int y = hc+1; y < _h; y++) { double r = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); psfReBuffer[x + y * _w] = psf2d[(((wc-x) + (_h+ hc-y) * _w)*2) + 0]; psfImBuffer[x + y * _w] = psf2d[(((wc-x) + (_h+ hc-y) * _w)*2) + 1]; double psf = Double.MIN_VALUE + Math.pow(psfReBuffer[x + y * _w], 2) + Math.pow(psfImBuffer[x + y * _w], 2); psfReBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfReBuffer[x + y * _w] * (1 - _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); psfImBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfImBuffer[x + y * _w] * (1 + _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); } } for(int x = (wc+1); x < _w; x++) { for(int y = 0; y < (hc+1); y++) { double r = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); psfReBuffer[x + y * _w] = psf2d[(((_w+wc-x) + (hc-y) * _w)*2) + 0]; psfImBuffer[x + y * _w] = psf2d[(((_w+wc-x) + (hc-y) * _w)*2) + 1]; double psf = Double.MIN_VALUE + Math.pow(psfReBuffer[x + y * _w], 2) + Math.pow(psfImBuffer[x + y * _w], 2); psfReBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfReBuffer[x + y * _w] * (1 - _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); psfImBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfImBuffer[x + y * _w] * (1 + _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); } for(int y = hc+1; y < _h; y++) { double r = Math.sqrt( Math.pow(x-wc, 2) + Math.pow(y-hc, 2) ); psfReBuffer[x + y * _w] = psf2d[(((_w+wc-x) + (_h+ hc-y) * _w)*2) + 0]; psfImBuffer[x + y * _w] = psf2d[(((_w+wc-x) + (_h+ hc-y) * _w)*2) + 1]; double psf = Double.MIN_VALUE + Math.pow(psfReBuffer[x + y * _w], 2) + Math.pow(psfImBuffer[x + y * _w], 2); psfReBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfReBuffer[x + y * _w] * (1 - _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); psfImBuffer[x + y * _w] = ((r < _rMax) ? 1 : 0) * psfImBuffer[x + y * _w] * (1 + _alpha - _alpha * bgRemovedArray[cPlane + selectedPlanes[iz]][x + y * _w]/psf ); } } }finally { psfCentered.endUpdate(); } double[] pupilArray = psfCentered.getDataCopyCXYAsDouble(); fftOp.complexInverse(pupilArray, false); for(int x = 0; x < _w; x++) { for(int y = 0; y < _h; y++) { dpupilReBuffer[x + y * _w] = pupilArray[((x + y * _w) * 2) + 0] * Math.cos((defocus[iz] * _k0 * cthetaBuffer[x + y * _w])); dpupilImBuffer[x + y * _w] = pupilArray[((x + y * _w) * 2) + 1] * Math.sin((defocus[iz] * _k0 * cthetaBuffer[x + y * _w])); avgPupilReBuffer[x + y * _w] = avgPupilReBuffer[x + y * _w] + dpupilReBuffer[x + y * _w]; avgPupilImBuffer[x + y * _w] = avgPupilImBuffer[x + y * _w] + dpupilImBuffer[x + y * _w]; } } ArrayMath.divide(avgPupilReBuffer, NSECTIONS); ArrayMath.divide(avgPupilImBuffer, NSECTIONS); for(int x = 0; x < _w; x++) { for(int y = 0; y < _h; y++) { pupilReBuffer[x + y * _w] = avgPupilReBuffer[x + y * _w]; pupilImBuffer[x + y * _w] = avgPupilImBuffer[x + y * _w]; } } if(Math.IEEEremainder(n, 5) == 0) { tempPupil = new double[][]{ pupilReBuffer }; Convolution1D.convolve(tempPupil, _w, _h, gaussianKernel, gaussianKernel, null); System.arraycopy(tempPupil[0], 0, pupilReBuffer, 0, _w*_h); tempPupil = new double[][]{ pupilImBuffer }; Convolution1D.convolve(tempPupil, _w, _h, gaussianKernel, gaussianKernel, null); System.arraycopy(tempPupil[0], 0, pupilReBuffer, 0, _w*_h); } } } pupil.addImage(pupilImage); return pupil; }
public void testMultitplePrefixes() throws Exception { System.out.println("*** testMultitplePrefixes ***"); Assembler assmbler = new Assembler(); SystemInstance.get().setProperty("openejb.altdd.prefix", "footest, test"); ConfigurationFactory factory = new ConfigurationFactory(); URL resource = AltDDPrefixTest.class.getClassLoader().getResource("altddapp2"); File file = URLs.toFile(resource); AppInfo appInfo = factory.configureApplication(file); assertNotNull(appInfo); assertEquals(1, appInfo.ejbJars.size()); EjbJarInfo ejbJar = appInfo.ejbJars.get(0); assertEquals("EjbJar.enterpriseBeans", 1, ejbJar.enterpriseBeans.size()); assertEquals("EjbJar.interceptors.size()", 1, ejbJar.interceptors.size()); assertEquals("EjbJar.enterpriseBeans.get(0).jndiEnc.envEntries.size()", 4, ejbJar.enterpriseBeans.get(0).jndiEnc.envEntries.size()); }
public void testMultitplePrefixes() throws Exception { System.out.println("*** testMultitplePrefixes ***"); Assembler assmbler = new Assembler(); SystemInstance.get().setProperty("openejb.altdd.prefix", "footest, test"); ConfigurationFactory factory = new ConfigurationFactory(); URL resource = AltDDPrefixTest.class.getClassLoader().getResource("altddapp2"); File file = URLs.toFile(resource); AppInfo appInfo = factory.configureApplication(file); assertNotNull(appInfo); assertEquals(1, appInfo.ejbJars.size()); EjbJarInfo ejbJar = appInfo.ejbJars.get(0); assertEquals("EjbJar.enterpriseBeans", 1, ejbJar.enterpriseBeans.size()); assertEquals("EjbJar.interceptors.size()", 1, ejbJar.interceptors.size()); assertEquals("EjbJar.enterpriseBeans.get(0).jndiEnc.envEntries.size()", 5, ejbJar.enterpriseBeans.get(0).jndiEnc.envEntries.size()); }
public void testParser() { AcceleratorParser parser = new AcceleratorParser(new File("src/test/resources/sample")); parser.parseAccelerator(); assertNotNull(parser.getAcceleratorComponents()); assertEquals(2, parser.getAcceleratorComponents().size()); }
public void testParser() { AcceleratorParser parser = new AcceleratorParser(new File("src/test/resources/sample")); parser.parseAccelerator(); assertNotNull(parser.getAcceleratorComponents()); assertEquals(2, parser.getAcceleratorComponents().getAllComponents().length); }
public static Collection<RoEvoNode> describeRO(URI sparqlEndpointURI, URI researchObjectURI) throws IOException, URISyntaxException { OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM); QueryExecution x = QueryExecutionFactory.sparqlService(sparqlEndpointURI.toString(), MyQueryFactory.getResourceClass(researchObjectURI.toString())); x.execConstruct(model); Query query = null; Individual i = model.getIndividual(researchObjectURI.toString()); if (i != null) { if (i.hasRDFType(Vocab.ROEVO_SNAPSHOT_RO)) { query = MyQueryFactory.getSnapshotEvolution(researchObjectURI.toString()); } else if (i.hasRDFType(Vocab.ROEVO_LIVE_RO)) { query = MyQueryFactory.getLiveEvolution(researchObjectURI.toString()); } else if (i.hasRDFType(Vocab.ROEVO_ARCHIVED_RO)) { query = MyQueryFactory.getArchivedEvolution(researchObjectURI.toString()); } } if (query == null) { query = MyQueryFactory.getSnapshotEvolution(researchObjectURI.toString()); } x = QueryExecutionFactory.sparqlService(sparqlEndpointURI.toString(), query); x.execConstruct(model); Map<URI, RoEvoNode> nodes = new HashMap<>(); StmtIterator it = model.listStatements(); while (it.hasNext()) { Statement statement = it.next(); URI subjectURI = new URI(statement.getSubject().getURI()); if (!nodes.containsKey(subjectURI)) { nodes.put(subjectURI, new RoEvoNode(subjectURI)); } RoEvoNode node = nodes.get(subjectURI); Property property = statement.getPredicate(); RDFNode object = statement.getObject(); if (property.equals(RDFS.label)) { node.setLabel(object.asLiteral().getString()); } else if (property.equals(Vocab.ROEVO_IS_SNAPSHOT_OF) && object.isURIResource()) { node.getItsLiveROs().add(createNode(nodes, object.asResource().getURI())); } else if (property.equals(Vocab.ROEVO_HAS_PREVIOUS_VERSION) && object.isURIResource()) { node.getPreviousSnapshots().add(createNode(nodes, object.asResource().getURI())); } else if (property.equals(Vocab.ROEVO_DERIVED_FROM) && object.isURIResource()) { RoEvoNode source = createNode(nodes, object.asResource().getURI()); node.getDerivedResources().add(source); source.setEvoClassModifier(EvoClassModifier.SOURCE); node.setEvoClassModifier(EvoClassModifier.FORK); } else if (property.equals(RDF.type)) { if (object.equals(Vocab.RO_RESEARCH_OBJECT)) { node.setResearchObject(true); } else if (object.equals(Vocab.ROEVO_SNAPSHOT_RO)) { node.setResearchObject(true); node.setEvoClass(EvoClass.SNAPSHOT); } else if (object.equals(Vocab.ROEVO_LIVE_RO)) { node.setResearchObject(true); node.setEvoClass(EvoClass.LIVE); } else if (object.equals(Vocab.ROEVO_ARCHIVED_RO)) { node.setResearchObject(true); node.setEvoClass(EvoClass.ARCHIVED); } } } return nodes.values(); }
public static Collection<RoEvoNode> describeRO(URI sparqlEndpointURI, URI researchObjectURI) throws IOException, URISyntaxException { OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM); QueryExecution x = QueryExecutionFactory.sparqlService(sparqlEndpointURI.toString(), MyQueryFactory.getResourceClass(researchObjectURI.toString())); x.execConstruct(model); Query query = null; Individual i = model.getIndividual(researchObjectURI.toString()); if (i != null) { if (i.hasRDFType(Vocab.ROEVO_SNAPSHOT_RO)) { query = MyQueryFactory.getSnapshotEvolution(researchObjectURI.toString()); } else if (i.hasRDFType(Vocab.ROEVO_LIVE_RO)) { query = MyQueryFactory.getLiveEvolution(researchObjectURI.toString()); } else if (i.hasRDFType(Vocab.ROEVO_ARCHIVED_RO)) { query = MyQueryFactory.getArchivedEvolution(researchObjectURI.toString()); } } if (query == null) { query = MyQueryFactory.getSnapshotEvolution(researchObjectURI.toString()); } x = QueryExecutionFactory.sparqlService(sparqlEndpointURI.toString(), query); x.execConstruct(model); Map<URI, RoEvoNode> nodes = new HashMap<>(); StmtIterator it = model.listStatements(); while (it.hasNext()) { Statement statement = it.next(); URI subjectURI = new URI(statement.getSubject().getURI()); if (!nodes.containsKey(subjectURI)) { nodes.put(subjectURI, new RoEvoNode(subjectURI)); } RoEvoNode node = nodes.get(subjectURI); Property property = statement.getPredicate(); RDFNode object = statement.getObject(); if (property.equals(RDFS.label)) { node.setLabel(object.asLiteral().getString()); } else if ((property.equals(Vocab.ROEVO_IS_SNAPSHOT_OF) || property.equals(Vocab.ROEVO_IS_SNAPSHOT_OF .getModel().createProperty("http://purl.org/wf4ever/roevo#isArchiveOf")) && object.isURIResource())) { node.getItsLiveROs().add(createNode(nodes, object.asResource().getURI())); } else if (property.equals(Vocab.ROEVO_HAS_PREVIOUS_VERSION) && object.isURIResource()) { node.getPreviousSnapshots().add(createNode(nodes, object.asResource().getURI())); } else if (property.equals(Vocab.ROEVO_DERIVED_FROM) && object.isURIResource()) { RoEvoNode source = createNode(nodes, object.asResource().getURI()); node.getDerivedResources().add(source); source.setEvoClassModifier(EvoClassModifier.SOURCE); node.setEvoClassModifier(EvoClassModifier.FORK); } else if (property.equals(RDF.type)) { if (object.equals(Vocab.RO_RESEARCH_OBJECT)) { node.setResearchObject(true); } else if (object.equals(Vocab.ROEVO_SNAPSHOT_RO)) { node.setResearchObject(true); node.setEvoClass(EvoClass.SNAPSHOT); } else if (object.equals(Vocab.ROEVO_LIVE_RO)) { node.setResearchObject(true); node.setEvoClass(EvoClass.LIVE); } else if (object.equals(Vocab.ROEVO_ARCHIVED_RO)) { node.setResearchObject(true); node.setEvoClass(EvoClass.ARCHIVED); } } } return nodes.values(); }
private void disablePreference(){ String value = preferences.getProjectPreference(file.getProject(), PROBLEM_ID); if(!SeverityPreferences.IGNORE.equals(value)){ IEclipsePreferences projectPreferences = preferences.getProjectPreferences(file.getProject()); String projectValue = null; if(projectPreferences != null){ projectValue = projectPreferences.get(PROBLEM_ID, null); } if(projectValue != null){ MessageDialog dialog = new MessageDialog(getShell(), label, null, "Do you want to disable 'Unsupported @SuppressWarnings' error/warning", MessageDialog.QUESTION_WITH_CANCEL, new String[]{"Cancel", "Disable"}, 0); int result = dialog.open(); if(result == 1){ IEclipsePreferences ePrefs = preferences.getProjectPreferences(file.getProject()); ePrefs.put(PROBLEM_ID, SeverityPreferences.IGNORE); try { ePrefs.flush(); } catch (BackingStoreException e) { CommonUIPlugin.getDefault().logError(e); } } }else{ MessageDialog dialog = new MessageDialog(getShell(), label, null, "Do you want to disable 'Unsupported @SuppressWarnings' error/warning on the Workspace or only on the project '"+file.getProject().getName()+"'", MessageDialog.QUESTION_WITH_CANCEL, new String[]{"Cancel", "Workspace", file.getProject().getName()}, 0); int result = dialog.open(); if(result == 1){ IEclipsePreferences ePrefs = preferences.getInstancePreferences(); ePrefs.put(PROBLEM_ID, SeverityPreferences.IGNORE); try { ePrefs.flush(); } catch (BackingStoreException e) { CommonUIPlugin.getDefault().logError(e); } }else if(result == 2){ IEclipsePreferences ePrefs = preferences.getProjectPreferences(file.getProject()); ePrefs.put(PROBLEM_ID, SeverityPreferences.IGNORE); try { ePrefs.flush(); } catch (BackingStoreException e) { CommonUIPlugin.getDefault().logError(e); } } } } }
private void disablePreference(){ String value = preferences.getProjectPreference(file.getProject(), PROBLEM_ID); if(!SeverityPreferences.IGNORE.equals(value)){ IEclipsePreferences projectPreferences = preferences.getProjectPreferences(file.getProject()); String projectValue = null; if(projectPreferences != null){ projectValue = projectPreferences.get(PROBLEM_ID, null); } if(projectValue != null){ MessageDialog dialog = new MessageDialog(getShell(), label, null, "This quick fix uses warning names that are not supported by Java Validator and will cause \"Unsupported @SuppressWarning\" problem message\n\n"+ "Do you want to disable 'Unsupported @SuppressWarnings' validation", MessageDialog.QUESTION_WITH_CANCEL, new String[]{"Cancel", "Disable"}, 0); int result = dialog.open(); if(result == 1){ IEclipsePreferences ePrefs = preferences.getProjectPreferences(file.getProject()); ePrefs.put(PROBLEM_ID, SeverityPreferences.IGNORE); try { ePrefs.flush(); } catch (BackingStoreException e) { CommonUIPlugin.getDefault().logError(e); } } }else{ MessageDialog dialog = new MessageDialog(getShell(), label, null, "This quick fix uses warning names that are not supported by Java Validator and will cause \"Unsupported @SuppressWarning\" problem message\n\n"+ "Do you want to disable 'Unsupported @SuppressWarnings' validation on the Workspace or only on the project '"+file.getProject().getName()+"'", MessageDialog.QUESTION_WITH_CANCEL, new String[]{"Cancel", "Workspace", file.getProject().getName()}, 0); int result = dialog.open(); if(result == 1){ IEclipsePreferences ePrefs = preferences.getInstancePreferences(); ePrefs.put(PROBLEM_ID, SeverityPreferences.IGNORE); try { ePrefs.flush(); } catch (BackingStoreException e) { CommonUIPlugin.getDefault().logError(e); } }else if(result == 2){ IEclipsePreferences ePrefs = preferences.getProjectPreferences(file.getProject()); ePrefs.put(PROBLEM_ID, SeverityPreferences.IGNORE); try { ePrefs.flush(); } catch (BackingStoreException e) { CommonUIPlugin.getDefault().logError(e); } } } } }
public Map<String, Boolean> complete(ParameterDescriptor<?> parameter, String prefix) throws Exception { if (parameter.getAnnotation() instanceof Path) { String path = (String)getProperty("currentPath"); Session session = (Session)getProperty("session"); if (session != null) { Node relative = null; if (prefix.length() == 0 || prefix.charAt(0) != '/') { if (path != null) { Item item = session.getItem(path); if (item instanceof Node) { relative = (Node)item; } } } else { relative = session.getRootNode(); prefix = prefix.substring(1); } if (relative != null) { for (int index = prefix.indexOf('/');index != -1;index = prefix.indexOf('/')) { String name = prefix.substring(0, index); if (relative.hasNode(name)) { relative = relative.getNode(name); prefix = prefix.substring(index + 1); } else { return Collections.emptyMap(); } } } Map<String, Boolean> completions = new HashMap<String, Boolean>(); for (NodeIterator i = relative.getNodes(prefix + '*');i.hasNext();) { Node child = i.nextNode(); String suffix = child.getName().substring(prefix.length()); if (child.hasNodes()) { completions.put(suffix + '/', false); } else { completions.put(suffix, true); } } return completions; } } return Collections.emptyMap(); }
public Map<String, Boolean> complete(ParameterDescriptor<?> parameter, String prefix) throws Exception { if (parameter.getJavaValueType() == Path.class) { Path path = (Path)getProperty("currentPath"); Session session = (Session)getProperty("session"); if (session != null) { Node relative = null; if (prefix.length() == 0 || prefix.charAt(0) != '/') { if (path != null) { Item item = session.getItem(path.getString()); if (item instanceof Node) { relative = (Node)item; } } } else { relative = session.getRootNode(); prefix = prefix.substring(1); } if (relative != null) { for (int index = prefix.indexOf('/');index != -1;index = prefix.indexOf('/')) { String name = prefix.substring(0, index); if (relative.hasNode(name)) { relative = relative.getNode(name); prefix = prefix.substring(index + 1); } else { return Collections.emptyMap(); } } } Map<String, Boolean> completions = new HashMap<String, Boolean>(); for (NodeIterator i = relative.getNodes(prefix + '*');i.hasNext();) { Node child = i.nextNode(); String suffix = child.getName().substring(prefix.length()); if (child.hasNodes()) { completions.put(suffix + '/', false); } else { completions.put(suffix, true); } } return completions; } } return Collections.emptyMap(); }
private void runDocEdit() { docTableGUI.setVisible(false); currentDoc.setVisible(true); try { for (String line = serverInput.readLine(); line!=null; line=serverInput.readLine()) { if (line.startsWith("exiteddoc ")) { String[] lineSplit = line.split(" "); if (lineSplit.length == 3){ String userName = lineSplit[1]; updateDocTable(); if(this.userName.equals(userName)){ Thread newThread = new Thread(new Runnable() { @Override public void run() { runDocTable(); } }); newThread.start(); return ; } }else{ throw new RuntimeException("Invalid format"); } } else if (line.startsWith("corrected")) { String[] lineSplit = line.split("\\|"); if (lineSplit.length == 4) { String userName = lineSplit[1]; String docName = lineSplit[2]; String newContent = lineSplit[3]; if (this.userName.equals(userName)) { if (currentDoc.getName().equals(docName)) { currentDoc.resetText(newContent); } } } } else if (line.startsWith("changed")) { String[] lineSplit = line.split("\\|"); if (lineSplit.length == 8) { String userName = lineSplit[1]; String docName = lineSplit[2]; String change = lineSplit[3]; int position = Integer.valueOf(lineSplit[4]); String[] colors = lineSplit[7].split(","); Color color = new Color(Integer.parseInt(colors[0]), Integer.parseInt(colors[1]), Integer.parseInt(colors[2])); int version = Integer.valueOf(lineSplit[6]); change = change.replace("\t", "\n"); if (currentDoc.getName().equals(docName)) { if (! this.userName.equals(userName)) { currentDoc.insertContent(change, position, version, color); } } } else if (lineSplit.length == 6) { String userName = lineSplit[1]; String docName = lineSplit[2]; int position = Integer.valueOf(lineSplit[3]); int length = Integer.valueOf(lineSplit[4]); int version = Integer.valueOf(lineSplit[5]); if (currentDoc.getName().equals(docName)) { if (! this.userName.equals(userName)) { currentDoc.deleteContent(position,length, version); } } } } else if (line.startsWith("update")) { String[] lineSplit = line.split("\\|"); if (lineSplit.length == 4) { String docName = lineSplit[1]; String collaboratorNames = lineSplit[2]; String colors = lineSplit[3]; System.out.println(colors); if (currentDoc.getName().equals(docName)) { currentDoc.updateCollaborators(collaboratorNames, colors); } } else{ System.out.println("Invalid format"); } } } } catch (IOException e) { throw new RuntimeException("IO Exception encountered"); } }
private void runDocEdit() { docTableGUI.setVisible(false); currentDoc.setVisible(true); try { for (String line = serverInput.readLine(); line!=null; line=serverInput.readLine()) { if (line.startsWith("exiteddoc ")) { String[] lineSplit = line.split(" "); if (lineSplit.length == 3){ String userName = lineSplit[1]; updateDocTable(); if(this.userName.equals(userName)){ Thread newThread = new Thread(new Runnable() { @Override public void run() { runDocTable(); } }); newThread.start(); return ; } }else{ throw new RuntimeException("Invalid format"); } } else if (line.startsWith("corrected")) { String[] lineSplit = line.split("\\|"); if (lineSplit.length == 4) { String userName = lineSplit[1]; String docName = lineSplit[2]; String newContent = lineSplit[3]; newContent = newContent.replace("\t", "\n"); if (this.userName.equals(userName)) { if (currentDoc.getName().equals(docName)) { currentDoc.resetText(newContent); } } } } else if (line.startsWith("changed")) { String[] lineSplit = line.split("\\|"); if (lineSplit.length == 8) { String userName = lineSplit[1]; String docName = lineSplit[2]; String change = lineSplit[3]; int position = Integer.valueOf(lineSplit[4]); String[] colors = lineSplit[7].split(","); Color color = new Color(Integer.parseInt(colors[0]), Integer.parseInt(colors[1]), Integer.parseInt(colors[2])); int version = Integer.valueOf(lineSplit[6]); change = change.replace("\t", "\n"); if (currentDoc.getName().equals(docName)) { if (! this.userName.equals(userName)) { currentDoc.insertContent(change, position, version, color); } } } else if (lineSplit.length == 6) { String userName = lineSplit[1]; String docName = lineSplit[2]; int position = Integer.valueOf(lineSplit[3]); int length = Integer.valueOf(lineSplit[4]); int version = Integer.valueOf(lineSplit[5]); if (currentDoc.getName().equals(docName)) { if (! this.userName.equals(userName)) { currentDoc.deleteContent(position,length, version); } } } } else if (line.startsWith("update")) { String[] lineSplit = line.split("\\|"); if (lineSplit.length == 4) { String docName = lineSplit[1]; String collaboratorNames = lineSplit[2]; String colors = lineSplit[3]; System.out.println(colors); if (currentDoc.getName().equals(docName)) { currentDoc.updateCollaborators(collaboratorNames, colors); } } else{ System.out.println("Invalid format"); } } } } catch (IOException e) { throw new RuntimeException("IO Exception encountered"); } }